text:
#include <algorithm>
#include <iostream>
#include <sstream>

#include <tiramisu/debug.h>
#include <tiramisu/core.h>
#include <tiramisu/type.h>
#include <tiramisu/expr.h>
#include <Halide.h>

using namespace Halide;
using namespace Halide::Internal;

using std::string;
using std::map;
using std::set;
using std::vector;

namespace tiramisu
{

string halide_type_to_tiramisu_type_str(Type type)
{
    if (type.is_uint())
    {
        if (type.bits() == 8)
        {
            return "tiramisu::p_uint8";
        }
        else if (type.bits() == 16)
        {
            return "tiramisu::p_uint16";
        }
        else if (type.bits() == 32)
        {
            return "tiramisu::p_uint32";
        }
        else
        {
            return "tiramisu::p_uint64";
        }
    }
    else if (type.is_int())
    {
        if (type.bits() == 8)
        {
            return "tiramisu::p_int8";
        }
        else if (type.bits() == 16)
        {
            return "tiramisu::p_int16";
        }
        else if (type.bits() == 32)
        {
            return "tiramisu::p_int32";
        }
        else
        {
            return "tiramisu::p_int64";
        }
    }
    else if (type.is_float())
    {
        if (type.bits() == 32)
        {
            return "tiramisu::p_float32";
        }
        else if (type.bits() == 64)
        {
            return "tiramisu::p_float64";
        }
        else
        {
            tiramisu::error("Floats other than 32 and 64 bits are not suppored in Tiramisu.", true);
        }
    }
    else if (type.is_bool())
    {
        return "tiramisu::p_boolean";
    }
    else
    {
        tiramisu::error("Halide type cannot be translated to Tiramisu type.", true);
    }
    return "tiramisu::p_none";
}

namespace
{

std::string to_string(const std::vector<Expr> &v)
{
    std::ostringstream ss;
    ss << "[";
    for (size_t i = 0; i < v.size(); ++i)
    {
        ss << v[i];
        if (i != v.size() - 1)
        {
            ss << ", ";
        }
    }
    ss << "]";
    return ss.str();
}

class HalideToC : public IRVisitor
{
private:
    const vector<Function> &outputs;
    const map<string, Function> &env;
    const set<string> &output_buffers;
    string func; // Represent one Halide pipeline
    Scope<Expr> &scope; // Scope of the variables

    set<string> temporary_buffers;

    void error() const
    {
        tiramisu::error("Can't convert to tiramisu expr.", true);
    }

    void push_loop_dim(const For *op)
    {
        loop_dims.push_back({op->name, op->min, op->extent});
    }

    void pop_loop_dim()
    {
        loop_dims.pop_back();
    }

    string get_loop_bound_vars() const
    {
        std::ostringstream ss;
        ss << "[";
        for (size_t i = 0; i < loop_dims.size(); ++i)
        {
            ss << loop_dims[i].min << ", " << loop_dims[i].extent;
            if (i != loop_dims.size() - 1)
            {
                ss << ", ";
            }
        }
        ss << "]";
        return ss.str();
    }

    string get_loop_bounds() const
    {
        std::ostringstream ss;
        ss << "(";
        for (size_t i = 0; i < loop_dims.size(); ++i)
        {
            ss << loop_dims[i].to_string();
            if (i != loop_dims.size() - 1)
            {
                ss << ") and (";
            }
        }
        ss << ")";
        return ss.str();
    }

    void define_constant(const string &name, Expr value);

public:
    set<string> computation_list;
    set<string> constant_list;

    struct Loop
    {
        std::string name;
        Expr min, extent;

        string to_string() const
        {
            std::ostringstream ss;
            Expr max = simplify(min + extent - 1);
            ss << min << " <= " << name << " <= " << max;
            return ss.str();
        }
    };

    vector<Loop> loop_dims;

    HalideToC(Scope<Expr> &s,
              const vector<Function> &outputs,
              const map<string, Function> &env,
              const set<string> &output_buffers,
              const string &f,
              std::ostream &ss)
        : outputs(outputs), env(env), output_buffers(output_buffers), func(f), scope(s), stream(ss),
          indent(0)
    {
        ss.setf(std::ios::fixed, std::ios::floatfield);
    }

    void print(Expr e)
    {
        assert(e.defined() && "HalideToC can't convert undefined expr\n");
        // For now, substitute in all lets to make life easier (does not substitute in lets in stmt though)
        e = substitute_in_all_lets(e);
        e.accept(this);
    }

    void print(Stmt s)
    {
        assert(s.defined() && "HalideToC can't convert undefined stmt\n");
        // For now, substitute in all lets to make life easier (does not substitute in lets in stmt though)
        s = substitute_in_all_lets(s);
        s.accept(this);
    }

protected:
    /** The stream we're outputting on */
    std::ostream &stream;

    /** The current indentation level, useful for pretty-printing
     * statements */
    int indent;

    /** Emit spaces according to the current indentation level */
    void do_indent();

    void visit(const IntImm *);
    void visit(const UIntImm *);
    void visit(const FloatImm *);
    void visit(const Cast *);
    void visit(const Variable *);
    void visit(const Add *);
    void visit(const Sub *);
    void visit(const Mul *);
    void visit(const Div *);
    void visit(const Mod *);
    void visit(const Min *);
    void visit(const Max *);
    void visit(const EQ *);
    void visit(const NE *);
    void visit(const LT *);
    void visit(const LE *);
    void visit(const GT *);
    void visit(const GE *);
    void visit(const And *);
    void visit(const Or *);
    void visit(const Not *);
    void visit(const Select *);

    void visit(const StringImm *)   { error(); }
    void visit(const AssertStmt *)  { error(); }
    void visit(const Ramp *)        { error(); }
    void visit(const Broadcast *)   { error(); }
    void visit(const IfThenElse *)  { error(); }
    void visit(const Free *)        { error(); }

    void visit(const Store *)       { error(); } // Should pass the unflatten version to Tiramisu
    void visit(const Allocate *)    { error(); } // Should pass the unflatten version to Tiramisu

    void visit(const Evaluate *);
    void visit(const Load *);
    void visit(const Let *);
    void visit(const LetStmt *);
    void visit(const For *);
    void visit(const Call *);
    void visit(const ProducerConsumer *);
    void visit(const Block *);

    void visit(const Provide *);
    void visit(const Realize *);
};

void HalideToC::do_indent()
{
    for (int i = 0; i < indent; i++) { stream << ' '; }
}

void HalideToC::visit(const IntImm *op)
{
    stream << "tiramisu::expr(";
    if (op->type.bits() == 8)
    {
        stream << "(int8_t)";
    }
    else if (op->type.bits() == 16)
    {
        stream << "(int16_t)";
    }
    else if (op->type.bits() == 32)
    {
        stream << "(int32_t)";
    }
    stream << op->value << ")";
}

void HalideToC::visit(const UIntImm *op)
{
    stream << "tiramisu::expr(";
    if (op->type.bits() == 8)
    {
        stream << "(uint8_t)";
    }
    else if (op->type.bits() == 16)
    {
        stream << "(uint16_t)";
    }
    else if (op->type.bits() == 32)
    {
        stream << "(uint32_t)";
    }
    stream << op->value << ")";
}

void HalideToC::visit(const FloatImm *op)
{
    if (op->type.bits() == 32)
    {
        stream << "tiramisu::expr((float)op->value);";
    }
    else if (op->type.bits() == 64)
    {
        stream << "tiramisu::expr(op->value);";
    }
    else
    {
        // Only support 32- and 64-bit integer
        error();
    }
}

void HalideToC::visit(const Cast *op)
{
    error();
}

void HalideToC::visit(const Variable *op)
{
    assert(!op->param.defined() && "Can only handle simple variable for now.\n");
    assert(!op->image.defined() && "Can only handle simple variable for now.\n");

    const auto &iter = constant_list.find(op->name);
    if (iter != constant_list.end())
    {
        // It is a reference to variable defined in Let/LetStmt
        // TODO(psuriana): when do we actually generate constant???
        stream << (*iter) << "(0)";
    }
    else
    {
        // It is presumably a reference to loop variable
        stream << "tiramisu::idx(" << op->name << ")";
    }
}

void HalideToC::visit(const Add *op)
{
    stream << '(';
    print(op->a);
    stream << " + ";
    print(op->b);
    stream << ')';
}

void HalideToC::visit(const Sub *op)
{
    stream << '(';
    print(op->a);
    stream << " - ";
    print(op->b);
    stream << ')';
}

void HalideToC::visit(const Mul *op)
{
    stream << '(';
    print(op->a);
    stream << "*";
    print(op->b);
    stream << ')';
}

void HalideToC::visit(const Div *op)
{
    stream << '(';
    print(op->a);
    stream << "/";
    print(op->b);
    stream << ')';
}

void HalideToC::visit(const Mod *op)
{
    stream << '(';
    print(op->a);
    stream << " % ";
    print(op->b);
    stream << ')';
}

void HalideToC::visit(const Min *op)
{
    stream << "tiramisu::expr(tiramisu::o_min, ";
    print(op->a);
    stream << ", ";
    print(op->b);
    stream << ")";
}

void HalideToC::visit(const Max *op)
{
    stream << "tiramisu::expr(tiramisu::o_max, ";
    print(op->a);
    stream << ", ";
    print(op->b);
    stream << ")";
}

void HalideToC::visit(const EQ *op)
{
    stream << '(';
    print(op->a);
    stream << " == ";
    print(op->b);
    stream << ')';
}

void HalideToC::visit(const NE *op)
{
    stream << '(';
    print(op->a);
    stream << " != ";
    print(op->b);
    stream << ')';
}

void HalideToC::visit(const LT *op)
{
    stream << '(';
    print(op->a);
    stream << " < ";
    print(op->b);
    stream << ')';
}

void HalideToC::visit(const LE *op)
{
    stream << '(';
    print(op->a);
    stream << " <= ";
    print(op->b);
    stream << ')';
}

void HalideToC::visit(const GT *op)
{
    stream << '(';
    print(op->a);
    stream << " > ";
    print(op->b);
    stream << ')';
}

void HalideToC::visit(const GE *op)
{
    stream << '(';
    print(op->a);
    stream << " >= ";
    print(op->b);
    stream << ')';
}

void HalideToC::visit(const And *op)
{
    stream << '(';
    print(op->a);
    stream << " && ";
    print(op->b);
    stream << ')';
}

void HalideToC::visit(const Or *op)
{
    stream << '(';
    print(op->a);
    stream << " || ";
    print(op->b);
    stream << ')';
}

void HalideToC::visit(const Not *op)
{
    stream << '!';
    print(op->a);
}

void HalideToC::visit(const Select *op)
{
    stream << "tiramisu::expr(tiramisu::o_select, ";
    print(op->condition);
    stream << ", ";
    print(op->true_value);
    stream << ", ";
    print(op->false_value);
    stream << ")";
}

void HalideToC::visit(const Let *op)
{
    error(); // Should not have encountered this since we called substitute_in_all_lets before mutating
}

void HalideToC::visit(const LetStmt *op)
{
    scope.push(op->name, op->value);
    print(op->body);
    scope.pop(op->name);
}

void HalideToC::visit(const ProducerConsumer *op)
{
    assert((op->body.as<Block>() == NULL) && "Does not currently handle update.\n");
    assert((!op->is_producer || (computation_list.find(op->name) == computation_list.end())) &&
           "Found another computation with the same name.\n");

    vector<Loop> old_loop_dims = loop_dims;
    print(op->body);
    loop_dims = old_loop_dims;
}

void HalideToC::define_constant(const string &name, Expr val)
{
    assert((constant_list.find(name) == constant_list.end()) &&
           "Redefinition of lets is not supported right now.\n");

    val = simplify(val);

    do_indent();

    stream << "tiramisu::constant " << name << "(\"" << name << "\", ";
    print(val);
    stream << ", " << halide_type_to_tiramisu_type_str(val.type())
           << ", true, NULL, 0, &" << func << ");\n";

    constant_list.insert(name);
}

void HalideToC::visit(const For *op)
{
    push_loop_dim(op);

    const Variable *min = op->min.as<Variable>();
    assert((min != NULL) && "Min value of a loop should have been a variable.\n");
    const Variable *extent = op->extent.as<Variable>();
    assert((extent != NULL) && "Extent of a loop should have been a variable.\n");

    Expr min_val = scope.get(min->name);
    Expr extent_val = scope.get(extent->name);

    // Substitute it in all references to some other variables in the min/extent val
    map<string, Expr> replacements;
    typename Scope<Expr>::const_iterator iter;
    for (iter = scope.cbegin(); iter != scope.cend(); ++iter)
    {
        if ((iter.name() != min->name) || (iter.name() != extent->name))
        {
            replacements.emplace(iter.name(), iter.value());
        }
    }

    // Do it twice, to make sure we substitute in all variables properly
    min_val = substitute(replacements, min_val);
    min_val = substitute(replacements, min_val);

    extent_val = substitute(replacements, extent_val);
    extent_val = substitute(replacements, extent_val);

    define_constant(min->name, min_val);
    define_constant(extent->name, extent_val);

    print(op->body);
    pop_loop_dim();
}

void HalideToC::visit(const Evaluate *op)
{
    // TODO(psuriana): do nothing for now
}

void HalideToC::visit(const Load *op)
{
    error(); // Load to external buffer is not currently supported
}

void HalideToC::visit(const Provide *op)
{
    assert((computation_list.find(op->name) == computation_list.end())
           && "Duplicate computation is not currently supported.\n");
    assert((temporary_buffers.count("buff_" + op->name) || output_buffers.count("buff_" + op->name))
           && "The buffer should have been allocated previously.\n");

    for (size_t i = 0; i < op->args.size(); ++i)
    {
        assert((op->args[i].as<Variable>() != NULL)
               && "Expect args of provide to be loop dims for now (doesn't currently handle update).\n");
    }
    assert((op->values.size() == 1) && "Expect 1D store (no tuple) in the Provide node for now.\n");

    do_indent();

    string dims_str = to_string(op->args);
    string iter_space_str = get_loop_bound_vars() + "->{" + op->name + dims_str + ": " +
                            get_loop_bounds() + "}";

    stream << "tiramisu::computation " << op->name << "(\"" << iter_space_str << "\", ";
    print(op->values[0]);
    stream << ", true, " << halide_type_to_tiramisu_type_str(op->values[0].type())
           << ", &" << func << ");\n";

    // 1-to-1 mapping to buffer
    string access_str = "{" + op->name + dims_str + "->" + "buff_" + op->name + dims_str + "}";
    stream << op->name << ".set_access(\"" << access_str << "\");\n";

    computation_list.insert(op->name);
}

void HalideToC::visit(const Realize *op)
{
    // We will ignore the condition on the Realize node for now.

    assert((temporary_buffers.find("buff_" + op->name) == temporary_buffers.end())
           && "Duplicate allocation (i.e. duplicate compute) is not currently supported.\n");

    const auto iter = env.find(op->name);
    assert((iter != env.end()) && "Cannot find function in env.\n");
    bool is_output = false;
    for (Function o : outputs)
    {
        is_output |= o.same_as(iter->second);
    }
    assert(!is_output && "Realize should have been temporary buffer.\n");

    // Assert that the types of all buffer dimensions are the same for now.
    for (size_t i = 1; i < op->types.size(); ++i)
    {
        assert((op->types[i - 1] == op->types[i]) &&
               "Realize node should have the same types for all dimensions for now.\n");
    }

    // Assert that the bounds on the dimensions start from 0 for now.
    for (size_t i = 0; i < op->bounds.size(); ++i)
    {
        assert(is_zero(op->bounds[i].min) && "Bound of realize node should start from 0 for now.\n");
    }

    do_indent();

    // Create a temporary buffer

    string buffer_name = "buff_" + op->name;
    stream << "tiramisu::buffer " << buffer_name << "(\"" << buffer_name << "\", "
           << op->bounds.size() << ", ";

    stream << "{";
    for (size_t i = 0; i < op->bounds.size(); ++i)
    {
        print(op->bounds[i].extent);
        if (i != op->bounds.size() - 1)
        {
            stream << ", ";
        }
    }
    stream << "}, ";

    stream << halide_type_to_tiramisu_type_str(op->types[0]) << ", NULL, tiramisu::a_temporary, "
           << "&" << func << ");\n";

    temporary_buffers.insert(buffer_name);

    print(op->body);
}

void HalideToC::visit(const Call *op)
{
    assert((op->call_type == Call::CallType::Halide) && "Only handle call to halide func for now.\n");

    const auto iter = computation_list.find(op->name);
    assert(iter != computation_list.end() && "Call to computation that does not exist.\n");

    stream << (*iter) << "(";
    for (size_t i = 0; i < op->args.size(); i++)
    {
        print(op->args[i]);
        if (i < op->args.size() - 1)
        {
            stream << ", ";
        }
    }
    stream << ")";
}

void HalideToC::visit(const Block *op)
{
    print(op->first);
    if (op->rest.defined()) { print(op->rest); }
}

} // anonymous namespace

void halide_pipeline_to_c(
    Stmt s, const vector<Function> &outputs, const map<string, Function> &env,
    const map<string, vector<int32_t>> &output_buffers_size,
    const string &func)
{

    std::ostringstream stream;

    stream << "tiramisu::function " << func << "(\"" << func << "\")" << ";\n";

    set<string> output_buffers;
    Scope<Expr> scope;

    std::ostringstream output_buffers_stream;
    output_buffers_stream << "{";
    // Allocate the output buffers
    for (size_t k = 0; k < outputs.size(); ++k)
    {
        const Function &f = outputs[k];
        const auto iter = output_buffers_size.find(f.name());
        assert(iter != output_buffers_size.end());
        assert(iter->second.size() == f.args().size());

        std::ostringstream sizes;
        sizes << "{";
        for (size_t i = 0; i < iter->second.size(); ++i)
        {
            sizes << "tiramisu::expr(" << iter->second[i] << ")";
            scope.push(f.name() + "_min_" + std::to_string(i), make_const(Int(32), 0));
            scope.push(f.name() + "_extent_" + std::to_string(i), make_const(Int(32), iter->second[i]));
            if (i != iter->second.size() - 1)
            {
                sizes << ", ";
            }
        }
        sizes << "}";

        string buffer_name = "buff_" + f.name();
        // TODO(psuriana): should make the buffer data type variable instead of uint8_t always
        stream << "tiramisu::buffer " << buffer_name << "(\"" << buffer_name << "\", "
               << f.args().size() << ", " << sizes.str() << ", tiramisu::p_uint8, NULL, tiramisu::a_output, "
               << "&" << func << ");\n";
        output_buffers.insert(buffer_name);

        output_buffers_stream << "&" << buffer_name;
        if (k != outputs.size() - 1)
        {
            output_buffers_stream << ", ";
        }
    }
    output_buffers_stream << "}";

    HalideToC converter(scope, outputs, env, output_buffers, func, stream);
    converter.print(s);

    stream << func << ".set_arguments(" << output_buffers_stream.str() << ");\n";
    stream << func << ".gen_isl_ast();\n";
    stream << func << ".gen_halide_stmt();\n";
    stream << func << ".dump_halide_stmt();\n";
    stream << func << ".gen_halide_obj(\"build/generated_fct_test_06.o\");\n";

    std::cout << "\nTiramisu C output:\n\n" << stream.str() << "\n";
}

}


text:
Pattern: Malformed whitespace before range operator in media feature

Issue: -

## Description

Require a single space or disallow whitespace before the range operator in media features.

## Examples

### `"always"`

There *must always* be a single space before the range operator.

The following patterns are considered violations:

```css
@media (width>=600px) {}
```

```css
@media (width>= 600px) {}
```

The following patterns are *not* considered violations:

```css
@media (width >=600px) {}
```

```css
@media (width >= 600px) {}
```

### `"never"`

There *must never* be whitespace before the range operator.

The following patterns are considered violations:

```css
@media (width >=600px) {}
```

```css
@media (width >= 600px) {}
```

The following patterns are *not* considered violations:

```css
@media (width>=600px) {}
```

```css
@media (width>= 600px) {}
```

## Further Reading

* [stylelint - media-feature-range-operator-space-before](https://stylelint.io/user-guide/rules/media-feature-range-operator-space-before)

redpajama_set_name: RedPajamaGithub


text: Loading


text:
<?php

namespace Orchestra\Story\Http\Handlers;

use Orchestra\Contracts\Auth\Guard;
use Orchestra\Foundation\Support\MenuHandler;

class PageMenuHandler extends MenuHandler
{
    /**
     * Menu configuration.
     *
     * @var array
     */
    protected $menu = [
        'id'    => 'storycms-pages',
        'title' => 'Pages',
        'link'  => 'orchestra::storycms/pages',
        'icon'  => null,
    ];

    /**
     * Check whether the menu should be displayed.
     *
     * @param  \Orchestra\Contracts\Auth\Guard  $auth
     *
     * @return bool
     */
    public function authorize(Guard $auth)
    {
        return ! $auth->guest();
    }
}


text:
namespace AT {

    class GameScreen : public Screen
    {
    public:
        typedef std::vector<Launcher*> Launchers;
        typedef std::vector<Wall*> Walls;
    private:
        std::string levelName;
        int levelPreviousParticles;
        std::string nextLevel;
        sf::Vector2f levelNextStart;
        sf::Vector2f levelPreviousStart;

        Launcher *mainLauncher;
        Launchers optionalLaunchers;
        //Receiver *receiver;
        Receiver receiver;
        Walls walls;
        Flow flow;

        ParticleSystem particleSystem;

        sf::Image fingerImage;
        sf::Sprite fingerSprite;
        sf::Image particleImage;
        sf::Sprite particleSprite;

        bool isUpdating;
        bool isStepping;
        bool debug;

        void Clear();

        void LoadLevel();
        void NextLevel();

        static bool IsFingerOK(const FingerData& FingerData, void *Data);
    public:
        GameScreen(ScreenManager& ScreenManager);
        virtual ~GameScreen();

        virtual void Load(sf::RenderTarget& Target);

        virtual void OnStateChange(ScreenState::Value OldState);

        virtual bool Process(sf::Event& Event);
        virtual bool Update(float TimeStep);
        virtual void Draw(sf::RenderTarget& Target);

        GameScreen* SetLevel(const std::string& Name, int PreviousParticles = 0)
        { levelName = Name; levelPreviousParticles = PreviousParticles; return this; }
    };

}

#endif


text:
<?xml version="1.0" encoding="utf-8" ?>
<Suite Category="Domains" Title="WhoisApi" Id="WhoisApi" RequireVersion="8.2" SourceUrl="https://github.com/nielsbosma/SeoTools-for-Excel-Connectors/blob/master/WhoisApi.xml" HelpUrl="http://seotoolsforexcel.com/whoisapi/" HelpText="Documentation">

  <Author Name="Niels Bosma" Url="https://se.linkedin.com/in/bosmaniels"/>

  <Settings HelpText="What's this?" HelpUrl="http://seotoolsforexcel.com/whoisapi/">
    <Text Id="ApiKey" Required="true"/>
  </Settings>

  <RestConnector Id="Whois" Title="Whois" HelpUrl="https://whois.whoisxmlapi.com">
    <Parameters>
      <Text Id="Domain" Required="true" Debug.DefaultValue="seotoolsforexcel.com"/>
    </Parameters>
    <Fetch>
      <Fetch.Url>
        <![CDATA[
        https://www.whoisxmlapi.com/whoisserver/WhoisService?apiKey=@(Model.ApiKey)
				&domainName=@(Model.Domain)
				&outputFormat=JSON
        ]]>
      </Fetch.Url>
    </Fetch>
    <Parse>
      <JsonPath Expr="WhoisRecord">
        <JsonPath Id="Created" Title="Created" Expr="createdDate" Converter="DateTime" />
        <JsonPath Id="Updated" Title="Updated" Expr="updatedDate" Converter="DateTime"/>
        <JsonPath Id="Expires" Title="Expires" Expr="expiresDate" Converter="DateTime" />
        <JsonPath Id="domainAge" Title="Domain Age" Expr="estimatedDomainAge" Converter="Int"/>
        <JsonPath Id="NameServers" Title="Name Servers" Expr="csv(nameServers.hostNames[*])" Converter="String" DefaultValue=""/>
        <JsonPath Id="WhoisServer" Title="Whois Server" Expr="registryData.whoisServer" Checked="false"/>
        <JsonPath Id="Registrar" Title="Registrar" Expr="registrarName" Checked="false"/>
        <JsonPath Id="RegistrarIanaId" Title="Registrar IANA Id" Expr="registrarIANAID" Converter="Int" Checked="false"/>
        <JsonPath Id="RegistrantName" Title="Registrant Name" Expr="registrant.name" Checked="false" DefaultValue=""/>
        <JsonPath Id="RegistrantOrganization" Title="Registrant Org" Expr="registrant.organization" Checked="false" DefaultValue=""/>
        <JsonPath Id="RegistrantCountry" Title="Registrant Country" Expr="registrant.country" Checked="false" DefaultValue=""/>
        <JsonPath Id="RegistrantCity" Title="Registrant City" Expr="registrant.city" Checked="false" DefaultValue=""/>
        <JsonPath Id="ContactEmail" Title="Contact Email" Expr="contactEmail" Checked="false" DefaultValue=""/>
        <JsonPath Id="Status" Title="Status" Expr="registryData.status" Checked="false" DefaultValue=""/>
      </JsonPath>
    </Parse>
    <Fail>
      <JsonPath Expr="ErrorMessage.msg"/>
    </Fail>
  </RestConnector>

  <RestConnector Id="Available" Title="Available" HelpUrl="https://www.whoisxmlapi.com/domain-availability-api-guide.php">
    <Parameters>
      <Radio Id="Mode" Title="Mode" DefaultValue="DNS_ONLY" Required="true">
        <DataSource>
          <Item Id="1" Title="Quicker"/>
          <Item Id="2" Title="Slower but more accurate"/>
        </DataSource>
      </Radio>
      <Text Id="Domain" Required="true" Debug.DefaultValue="seotoolsforexcel.com"/>
    </Parameters>
    <Fetch>
      <Fetch.Url>
        <![CDATA[
        https://www.whoisxmlapi.com/whoisserver/WhoisService?apiKey=@(Model.ApiKey)
				&domainName=@(Model.Domain)
				&outputFormat=JSON
				&da=@(Model.Mode)
        ]]>
      </Fetch.Url>
    </Fetch>
    <Parse>
      <JsonPath Expr="WhoisRecord.domainAvailability" Converter="Bool" Converter.TrueIf="AVAILABLE"/>
    </Parse>
    <Fail>
      <JsonPath Expr="ErrorMessage.msg"/>
    </Fail>
  </RestConnector>

</Suite>


text:
layout: post
title: "What does RTBC mean?"
date: 2013-01-12 15:07:02
---

If you ever spend time in the Drupal.org issue queues, the Drupal forums, or Drupal-centric IRC chatrooms, you'll see people mentioning RTBC. But what does RTBC mean?

**RTBC means "Reviewed and Tested by the Community"**

Let me use an example. Lets say you have made changes to a file and you submit those changes for inclusion in Drupal in the form of a patch. That patch is uploaded through the issue comments on Drupal.org where other people can see it. This begins a process whereby people try out your patch and set the issue status as "Needs Work" whenever the patch needs more work, or "Needs Review" whenever the patch has been updated and needs to be reviewed again. If the patch is reviewed and the reviewer finds it in good working condition, then that reviewer can set the status to "Reviewed and Tested by the Community."

Other information about RTBC:

*   Anybody with a Drupal.org account can set a ticket to RTBC.
*   RTBC status should be set by the person who tests the update and finds that it passes all relevant criteria.
*   The person who updated the code should not set their own ticket status to RTBC.
*   Once an issue has the status of RTBC, somebody with 'commit access' gives it another review and, if it is good, commits it to the project.


text:
class LiveDataController < ApplicationController
	DefaultUserId    = "guest"
	DefaultChannelId = "chat"
	DefaultWaitTime  = 15

	def get
		user_id    = params[:user_id]    || DefaultUserId
		channel_id = params[:channel_id] || DefaultChannelId
		channel = LiveData.get_channel(channel_id) || LiveData.create_channel(channel_id)
		user    = channel.get_user( user_id ) || channel.create_user( user_id )
		user.set_read_time( ( params[:read_time] || DefaultWaitTime ).to_i )
		respond_to do |format|
			format.html {
				render :text => user.read.to_query
			}
			format.xml {
				render :text => user.read.to_xml
			}
			format.yaml {
				render :text => user.read.to_yaml
			}
			format.json {
				render :text => user.read.to_json
			}

		end

	end

	def put
		user_id = params[:user_id] || GestUserId
		channel_id = params[:channel_id] || DefaultChannelId
		channel = LiveData.get_channel(channel_id) || LiveData.create_channel(channel_id)
		user    = channel.get_user( user_id ) || channel.create_user( user_id )
		user.write( params.to_hash )
		render :text => "OK", :layout => false
	end

end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace Betabit.Lora.Nuget.Example.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Error()
        {
            return View();
        }
    }
}


text:
package com.mcleodmoores.integration.adapter;

import java.util.Objects;

import org.joda.convert.FromStringFactory;
import org.joda.time.LocalDate;

import com.mcleodmoores.integration.convention.DayCount;
import com.opengamma.util.ArgumentChecker;

import net.finmath.time.daycount.DayCountConventionInterface;

/**
 * Top-level wrapper for {@link DayCountConventionInterface} classes.
 */
@FromStringFactory(factory = FinmathDayCountFactory.class)
public abstract class FinmathDayCount implements DayCount, DayCountConventionInterface {
  /** The name of the convention */
  private final String _name;
  /** The day count */
  private final DayCountConventionInterface _dayCount;

  /**
   * Creates an instance.
   * @param name The name, not null
   * @param dayCount The day count, not null
   */
  protected FinmathDayCount(final String name, final DayCountConventionInterface dayCount) {
    _name = ArgumentChecker.notNull(name, "name");
    _dayCount = ArgumentChecker.notNull(dayCount, "dayCount");
  }

  @Override
  public double getDaycount(final LocalDate startDate, final LocalDate endDate) {
    return getConvention().getDaycount(startDate, endDate);
  }

  @Override
  public double getDaycountFraction(final LocalDate startDate, final LocalDate endDate) {
    return getConvention().getDaycountFraction(startDate, endDate);
  }

  /**
   * Gets the convention.
   * @return The convention
   */
  public DayCountConventionInterface getConvention() {
    return _dayCount;
  }

  @Override
  public String getName() {
    return _name;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + (_name == null ? 0 : _name.hashCode());
    result = prime * result + (_dayCount == null ? 0 : _dayCount.getClass().getName().hashCode());
    // don't use day-count directly because hashCode() is not implemented
    return result;
  }

  @Override
  public boolean equals(final Object obj) {
    if (this == obj) {
      return true;
    }
    if (!(obj instanceof FinmathDayCount)) {
      return false;
    }
    final FinmathDayCount other = (FinmathDayCount) obj;
    return Objects.equals(_name, other._name)
        && Objects.equals(_dayCount.getClass().getName(), other._dayCount.getClass().getName());
    //don't use day-count directly because equals() is not implemented
  }

}


text:
package org.sakaiproject.entitybroker.entityprovider;

import org.sakaiproject.entitybroker.EntityBroker;
import org.sakaiproject.entitybroker.entityprovider.capabilities.AutoRegisterEntityProvider;

/**
 * This is the base unit for working with Sakai entities, by implementing this interface and
 * creating a spring bean you will tie your entities into Sakai, there are many other interfaces
 * which you can implement to extend the interaction of your entities with Sakai in this package

 * You (the implementor) will want to create one implementation of this interface for each type of
 * entity you want to link to Sakai to track events, provide URL access, etc.

 *

 * Usage:

 * 1) Implement this interface

 * 2) Implement any additional capabilities interfaces (optional)

 * 3) Create a spring bean definition in the Sakai application context (components.xml)

 * 4) Implement {@link AutoRegisterEntityProvider} or register this implementation some other way

 *

 * Recommended best practices: (example: Thing entity)

 * 1) Create an interface called
 * ThingEntityProvider which extends {@link EntityProvider} in api logic (add an entity package for
 * it), (e.g. org.sakaiproject.evaluation.logic.entity.EvaluationEntityProvider.java)

 * 2) Add a public static string which contains the entity prefix (called ENTITY_PREFIX), (e.g. public final
 * static String ENTITY_PREFIX = "eval-evaluation";)

 * 3) Implement your ThingEntityProvider in
 * impl logic as ThingEntityProviderImpl (add an entity package for it), (e.g.
 * org.sakaiproject.evaluation.logic.impl.entity.EvaluationEntityProviderImpl.java)

 * 4) Implement {@link CoreEntityProvider} in ThingEntityProviderImpl

 * 5) Implement {@link AutoRegisterEntityProvider} in ThingEntityProviderImpl

 * 6) Add a spring bean
 * definition in the Sakai application context (components.xml), use the api name as the id

 * Example: <xmp> <bean id="org.sakaiproject.evaluation.logic.entity.EvaluationEntityProvider"
 * class="org.sakaiproject.evaluation.logic.impl.entity.EvaluationEntityProviderImpl"> </bean>
 * </xmp>

 * 7) Add the needed maven dependendencies to api/logic and impl/logic project.xml
 * files

 * Exmaple: <xmp>
 * <dependency>
 *    <groupId>sakaiproject</groupId>
 *    <artifactId>sakai-entitybroker-api</artifactId>
 *    <version>${sakai.version}</version>
 * </dependency>
 * </xmp>

 * That should do it. You should now be able to use the
 * {@link EntityBroker} to access information about your entities and register events for your
 * entities (among other things).
 *
 * @author Aaron Zeckoski (aaronz@vt.edu)
 * @author Antranig Basman (antranig@caret.cam.ac.uk)
 */
public interface CoreEntityProvider extends EntityProvider {

   /**
    * Check if a specific entity managed by this provider exists.

    * This is primarily used to validate references before making other calls or operating on them.

    * WARNING: This will be called many times and AT LEAST right before calls are made to
    * any methods or capabilities related to specific entities, please make sure this is
    * very efficient. If you are concerned about efficiency, it is ok for this method to always
    * return true but you will no longer be able to be sure that calls through to your capability
    * implementations are always valid.
    *
    * @param id a locally unique id for an entity managed by this provider

    * NOTE: this will be an empty string if this is an entity space (singleton entity) without an id available
    * @return true if an entity with given local id exists, false otherwise
    */
   public boolean entityExists(String id);

}


text:
"""
Flask-Script
--------------

Flask support for writing external scripts.

Links
`````

* `documentation <http://packages.python.org/Flask-Script>`_
* `development version
  <http://bitbucket.org/danjac/flask-Script/get/tip.gz#egg=Flask-Script-dev>`_

"""
from setuptools import setup

setup(
    name='Flask-Script',
    version='0.3.1',
    url='http://bitbucket.org/danjac/flask-script',
    license='BSD',
    author='Dan Jacob',
    author_email='danjac354@gmail.com',
    description='Scripting support for Flask',
    long_description=__doc__,
    packages=['flaskext'],
    namespace_packages=['flaskext'],
    test_suite='nose.collector',
    zip_safe=False,
    platforms='any',
    install_requires=[
        'Flask',
        'argparse',
    ],
    tests_require=[
        'nose',
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
        'Topic :: Software Development :: Libraries :: Python Modules'
    ]
)


text:
<?php
/**
 * Created by PhpStorm.
 * User: stas
 * Date: 14.04.16
 * Time: 10:31
 */

namespace CoreBundle\Entity;

use Behat\Transliterator\Transliterator;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use JMS\Serializer\Annotation as JMS;

/**
 * Class UserSetting
 * @package CoreBundle\Entity
 *
 * @ORM\Table(name="user_setting")
 * @ORM\Entity(repositoryClass="CoreBundle\Repository\UserSettingRepository")
 */
class UserSetting
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     *
     * @JMS\Expose
     * @JMS\SerializedName("id")
     * @JMS\Type("integer")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255, unique=true)
     *
     * @JMS\Expose
     * @JMS\SerializedName("name")
     * @JMS\Type("string")
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(type="string", length=128, nullable=true)
     */
    private $code;

    /**
     * @var string
     *
     * @ORM\Column(name="type", type="string", length=255)
     *
     * @JMS\Expose
     * @JMS\SerializedName("type")
     * @JMS\Type("string")
     */
    private $type;

    /**
     * @var string
     *
     * @JMS\Expose
     * @JMS\SerializedName("value")
     * @JMS\Type("string")
     */
    private $value;

    /**
     * @var int
     *
     * @ORM\Column(name="sort", type="integer")
     *
     * @JMS\Expose
     * @JMS\Type("integer")
     */
    private $sort = 20;

    /**
     * @param int $id
     * @return UserSetting
     */
    public function setId(int $id) : UserSetting
    {
        $this->id = $id;

        return $this;
    }

    /**
     * @return int
     */
    public function getId() : int
    {
        return $this->id;
    }

    /**
     * @return string
     */
    public function getName() : string
    {
        return $this->name;
    }

    /**
     * @param string $name
     * @return UserSetting
     */
    public function setName(string $name) : UserSetting
    {
        $this->name = $name;

        $this->code = Transliterator::transliterate($name);

        return $this;
    }

    /**
     * @return string
     */
    public function getValue() : string
    {
        return $this->value;
    }

    /**
     * @param string $value
     * @return UserSetting
     */
    public function setValue(string $value) : UserSetting
    {
        $this->value = $value;

        return $this;
    }

    /**
     * @return string
     */
    public function getType() : string
    {
        return $this->type;
    }

    /**
     * @param string $type
     * @return UserSetting
     */
    public function setType(string $type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * @return int
     */
    public function getSort() : int
    {
        return $this->sort;
    }

    /**
     * @param int $sort
     * @return UserSetting
     */
    public function setSort(int $sort) : UserSetting
    {
        $this->sort = $sort;

        return $this;
    }

    /**
     * @return string
     */
    public function getCode() : string
    {
        return $this->code;
    }

    /**
     * @param string $code
     * @return UserSetting
     */
    public function setCode($code)
    {
        $this->code = $code;

        return $this;
    }
}


text:
<?php

namespace yiithings\develop\helpers;

use PHPSQLParser\PHPSQLParser;

class MigrateHelper
{
    /**
     * Help developers to migrate using native SQL constructs to support IDE.
     *
     * @param string $sql
     * @return string
     */
    public static function replaceTablePrefix($sql, $filter = [])
    {
        $parser = new PHPSQLParser();
        $parsed = $parser->parse($sql, false);

        $tableNames = [];
        if (isset($parsed['FROM'])) {
            foreach ($parsed['FROM'] as $table) {
                if ($table['expr_type'] == 'table') {
                    $tableNames[] = $table['table'];
                }
            }
        }

        $tables = implode('|', $tableNames);
        $sql = preg_replace_callback('#(' . $tables .')#', function($match) {
            if (preg_match('#`(.*?)`#', $match[1], $matchTable)) {
                $match[1] = $matchTable[1];
            }

            return '{{%' . $match[1] . '}}';
        }, $sql);

        var_dump($sql);

        return $sql;
    }
}


text:
using UnityEngine;
using System.Collections;

public class unitychanFace : MonoBehaviour {

	private Animator anim;
	private int faceCount;
	private string faceName;
	public float fadeTime = 3;
	static readonly string[] faceNames =
	{
		"angry1",
		"angry2",
		"conf",
		"default",
		"disstract1",
		"disstract2",
		"eye_close",
		"sap",
		"smile1",
		"smile2",
	};

	void FaceChange()
	{
		var go = GameObject.Find("Main Camera").GetComponent<Transform> ();
		var head = GameObject.Find("Character1_Head").GetComponent<Transform> ();
		go.position = new Vector3 (0, 0, 0.7f) + head.position;
		anim.SetLayerWeight (1, 1);

		faceName = faceNames[faceCount];
		anim.CrossFade(faceName + "@unitychan", fadeTime);
		faceCount = (faceCount + 1) % faceNames.Length;
	}

	// Use this for initialization
	void Start () {
		anim = GetComponent<Animator> ();
		FaceChange();

	}

	// Update is called once per frame
	void Update () {
	}
	void OnGUI()
	{
		if ( GUI.Button( new Rect(10, 70, 100, 20), faceName ) )
		{
			FaceChange();
		}
	}
}


text:
dialogflow client library. This library supports api.ai webhook.

# parse request from dialogflow

use `json.Unmarshal()`

```
func handler(w http.ResponseWriter, r *http.Request) {
        buf := new(bytes.Buffer)
        buf.ReadFrom(r.Body)
        var request dialogflow.Request
        err := json.Unmarshal(buf.Bytes(), &request)
        ...
```

# build response for dialogflow

```
// w is http.ResponseWriter
resp = dialogflow.NewSSMLResponse(
    "speak response",
    "displayText response",
    true,
)
data, _ := resp.ToJSON()
w.Write(data)
```


text:
title: "Welsh Rarebit"
categories: moosefood
tags:
  - appetizer
  - entree
  - side-dish
  - snack
  - American
  - British
header:
  teaser:
---

## INGREDIENTS
* 3 tablespoons butter
* 3 tablespoons flour
* ¼ teaspoon salt
* ¼ teaspoon black pepper
* ¼ teaspoon Coleman's dry mustard
* ¼ teaspoon Worcestershire sauce
* dash cayenne to taste
* 1 cup milk
* ½ cup beer
* 8 ounces extra sharp Cheddar *shredded*

## INSTRUCTIONS
1. Melt butter, stir in flour and seasonings (except Worcestershire sauce—mix this with the beer). Cook a few minutes, then stir in milk.
2. Heat to boiling, boil and stir one minute. Gradually add beer.
3. Stir in cheese a little at a time over low heat until all is melted. Serve hot over toast or broccoli.


text:
package org.killbill.billing.plugin.analytics.dao;

import org.killbill.billing.osgi.libs.killbill.OSGIKillbillDataSource;
import org.killbill.billing.plugin.analytics.dao.model.BusinessBundleModelDao;
import org.killbill.billing.util.callcontext.CallContext;

public class BusinessBundleDao extends BusinessAnalyticsDaoBase {

    public BusinessBundleDao(final OSGIKillbillDataSource osgiKillbillDataSource) {
        super(osgiKillbillDataSource);
    }

    public void updateInTransaction(final Iterable<BusinessBundleModelDao> bbss,
                                    final Long tenantRecordId,
                                    final BusinessAnalyticsSqlDao transactional,
                                    final CallContext context) {
        for (final BusinessBundleModelDao bbs : bbss) {
            // Delete by bundle to support partial refreshes
            transactional.deleteByBundleId(BusinessBundleModelDao.BUNDLES_TABLE_NAME,
                                           bbs.getBundleId(),
                                           tenantRecordId,
                                           context);

            transactional.create(bbs.getTableName(), bbs, context);
        }

        // The update of summary columns in BAC will be done via BST
    }
}


text:
import { $, ElementFinder, promise } from 'protractor';

export class SummaryStepPage {
  private get proceedButton(): ElementFinder {
    return $('a.standard-checkout');
  }

  public proceedToCheckout(): promise.Promise<void> {
    return this.proceedButton.click();
  }
}


text:
(function () {
    'use strict';

    angular.module('app.import', []);
})();


text:
import { Component, OnInit }  from '@angular/core';
import { FORM_DIRECTIVES ,
    FORM_PROVIDERS }          from '@angular/common';
import { Router }             from '@angular/router';
import { NgClass }            from '@angular/common';
import { Driver }             from '../driver';
import { DriverService }      from '../services/driver.service';

@Component({
  selector: 'my-modify',
  templateUrl: 'app/modify/modify.component.html',
  styleUrls: ['app/modify/modify.component.css'],
  providers:  [  FORM_PROVIDERS, Driver ],
  directives: [ FORM_DIRECTIVES, NgClass ]
})

export class ModifyComponent implements OnInit {
  constructor(
      private driverService: DriverService,
      private router: Router
      ) {  }

  private message = {
    success: '',
    error: ''
  };

  // for dropdown lists
  driving_ability_list = ['Bicycle', 'Scooter', 'Motorcycle', 'Car (Automatic Transmission)',
    'Car (Manual Transmission)', 'Commercial Truck'];

  state_abbreviation_list = [
    'Alabama',
    'Alaska',
    'Arizona',
    'Arkansas',
    'California',
    'Colorado',
    'Connecticut',
    'Delaware',
    'District of Columbia',
    'Florida',
    'Georgia',
    'Hawaii',
    'Idaho',
    'Illinois',
    'Indiana',
    'Iowa',
    'Kansas',
    'Kentucky',
    'Louisiana',
    'Maine',
    'Maryland',
    'Massachusetts',
    'Michigan',
    'Minnesota',
    'Mississippi',
    'Missouri',
    'Montana',
    'Nebraska',
    'Nevada',
    'New Hampshire',
    'New Jersey',
    'New Mexico',
    'New York',
    'North Carolina',
    'North Dakota',
    'Ohio',
    'Oklahoma',
    'Oregon',
    'Pennsylvania',
    'Puerto Rico',
    'Rhode Island',
    'South Carolina',
    'South Dakota',
    'Tennessee',
    'Texas',
    'Utah',
    'Vermont',
    'Virginia',
    '(U.S.) Virgin Islands',
    'Washington',
    'West Virginia',
    'Wisconsin',
    'Wyoming'
  ];

  // driver model
  driver = {
    selected: false,
    drivername: 'new driver',
    password: '',
    ability: '',
    firstname: '',
    lastname: '',
    email: '',
    address: '',
    city: '',
    state: '',
    zip: '',
    phone: ''
  };

  selected_index:number;

  ngOnInit (){
    // find selected rows
    this.selected_index = this.driverService.find_row_to_modify();

    if (this.selected_index > -1) {
      // populate this modify page form field model with existing driverArray data
      let i = this.selected_index;
      this.driver.selected    = this.driverService.driverArray[i].selected;
      this.driver.drivername  = this.driverService.driverArray[i].drivername;
      this.driver.password    = this.driverService.driverArray[i].password;
      this.driver.ability     = this.driverService.driverArray[i].ability;
      this.driver.firstname   = this.driverService.driverArray[i].firstname;
      this.driver.lastname    = this.driverService.driverArray[i].lastname;
      this.driver.email       = this.driverService.driverArray[i].email;
      this.driver.address     = this.driverService.driverArray[i].address;
      this.driver.city        = this.driverService.driverArray[i].city;
      this.driver.state       = this.driverService.driverArray[i].state;
      this.driver.zip         = this.driverService.driverArray[i].zip;
      this.driver.phone       = this.driverService.driverArray[i].phone;
    }
  }

  cancel_modify() {
    // go back to list view
    this.router.navigate(['/']);
    this.driverService.active_menu = "List";
  }

  /*
      modify_driver() is the click handler for the Modify button on the modify page.
   */
  modify_driver(driver:Driver){
    this.driverService.modify_selected_driver_in_driverArray(driver);
    this.driverService.modify_selected_driver_in_database(driver).subscribe(
      driver => {
        this.message.success = 'Driver ' + this.driver.drivername + ' updated';

        // go back to list view
        this.router.navigate(['/']);
        this.driverService.active_menu = "List";
      },
      error => {
        if (error.status == '404') {
          this.message.error = 'Driver not found';
        } else {
          this.message.error = 'Unknown error';
        }
      }
    );
  }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>io.apiman</groupId>
    <artifactId>apiman-tools</artifactId>
    <version>1.2.0-SNAPSHOT</version>
  </parent>
  <artifactId>apiman-tools-server-all</artifactId>
  <packaging>pom</packaging>
  <name>apiman-tools-server-all</name>

  <dependencies>
    <!-- The WildFly 8 version of APIMan -->
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>apiman-distro-wildfly8</artifactId>
      <type>zip</type>
      <classifier>overlay</classifier>
    </dependency>

    <!-- The EAP 6.4 version of APIMan -->
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>apiman-distro-eap64</artifactId>
      <type>zip</type>
      <classifier>overlay</classifier>
    </dependency>

    <!-- Some Basic Services for Testing -->
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>apiman-tools-services</artifactId>
      <type>war</type>
    </dependency>

    <!-- Data Source Dependencies -->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
    </dependency>
    <dependency>
      <groupId>commons-pool</groupId>
      <artifactId>commons-pool</artifactId>
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
    </dependency>
  </dependencies>

  <profiles>
    <!-- Install on WildFly 8.2 -->
    <profile>
      <id>install-all-wildfly8</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>1.7</version>
            <dependencies>
              <dependency>
                <groupId>org.apache.ant</groupId>
                <artifactId>ant</artifactId>
                <version>1.8.2</version>
              </dependency>
            </dependencies>
            <executions>
              <execution>
                <id>run-wildfly8</id>
                <phase>install</phase>
                <configuration>
                  <tasks>
                    <antversion property="antversion" />
                    <echo>Ant Version: ${antversion}</echo>

                    <property name="appserver.id" value="wildfly8" />
                    <property name="apiman.wildfly.download.url"
                      value="http://download.jboss.org/wildfly/8.2.0.Final/wildfly-8.2.0.Final.zip" />
                    <property name="apiman.tempdir" value="${project.build.directory}/_tmp" />
                    <property name="apiman.install.dir" value="${project.build.directory}" />
                    <property name="apiman.appserver.dir" location="${apiman.install.dir}/wildfly-8.2.0.Final" />
                    <property name="apiman.appserver.zip" location="${basedir}/wildfly-8.2.0.Final.zip" />
                    <property name="apiman.apiman-distro-wildfly8.zip" value="${maven.dependency.io.apiman.apiman-distro-wildfly8.overlay.zip.path}" />
                    <property name="apiman.apiman-tools-services.war" value="${maven.dependency.io.apiman.apiman-tools-services.war.path}" />
                    <property name="apiman.wildfly.home" location="${apiman.appserver.dir}" />
                    <property name="apiman.wildfly.webapps" location="${apiman.appserver.dir}/standalone/deployments" />
                    <property name="apiman.resources.dir" location="${basedir}/src/main/resources" />

                    <echo></echo>
                    <echo>********************************************************************</echo>
                    <echo>APIMan Dist: ${apiman.apiman-distro-wildfly8.zip}</echo>
                    <echo>Dev Services: ${apiman.apiman-tools-services.war}</echo>
                    <echo>-------</echo>
                    <echo>WildFly Home: ${apiman.wildfly.home}</echo>
                    <echo>********************************************************************</echo>
                    <echo></echo>

                    <mkdir dir="${apiman.tempdir}" />

                    <!-- Download and unpack WildFly 8.2 -->
                    <get src="${apiman.wildfly.download.url}" dest="${apiman.appserver.zip}" usetimestamp="true" />
                    <unzip src="${apiman.appserver.zip}" dest="${apiman.install.dir}" overwrite="false" />

                    <!-- Overlay APIMan on top of WildFly 8.2 -->
                    <unzip src="${apiman.apiman-distro-wildfly8.zip}" dest="${apiman.install.dir}/wildfly-8.2.0.Final" overwrite="true" />

                    <!-- Make sure to chmod 755 the shell scripts -->
                    <chmod perm="a+x" dir="${apiman.appserver.dir}/bin">
                      <include name="*.sh" />
                    </chmod>

                    <!-- Deploy additional stuff -->
                    <copy file="${apiman.resources.dir}/wildfly8/deployments/authtest-ds.xml" todir="${apiman.wildfly.webapps}"
                      overwrite="true" />
                    <copy file="${apiman.resources.dir}/wildfly8/deployments/mysql-connector-java-5.1.33-bin.jar"
                      todir="${apiman.wildfly.webapps}" overwrite="true" />
                    <copy file="${apiman.resources.dir}/wildfly8/deployments/postgresql-9.3-1102.jdbc41.jar"
                      todir="${apiman.wildfly.webapps}" overwrite="true" />
                    <copy
                      file="../../distro/wildfly8/src/main/resources/overlay/standalone/configuration/standalone-apiman.xml"
                      tofile="${apiman.wildfly.home}/standalone/configuration/standalone.xml" overwrite="true" />
                    <copy file="${apiman.apiman-tools-services.war}" tofile="${apiman.wildfly.webapps}/services.war"
                      overwrite="true" />
                  </tasks>
                </configuration>
                <goals>
                  <goal>run</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
    <!-- Install on EAP 6.4 -->
    <profile>
      <id>install-all-eap64</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>1.7</version>
            <dependencies>
              <dependency>
                <groupId>org.apache.ant</groupId>
                <artifactId>ant</artifactId>
                <version>1.8.2</version>
              </dependency>
            </dependencies>
            <executions>
              <execution>
                <id>run-eap64</id>
                <phase>install</phase>
                <configuration>
                  <tasks>
                    <antversion property="antversion" />
                    <echo>Ant Version: ${antversion}</echo>

                    <property name="apiman.tempdir" value="${project.build.directory}/_tmp" />
                    <property name="apiman.install.dir" value="${project.build.directory}" />
                    <property name="apiman.appserver.dir" location="${apiman.install.dir}/jboss-eap-6.4" />
                    <property name="apiman.appserver.zip" location="${basedir}/jboss-eap-6.4.0.zip" />
                    <property name="apiman.apiman-distro-eap64.zip" value="${maven.dependency.io.apiman.apiman-distro-eap64.overlay.zip.path}" />
                    <property name="apiman.apiman-tools-services.war" value="${maven.dependency.io.apiman.apiman-tools-services.war.path}" />
                    <property name="apiman.eap.home" location="${apiman.appserver.dir}" />
                    <property name="apiman.eap.webapps" location="${apiman.appserver.dir}/standalone/deployments" />
                    <property name="apiman.resources.dir" location="${basedir}/src/main/resources" />

                    <echo></echo>
                    <echo>********************************************************************</echo>
                    <echo>APIMan Dist: ${apiman.apiman-distro-eap64.zip}</echo>
                    <echo>Dev Services: ${apiman.apiman-tools-services.war}</echo>
                    <echo>-------</echo>
                    <echo>WildFly Home: ${apiman.eap.home}</echo>
                    <echo>********************************************************************</echo>
                    <echo></echo>

                    <mkdir dir="${apiman.tempdir}" />

                    <!-- Unpack EAP 6.4 -->
                    <unzip src="${apiman.appserver.zip}" dest="${apiman.install.dir}" overwrite="false" />

                    <!-- Overlay apiman on top of EAP 6.4 -->
                    <unzip src="${apiman.apiman-distro-eap64.zip}" dest="${apiman.appserver.dir}" overwrite="true" />

                    <!-- Make sure to chmod 755 the shell scripts -->
                    <chmod perm="a+x" dir="${apiman.appserver.dir}/bin">
                      <include name="*.sh" />
                    </chmod>

                    <!-- Deploy additional stuff -->
<!--                     <copy file="${apiman.resources.dir}/wildfly8/deployments/authtest-ds.xml" todir="${apiman.eap.webapps}" -->
<!--                       overwrite="true" /> -->
<!--                     <copy file="${apiman.resources.dir}/wildfly8/deployments/mysql-connector-java-5.1.33-bin.jar" -->
<!--                       todir="${apiman.eap.webapps}" overwrite="true" /> -->
<!--                     <copy file="${apiman.resources.dir}/wildfly8/deployments/postgresql-9.3-1102.jdbc41.jar" -->
<!--                       todir="${apiman.eap.webapps}" overwrite="true" />                       -->
                    <copy
                      file="../../distro/eap64/src/main/resources/overlay/standalone/configuration/standalone-apiman.xml"
                      tofile="${apiman.eap.home}/standalone/configuration/standalone.xml" overwrite="true" />
                    <copy file="${apiman.apiman-tools-services.war}" tofile="${apiman.eap.webapps}/services.war"
                      overwrite="true" />
                  </tasks>
                </configuration>
                <goals>
                  <goal>run</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>
</project>


text:
package clienttest

import (
	"fmt"
	"strings"

	"github.com/open-policy-agent/frameworks/constraint/pkg/core/templates"
	"github.com/open-policy-agent/frameworks/constraint/pkg/handler/handlertest"
	"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
)

const (
	KindAllow            = "Allow"
	KindDeny             = "Deny"
	KindDenyPrint        = "DenyPrint"
	KindDenyImport       = "DenyImport"
	KindCheckData        = "CheckData"
	KindRuntimeError     = "RuntimeError"
	KindForbidDuplicates = "ForbidDuplicates"
	KindFuture           = "Future"
)

// ModuleAllow defines a Rego package which allows all objects it reviews.
const ModuleAllow = `
package foo

violation[{"msg": msg}] {
  false
  msg := "denied"
}
`

func TemplateAllow() *templates.ConstraintTemplate {
	ct := &templates.ConstraintTemplate{}

	ct.SetName("allow")

	ct.Spec.CRD.Spec.Names.Kind = KindAllow
	ct.Spec.CRD.Spec.Validation = &templates.Validation{
		OpenAPIV3Schema: &apiextensions.JSONSchemaProps{
			Type: "object",
		},
	}

	ct.Spec.Targets = []templates.Target{{
		Target: handlertest.TargetName,
		Rego:   ModuleAllow,
	}}

	return ct
}

// ModuleDeny defines a Rego package which denies all objects it reviews.
const ModuleDeny = `
package foo

violation[{"msg": msg}] {
  true
  msg := "denied"
}
`

func TemplateDeny() *templates.ConstraintTemplate {
	ct := &templates.ConstraintTemplate{}

	ct.SetName("deny")

	ct.Spec.CRD.Spec.Names.Kind = KindDeny
	ct.Spec.CRD.Spec.Validation = &templates.Validation{
		OpenAPIV3Schema: &apiextensions.JSONSchemaProps{
			Type: "object",
		},
	}

	ct.Spec.Targets = []templates.Target{{
		Target: handlertest.TargetName,
		Rego:   ModuleDeny,
	}}

	return ct
}

const moduleDenyPrint = `
package foo

violation[{"msg": msg}] {
  print("denied!")
  true
  msg := "denied"
}
`

func TemplateDenyPrint() *templates.ConstraintTemplate {
	ct := &templates.ConstraintTemplate{}

	ct.SetName("denyprint")

	ct.Spec.CRD.Spec.Names.Kind = KindDenyPrint
	ct.Spec.CRD.Spec.Validation = &templates.Validation{
		OpenAPIV3Schema: &apiextensions.JSONSchemaProps{
			Type: "object",
		},
	}

	ct.Spec.Targets = []templates.Target{{
		Target: handlertest.TargetName,
		Rego:   moduleDenyPrint,
	}}

	return ct
}

const moduleImportDenyRego = `
package foo

import data.lib.bar

violation[{"msg": msg}] {
  bar.always[x]
  x == "imported"
  msg := "denied with library"
}
`

const moduleImportDenyLib = `
package lib.bar

always[y] {
  y = "imported"
}
`

// TemplateDenyImport returns a ConstraintTemplate which rejects all incoming
// objects and relies on a library to do so.
func TemplateDenyImport() *templates.ConstraintTemplate {
	ct := &templates.ConstraintTemplate{}

	ct.SetName("denyimport")
	ct.Spec.CRD.Spec.Names.Kind = KindDenyImport
	ct.Spec.CRD.Spec.Validation = &templates.Validation{
		OpenAPIV3Schema: &apiextensions.JSONSchemaProps{
			Type: "object",
		},
	}

	ct.Spec.Targets = []templates.Target{{
		Target: handlertest.TargetName,
		Rego:   moduleImportDenyRego,
		Libs:   []string{moduleImportDenyLib},
	}}

	return ct
}

// moduleCheckData defines a Rego package which checks the "data" field of
// Objects under review.
const moduleCheckData = `
package foo

violation[{"msg": msg, "details": details}] {
  wantData := input.parameters.wantData
  gotData := object.get(input.review.object, "data", "")
  wantData != gotData
  msg := sprintf("got %v but want %v for data", [gotData, wantData])
  details := {"got": gotData}
}
`

func TemplateCheckData() *templates.ConstraintTemplate {
	ct := &templates.ConstraintTemplate{}

	ct.SetName("checkdata")
	ct.Spec.CRD.Spec.Names.Kind = KindCheckData
	ct.Spec.CRD.Spec.Validation = &templates.Validation{
		OpenAPIV3Schema: &apiextensions.JSONSchemaProps{
			Type: "object",
		},
	}

	ct.Spec.Targets = []templates.Target{{
		Target: handlertest.TargetName,
		Rego:   moduleCheckData,
	}}

	return ct
}

func KindCheckDataNumbered(i int) string {
	return fmt.Sprintf("%s-%d", KindCheckData, i)
}

func TemplateCheckDataNumbered(i int) *templates.ConstraintTemplate {
	ct := TemplateCheckData()

	kind := KindCheckDataNumbered(i)
	ct.SetName(strings.ToLower(kind))
	ct.Spec.CRD.Spec.Names.Kind = kind

	return ct
}

const moduleRuntimeError = `
package foo

message(arg) = output {
  output := 7
}

message(arg) = output {
  output := 5
}

violation[{"msg": msg}] {
  result := message("a")
  msg := sprintf("result is %v", [result])
}

`

func TemplateRuntimeError() *templates.ConstraintTemplate {
	ct := &templates.ConstraintTemplate{}

	ct.SetName("runtimeerror")
	ct.Spec.CRD.Spec.Names.Kind = KindRuntimeError
	ct.Spec.CRD.Spec.Validation = &templates.Validation{
		OpenAPIV3Schema: &apiextensions.JSONSchemaProps{
			Type: "object",
		},
	}

	ct.Spec.Targets = []templates.Target{{
		Target: handlertest.TargetName,
		Rego:   moduleRuntimeError,
	}}

	return ct
}

const moduleForbidDuplicates = `
package foo

violation[{"msg": msg}] {
  obj := data.inventory.cluster[_]
  gotData := input.review.object.data
  gotData == obj.data
  msg := sprintf("duplicate data %v", [gotData])
}
`

func TemplateForbidDuplicates() *templates.ConstraintTemplate {
	ct := &templates.ConstraintTemplate{}

	ct.SetName("forbidduplicates")
	ct.Spec.CRD.Spec.Names.Kind = KindForbidDuplicates
	ct.Spec.CRD.Spec.Validation = &templates.Validation{
		OpenAPIV3Schema: &apiextensions.JSONSchemaProps{
			Type: "object",
		},
	}

	ct.Spec.Targets = []templates.Target{{
		Target: handlertest.TargetName,
		Rego:   moduleForbidDuplicates,
	}}

	return ct
}

const moduleFuture = `
package foo

import future.keywords.in

violation[{"msg": msg}] {
  some n in ["1", "2"]
  n == input.review.object.data
  msg := "bad data"
}
`

func TemplateFuture() *templates.ConstraintTemplate {
	ct := &templates.ConstraintTemplate{}

	ct.SetName("future")
	ct.Spec.CRD.Spec.Names.Kind = KindFuture
	ct.Spec.CRD.Spec.Validation = &templates.Validation{
		OpenAPIV3Schema: &apiextensions.JSONSchemaProps{
			Type: "object",
		},
	}

	ct.Spec.Targets = []templates.Target{{
		Target: handlertest.TargetName,
		Rego:   moduleFuture,
	}}

	return ct
}