text:
#include <llvm/ADT/StringRef.h>
#include <llvm/IR/Verifier.h>
#include <llvm/PassManager.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Transforms/Scalar.h>

#define LLL_USE_MCJIT
#ifdef LLL_USE_MCJIT
#include <llvm/ExecutionEngine/MCJIT.h>
#else
#include <llvm/ExecutionEngine/JIT.h>
#endif

#include "lllarith.h"
#include "lllcompiler.h"
#include "lllengine.h"
#include "llllogical.h"
#include "lllruntime.h"
#include "llltableget.h"
#include "llltableset.h"
#include "lllvararg.h"

extern "C" {
#include "lprefix.h"
#include "lfunc.h"
#include "lgc.h"
#include "lopcodes.h"
#include "ltable.h"
#include "luaconf.h"
#include "lvm.h"
}

static const llvm::CodeGenOpt::Level OPT_LEVEL =
        //llvm::CodeGenOpt::None;
        //llvm::CodeGenOpt::Default;
        llvm::CodeGenOpt::Aggressive;

namespace lll {

Compiler::Compiler(lua_State* L, Proto* proto) :
    cs_(L, proto),
    stack_(cs_),
    engine_(nullptr) {
    static bool init = true;
    if (init) {
        llvm::InitializeNativeTarget();
        llvm::InitializeNativeTargetAsmPrinter();
        llvm::InitializeNativeTargetAsmParser();
        init = false;
    }
}

bool Compiler::Compile() {
    return CompileInstructions() &&
           VerifyModule() &&
           OptimizeModule() &&
           CreateEngine();
}

const std::string& Compiler::GetErrorMessage() {
    return error_;
}

Engine* Compiler::GetEngine() {
    return engine_.release();
}

bool Compiler::CompileInstructions() {
    cs_.InitEntryBlock();
    stack_.InitValues();
    cs_.B_.CreateBr(cs_.blocks_[0]);

    for (cs_.curr_ = 0; cs_.curr_ < cs_.proto_->sizecode; ++cs_.curr_) {
        cs_.B_.SetInsertPoint(cs_.blocks_[cs_.curr_]);
        cs_.instr_ = cs_.proto_->code[cs_.curr_];
        //cs_.DebugPrint(luaP_opnames[GET_OPCODE(cs_.instr_)]);
        switch (GET_OPCODE(cs_.instr_)) {
            case OP_MOVE:     CompileMove(); break;
            case OP_LOADK:    CompileLoadk(false); break;
            case OP_LOADKX:   CompileLoadk(true); break;
            case OP_LOADBOOL: CompileLoadbool(); break;
            case OP_LOADNIL:  CompileLoadnil(); break;
            case OP_GETUPVAL: CompileGetupval(); break;
            case OP_GETTABUP: CompileGettabup(); break;
            case OP_GETTABLE: CompileGettable(); break;
            case OP_SETTABUP: CompileSettabup(); break;
            case OP_SETUPVAL: CompileSetupval(); break;
            case OP_SETTABLE: CompileSettable(); break;
            case OP_NEWTABLE: CompileNewtable(); break;
            case OP_SELF:     CompileSelf(); break;

            case OP_ADD: case OP_SUB: case OP_MUL: case OP_MOD: case OP_POW:
            case OP_DIV: case OP_IDIV:
                              Arith(cs_, stack_).Compile(); break;

            case OP_BAND: case OP_BOR: case OP_BXOR: case OP_SHL: case OP_SHR:
                              Logical(cs_, stack_).Compile(); break;

            case OP_UNM:      CompileUnm(); break;
            case OP_BNOT:     CompileBNot(); break;
            case OP_NOT:      CompileNot(); break;
            case OP_LEN:      CompileLen(); break;
            case OP_CONCAT:   CompileConcat(); break;
            case OP_JMP:      CompileJmp(); break;
            case OP_EQ:       CompileCmp("luaV_equalobj"); break;
            case OP_LT:       CompileCmp("luaV_lessthan"); break;
            case OP_LE:       CompileCmp("luaV_lessequal"); break;
            case OP_TEST:     CompileTest(); break;
            case OP_TESTSET:  CompileTestset(); break;
            case OP_CALL:     CompileCall(); break;
            case OP_TAILCALL: CompileTailcall(); break;
            case OP_RETURN:   CompileReturn(); break;
            case OP_FORLOOP:  CompileForloop(); break;
            case OP_FORPREP:  CompileForprep(); break;
            case OP_TFORCALL: CompileTforcall(); break;
            case OP_TFORLOOP: CompileTforloop(); break;
            case OP_SETLIST:  CompileSetlist(); break;
            case OP_CLOSURE:  CompileClosure(); break;
            case OP_VARARG:   Vararg(cs_, stack_).Compile(); break;
            case OP_EXTRAARG: /* ignored */ break;
        }
        if (!cs_.blocks_[cs_.curr_]->getTerminator())
            cs_.B_.CreateBr(cs_.blocks_[cs_.curr_ + 1]);
    }
    return true;
}

bool Compiler::VerifyModule() {
    llvm::raw_string_ostream error_os(error_);
    bool err = llvm::verifyModule(*cs_.module_, &error_os);
    if (err) {
        cs_.module_->dump();
    }
    return !err;
}

bool Compiler::OptimizeModule() {
    llvm::FunctionPassManager fpm(cs_.module_.get());
    fpm.add(llvm::createGVNPass()); // required by SCCP Pass
    fpm.add(llvm::createPromoteMemoryToRegisterPass());
    fpm.add(llvm::createSCCPPass());
    fpm.add(llvm::createAggressiveDCEPass());
    fpm.run(*cs_.function_);
    return true;
}

bool Compiler::CreateEngine() {
    auto module = cs_.module_.get();
    auto engine = llvm::EngineBuilder(cs_.module_.release())
            .setErrorStr(&error_)
            .setOptLevel(OPT_LEVEL)
            .setEngineKind(llvm::EngineKind::JIT)
#ifdef LLL_USE_MCJIT
            .setUseMCJIT(true)
#else
            .setUseMCJIT(false)
#endif
            .create();

    if (engine) {
        engine->finalizeObject();
        engine_.reset(new Engine(engine, module, cs_.function_));
        return true;
    } else {
        return false;
    }
}

void Compiler::CompileMove() {
    auto& ra = stack_.GetR(GETARG_A(cs_.instr_));
    auto& rb = stack_.GetR(GETARG_B(cs_.instr_));
    ra.Assign(rb);
}

void Compiler::CompileLoadk(bool extraarg) {
    auto& ra = stack_.GetR(GETARG_A(cs_.instr_));
    int karg = extraarg ? GETARG_Ax(cs_.proto_->code[cs_.curr_ + 1])
                        : GETARG_Bx(cs_.instr_);
    auto& k = stack_.GetK(karg);
    ra.Assign(k);
}

void Compiler::CompileLoadbool() {
    auto& ra = stack_.GetR(GETARG_A(cs_.instr_));
    ra.SetBoolean(cs_.MakeInt(GETARG_B(cs_.instr_)));
    if (GETARG_C(cs_.instr_))
        cs_.B_.CreateBr(cs_.blocks_[cs_.curr_ + 2]);
}

void Compiler::CompileLoadnil() {
    int start = GETARG_A(cs_.instr_);
    int end = start + GETARG_B(cs_.instr_);
    for (int i = start; i <= end; ++i) {
        auto& r = stack_.GetR(i);
        r.SetTagK(LUA_TNIL);
    }
}

void Compiler::CompileGetupval() {
    auto& ra = stack_.GetR(GETARG_A(cs_.instr_));
    auto& upval = stack_.GetUp(GETARG_B(cs_.instr_));
    ra.Assign(upval);
}

void Compiler::CompileGettabup() {
    auto& table = stack_.GetUp(GETARG_B(cs_.instr_));
    auto& key = stack_.GetRK(GETARG_C(cs_.instr_));
    auto& dest = stack_.GetR(GETARG_A(cs_.instr_));
    TableGet(cs_, stack_, table, key, dest).Compile();
}

void Compiler::CompileGettable() {
    auto& table = stack_.GetR(GETARG_B(cs_.instr_));
    auto& key = stack_.GetRK(GETARG_C(cs_.instr_));
    auto& dest = stack_.GetR(GETARG_A(cs_.instr_));
    TableGet(cs_, stack_, table, key, dest).Compile();
}

void Compiler::CompileSettabup() {
    auto& table = stack_.GetUp(GETARG_A(cs_.instr_));
    auto& key = stack_.GetRK(GETARG_B(cs_.instr_));
    auto& value = stack_.GetRK(GETARG_C(cs_.instr_));
    TableSet(cs_, stack_, table, key, value).Compile();
}

void Compiler::CompileSetupval() {
    auto& upval = stack_.GetUp(GETARG_B(cs_.instr_));
    auto& ra = stack_.GetR(GETARG_A(cs_.instr_));
    upval.Assign(ra);
    cs_.CreateCall("lll_upvalbarrier", {cs_.values_.state, upval.GetUpVal()});
}

void Compiler::CompileSettable() {
    auto& table = stack_.GetR(GETARG_A(cs_.instr_));
    auto& key = stack_.GetRK(GETARG_B(cs_.instr_));
    auto& value = stack_.GetRK(GETARG_C(cs_.instr_));
    TableSet(cs_, stack_, table, key, value).Compile();
}

void Compiler::CompileNewtable() {
    int a = GETARG_A(cs_.instr_);
    int b = GETARG_B(cs_.instr_);
    int c = GETARG_C(cs_.instr_);
    auto& ra = stack_.GetR(a);
    auto args = {cs_.values_.state, ra.GetTValue()};
    auto table = cs_.CreateCall("lll_newtable", args);
    if (b != 0 || c != 0) {
        args = {
            cs_.values_.state,
            table,
            cs_.MakeInt(luaO_fb2int(b)),
            cs_.MakeInt(luaO_fb2int(c))
        };
        cs_.CreateCall("luaH_resize", args);
    }
    auto& ra1 = stack_.GetR(a + 1);
    CompileCheckcg(ra1.GetTValue());
}

void Compiler::CompileSelf() {
    auto& table = stack_.GetR(GETARG_B(cs_.instr_));
    auto& key = stack_.GetRK(GETARG_C(cs_.instr_));
    auto& methodslot = stack_.GetR(GETARG_A(cs_.instr_));
    auto& selfslot = stack_.GetR(GETARG_A(cs_.instr_) + 1);
    selfslot.Assign(table);
    TableGet(cs_, stack_, table, key, methodslot).Compile();
}

void Compiler::CompileUnm() {
    auto entry = cs_.blocks_[cs_.curr_];
    auto checkfloat = cs_.CreateSubBlock("isfloat", entry);
    auto convert = cs_.CreateSubBlock("convert", checkfloat);
    auto intop = cs_.CreateSubBlock("intop", convert);
    auto floatop = cs_.CreateSubBlock("floatop", intop);
    auto tmop = cs_.CreateSubBlock("tmop", floatop);
    auto exit = cs_.blocks_[cs_.curr_ + 1];

    cs_.B_.SetInsertPoint(entry);
    auto& ra = stack_.GetR(GETARG_A(cs_.instr_));
    auto& rb = stack_.GetR(GETARG_B(cs_.instr_));
    auto tag = rb.GetTag();
    auto isint = cs_.B_.CreateICmpEQ(tag, cs_.MakeInt(LUA_TNUMINT));
    cs_.B_.CreateCondBr(isint, intop, checkfloat);

    cs_.B_.SetInsertPoint(checkfloat);
    auto floatval = rb.GetFloat();
    auto isfloat = cs_.B_.CreateICmpEQ(tag, cs_.MakeInt(LUA_TNUMFLT));
    cs_.B_.CreateCondBr(isfloat, floatop, convert);

    cs_.B_.SetInsertPoint(convert);
    auto args = {rb.GetTValue(), cs_.values_.xnumber};
    auto tonumberret = cs_.CreateCall("luaV_tonumber_", args);
    auto convertedval = cs_.B_.CreateLoad(cs_.values_.xnumber);
    auto convok = cs_.ToBool(tonumberret);
    cs_.B_.CreateCondBr(convok, floatop, tmop);

    cs_.B_.SetInsertPoint(intop);
    auto intresult = cs_.B_.CreateNeg(rb.GetInteger(), "intresult");
    ra.SetInteger(intresult);
    cs_.B_.CreateBr(exit);

    cs_.B_.SetInsertPoint(floatop);
    auto floatt = cs_.rt_.GetType("lua_Number");
    auto floatphi = cs_.B_.CreatePHI(floatt, 2, "floatphi");
    floatphi->addIncoming(floatval, checkfloat);
    floatphi->addIncoming(convertedval, convert);
    auto floatresult = cs_.B_.CreateFNeg(floatphi, "floatresult");
    ra.SetFloat(floatresult);
    cs_.B_.CreateBr(exit);

    cs_.B_.SetInsertPoint(tmop);
    auto tm_args = {
        cs_.values_.state,
        rb.GetTValue(),
        rb.GetTValue(),
        ra.GetTValue(),
        cs_.MakeInt(TM_UNM)
    };
    cs_.CreateCall("luaT_trybinTM", tm_args);
    stack_.Update();
    cs_.B_.CreateBr(exit);
}

void Compiler::CompileBNot() {
    auto entry = cs_.blocks_[cs_.curr_];
    auto convert = cs_.CreateSubBlock("convert", entry);
    auto intop = cs_.CreateSubBlock("intop", convert);
    auto tmop = cs_.CreateSubBlock("tmtop", intop);
    auto exit = cs_.blocks_[cs_.curr_ + 1];

    cs_.B_.SetInsertPoint(entry);
    auto& ra = stack_.GetR(GETARG_A(cs_.instr_));
    auto& rb = stack_.GetR(GETARG_B(cs_.instr_));
    auto b_int = rb.GetInteger();
    auto b_is_int = rb.HasTag(LUA_TNUMINT);
    cs_.B_.CreateCondBr(b_is_int, intop, convert);

    cs_.B_.SetInsertPoint(convert);
    auto args = {
        rb.GetTValue(),
        cs_.values_.meminteger,
        cs_.MakeInt(LUA_FLOORN2I)
    };
    auto convresult = cs_.CreateCall("luaV_tointeger", args);
    auto b_conv = cs_.B_.CreateLoad(cs_.values_.meminteger);
    auto b_is_conv = cs_.ToBool(convresult);
    cs_.B_.CreateCondBr(b_is_conv, intop, tmop);

    cs_.B_.SetInsertPoint(intop);
    auto tluainteger = cs_.rt_.GetType("lua_Integer");
    auto b_val = cs_.B_.CreatePHI(tluainteger, 2);
    b_val->addIncoming(b_int, entry);
    b_val->addIncoming(b_conv, convert);
    auto a_val = cs_.B_.CreateNot(b_val);
    ra.SetInteger(a_val);
    cs_.B_.CreateBr(exit);

    cs_.B_.SetInsertPoint(tmop);
    auto tm_args = {
        cs_.values_.state,
        rb.GetTValue(),
        rb.GetTValue(),
        ra.GetTValue(),
        cs_.MakeInt(TM_BNOT)
    };
    cs_.CreateCall("luaT_trybinTM", tm_args);
    stack_.Update();
    cs_.B_.CreateBr(exit);
}

void Compiler::CompileNot() {
    auto entry = cs_.blocks_[cs_.curr_];
    auto checkbool = cs_.CreateSubBlock("checkbool", entry);
    auto assign_by_bool = cs_.CreateSubBlock("assignbool", checkbool);
    auto assign_by_tag = cs_.CreateSubBlock("assignbytag", assign_by_bool);
    auto exit = cs_.blocks_[cs_.curr_ + 1];

    cs_.B_.SetInsertPoint(entry);
    auto& ra = stack_.GetR(GETARG_A(cs_.instr_));
    auto& rb = stack_.GetR(GETARG_B(cs_.instr_));
    auto btag = rb.GetTag();
    auto b_is_nil = cs_.B_.CreateICmpEQ(btag, cs_.MakeInt(LUA_TNIL));
    cs_.B_.CreateCondBr(b_is_nil, assign_by_tag, checkbool);

    cs_.B_.SetInsertPoint(checkbool);
    auto b_is_bool = cs_.B_.CreateICmpEQ(btag, cs_.MakeInt(LUA_TBOOLEAN));
    cs_.B_.CreateCondBr(b_is_bool, assign_by_bool, assign_by_tag);

    cs_.B_.SetInsertPoint(assign_by_tag);
    auto intt = cs_.rt_.MakeIntT();
    auto val = cs_.B_.CreatePHI(intt, 2);
    val->addIncoming(cs_.MakeInt(1), entry);
    val->addIncoming(cs_.MakeInt(0), checkbool);
    ra.SetBoolean(val);
    cs_.B_.CreateBr(exit);

    cs_.B_.SetInsertPoint(assign_by_bool);
    auto b_bool = rb.GetBoolean();
    auto not_b = cs_.B_.CreateICmpEQ(b_bool, cs_.MakeInt(0));
    auto not_b_int = cs_.B_.CreateIntCast(not_b, intt, false);
    ra.SetBoolean(not_b_int);
    cs_.B_.CreateBr(exit);
}

void Compiler::CompileLen() {
    auto& ra = stack_.GetR(GETARG_A(cs_.instr_));
    auto& rkb = stack_.GetRK(GETARG_B(cs_.instr_));
    auto args = {cs_.values_.state, ra.GetTValue(), rkb.GetTValue()};
    cs_.CreateCall("luaV_objlen", args);
    stack_.Update();
}

void Compiler::CompileConcat() {
    int a = GETARG_A(cs_.instr_);
    int b = GETARG_B(cs_.instr_);
    int c = GETARG_C(cs_.instr_);

    cs_.SetTop(c + 1);
    auto args = {cs_.values_.state, cs_.MakeInt(c - b + 1)};
    cs_.CreateCall("luaV_concat", args);
    stack_.Update();

    auto& ra = stack_.GetR(a);
    auto& rb = stack_.GetR(b);
    ra.Assign(rb);

    if (a >= b) {
        auto& ra1 = stack_.GetR(a + 1);
        CompileCheckcg(ra1.GetTValue());
    } else {
        CompileCheckcg(rb.GetTValue());
    }

    cs_.ReloadTop();
}

void Compiler::CompileJmp() {
    int a = GETARG_A(cs_.instr_);
    if (a != 0) {
        auto& r = stack_.GetR(a - 1);
        cs_.CreateCall("luaF_close", {cs_.values_.state, r.GetTValue()});
    }
    cs_.B_.CreateBr(cs_.blocks_[cs_.curr_ + GETARG_sBx(cs_.instr_) + 1]);
}

void Compiler::CompileCmp(const std::string& function) {
    auto& rkb = stack_.GetRK(GETARG_B(cs_.instr_));
    auto& rkc = stack_.GetRK(GETARG_C(cs_.instr_));
    auto args = {cs_.values_.state, rkb.GetTValue(), rkc.GetTValue()};
    auto result = cs_.CreateCall(function, args, "result");
    stack_.Update();

    auto a = cs_.MakeInt(GETARG_A(cs_.instr_));
    auto cmp = cs_.B_.CreateICmpNE(result, a, "cmp");
    auto nextblock = cs_.blocks_[cs_.curr_ + 2];
    auto jmpblock = cs_.blocks_[cs_.curr_ + 1];
    cs_.B_.CreateCondBr(cmp, nextblock, jmpblock);
}

void Compiler::CompileTest() {
    auto checkbool = cs_.CreateSubBlock("checkbool");
    auto checkfalse = cs_.CreateSubBlock("checkfalse", checkbool);
    auto success = cs_.blocks_[cs_.curr_ + 2];
    auto fail = cs_.blocks_[cs_.curr_ + 1];

    auto& r = stack_.GetR(GETARG_A(cs_.instr_));
    if (GETARG_C(cs_.instr_)) {
        auto isnil = r.HasTag(LUA_TNIL);
        cs_.B_.CreateCondBr(isnil, success, checkbool);

        cs_.B_.SetInsertPoint(checkbool);
        auto isbool = r.HasTag(LUA_TBOOLEAN);
        cs_.B_.CreateCondBr(isbool, checkfalse, fail);

        cs_.B_.SetInsertPoint(checkfalse);
        auto bvalue = r.GetBoolean();
        auto isfalse = cs_.B_.CreateICmpEQ(bvalue, cs_.MakeInt(0));
        cs_.B_.CreateCondBr(isfalse, success, fail);
    } else {
        auto isnil = r.HasTag(LUA_TNIL);
        cs_.B_.CreateCondBr(isnil, fail, checkbool);

        cs_.B_.SetInsertPoint(checkbool);
        auto isbool = r.HasTag(LUA_TBOOLEAN);
        cs_.B_.CreateCondBr(isbool, checkfalse, success);

        cs_.B_.SetInsertPoint(checkfalse);
        auto bvalue = r.GetBoolean();
        auto isfalse = cs_.B_.CreateICmpEQ(bvalue, cs_.MakeInt(0));
        cs_.B_.CreateCondBr(isfalse, fail, success);
    }
}

void Compiler::CompileTestset() {
    auto checkbool = cs_.CreateSubBlock("checkbool");
    auto checkfalse = cs_.CreateSubBlock("checkfalse", checkbool);
    auto fail = cs_.CreateSubBlock("set", checkfalse);
    auto success = cs_.blocks_[cs_.curr_ + 2];

    auto& r = stack_.GetR(GETARG_B(cs_.instr_));
    if (GETARG_C(cs_.instr_)) {
        auto isnil = r.HasTag(LUA_TNIL);
        cs_.B_.CreateCondBr(isnil, success, checkbool);

        cs_.B_.SetInsertPoint(checkbool);
        auto isbool = r.HasTag(LUA_TBOOLEAN);
        cs_.B_.CreateCondBr(isbool, checkfalse, fail);

        cs_.B_.SetInsertPoint(checkfalse);
        auto bvalue = r.GetBoolean();
        auto isfalse = cs_.B_.CreateICmpEQ(bvalue, cs_.MakeInt(0));
        cs_.B_.CreateCondBr(isfalse, success, fail);
    } else {
        auto isnil = r.HasTag(LUA_TNIL);
        cs_.B_.CreateCondBr(isnil, fail, checkbool);

        cs_.B_.SetInsertPoint(checkbool);
        auto isbool = r.HasTag(LUA_TBOOLEAN);
        cs_.B_.CreateCondBr(isbool, checkfalse, success);

        cs_.B_.SetInsertPoint(checkfalse);
        auto bvalue = r.GetBoolean();
        auto isfalse = cs_.B_.CreateICmpEQ(bvalue, cs_.MakeInt(0));
        cs_.B_.CreateCondBr(isfalse, fail, success);
    }

    cs_.B_.SetInsertPoint(fail);
    auto& ra = stack_.GetR(GETARG_A(cs_.instr_));
    ra.Assign(r);
    cs_.B_.CreateBr(cs_.blocks_[cs_.curr_ + 1]);
}

void Compiler::CompileCall() {
    int a = GETARG_A(cs_.instr_);
    int b = GETARG_B(cs_.instr_);
    if (b != 0)
        cs_.SetTop(a + b);
    auto& ra = stack_.GetR(a);
    auto args = {
        cs_.values_.state,
        ra.GetTValue(),
        cs_.MakeInt(GETARG_C(cs_.instr_) - 1)
    };
    cs_.CreateCall("luaD_callnoyield", args);
    stack_.Update();
}

void Compiler::CompileTailcall() {
    // Tailcall returns a negative value that signals the call must be performed
    if (cs_.proto_->sizep > 0)
        cs_.CreateCall("luaF_close", {cs_.values_.state, cs_.GetBase()});
    int a = GETARG_A(cs_.instr_);
    int b = GETARG_B(cs_.instr_);
    if (b != 0)
        cs_.SetTop(a + b);
    auto diff = cs_.TopDiff(a);
    auto ret = cs_.B_.CreateNeg(diff, "ret");
    cs_.B_.CreateRet(ret);
}

void Compiler::CompileReturn() {
    if (cs_.proto_->sizep > 0)
        cs_.CreateCall("luaF_close", {cs_.values_.state, cs_.GetBase()});
    int a = GETARG_A(cs_.instr_);
    int b = GETARG_B(cs_.instr_);
    llvm::Value* nresults = nullptr;
    if (b == 0) {
        nresults = cs_.TopDiff(GETARG_A(cs_.instr_));
    } else if (b == 1) {
        nresults = cs_.MakeInt(0);
    } else {
        nresults = cs_.MakeInt(b - 1);
        cs_.SetTop(a + b - 1);
    }
    cs_.B_.CreateRet(nresults);
}

void Compiler::CompileForloop() {
    auto entry = cs_.blocks_[cs_.curr_];
    auto intcheck = cs_.CreateSubBlock("intcheck", entry);
    auto intgoback = cs_.CreateSubBlock("intgoback", intcheck);
    auto floatcheck = cs_.CreateSubBlock("floatcheck", intgoback);
    auto floatgoback = cs_.CreateSubBlock("floatgoback", floatcheck);
    auto exit = cs_.blocks_[cs_.curr_ + 1];
    auto jumpblock = cs_.blocks_[cs_.curr_ + 1 + GETARG_sBx(cs_.instr_)];

    cs_.B_.SetInsertPoint(entry);
    auto& ra = stack_.GetR(GETARG_A(cs_.instr_));
    auto& ra1 = stack_.GetR(GETARG_A(cs_.instr_) + 1);
    auto& ra2 = stack_.GetR(GETARG_A(cs_.instr_) + 2);
    auto& ra3 = stack_.GetR(GETARG_A(cs_.instr_) + 3);
    auto a_is_int = ra.HasTag(LUA_TNUMINT);
    cs_.B_.CreateCondBr(a_is_int, intcheck, floatcheck);

    cs_.B_.SetInsertPoint(intcheck); {
    auto step = ra2.GetInteger();
    auto oldidx = ra.GetInteger();
    auto idx = cs_.B_.CreateAdd(oldidx, step);
    auto limit = ra1.GetInteger();
    auto idx_le_limit = cs_.B_.CreateICmpSLE(idx, limit);
    auto limit_le_idx = cs_.B_.CreateICmpSLE(limit, idx);
    auto zero = cs_.MakeInt(0, step->getType());
    auto step_ltz = cs_.B_.CreateICmpSLE(step, zero);
    auto condition = cs_.B_.CreateSelect(step_ltz, limit_le_idx, idx_le_limit);
    cs_.B_.CreateCondBr(condition, intgoback, exit);

    cs_.B_.SetInsertPoint(intgoback);
    ra.SetValue(idx);
    ra3.SetInteger(idx);
    cs_.B_.CreateBr(jumpblock); }

    cs_.B_.SetInsertPoint(floatcheck); {
    auto step = ra2.GetFloat();
    auto oldidx = ra.GetFloat();
    auto idx = cs_.B_.CreateFAdd(oldidx, step);
    auto limit = ra1.GetFloat();
    auto idx_le_limit = cs_.B_.CreateFCmpOLE(idx, limit);
    auto limit_le_idx = cs_.B_.CreateFCmpOLE(limit, idx);
    auto zero = llvm::ConstantFP::get(step->getType(), 0.0);
    auto step_ltz = cs_.B_.CreateFCmpOLE(step, zero);
    auto condition = cs_.B_.CreateSelect(step_ltz, limit_le_idx, idx_le_limit);
    cs_.B_.CreateCondBr(condition, floatgoback, exit);

    cs_.B_.SetInsertPoint(floatgoback);
    ra.SetValue(idx);
    ra3.SetFloat(idx);
    cs_.B_.CreateBr(jumpblock); }
}

void Compiler::CompileForprep() {
    auto& ra = stack_.GetR(GETARG_A(cs_.instr_));
    auto args = {cs_.values_.state, ra.GetTValue()};
    cs_.CreateCall("lll_forprep", args);
    cs_.B_.CreateBr(cs_.blocks_[cs_.curr_ + 1 + GETARG_sBx(cs_.instr_)]);
}

void Compiler::CompileTforcall() {
    int a = GETARG_A(cs_.instr_);
    int cb = a + 3;
    auto& rcb = stack_.GetR(cb);
    rcb.Assign(stack_.GetR(a));
    stack_.GetR(cb + 1).Assign(stack_.GetR(a + 1));
    stack_.GetR(cb + 2).Assign(stack_.GetR(a + 2));
    cs_.SetTop(cb + 3);
    auto args = {
        cs_.values_.state,
        rcb.GetTValue(),
        cs_.MakeInt(GETARG_C(cs_.instr_))
    };
    cs_.CreateCall("luaD_callnoyield", args);
    stack_.Update();
    cs_.ReloadTop();
}

void Compiler::CompileTforloop() {
    int a = GETARG_A(cs_.instr_);
    auto& ra1 = stack_.GetR(a + 1);
    auto isnil = ra1.HasTag(LUA_TNIL);
    auto end = cs_.blocks_[cs_.curr_ + 1];
    auto cont = cs_.CreateSubBlock("continue");
    cs_.B_.CreateCondBr(isnil, end, cont);

    cs_.B_.SetInsertPoint(cont);
    auto& ra = stack_.GetR(a);
    ra.Assign(ra1);
    cs_.B_.CreateBr(cs_.blocks_[cs_.curr_ + 1 + GETARG_sBx(cs_.instr_)]);
}

void Compiler::CompileSetlist() {
    int a = GETARG_A(cs_.instr_);
    int b = GETARG_B(cs_.instr_);
    int c = GETARG_C(cs_.instr_);
    if (c == 0)
        c = GETARG_Ax(cs_.proto_->code[cs_.curr_ + 1]);

    auto n = (b != 0 ? cs_.MakeInt(b) : cs_.TopDiff(a + 1));
    auto fields = cs_.MakeInt((c - 1) * LFIELDS_PER_FLUSH);

    auto& ra = stack_.GetR(a);
    auto args = {cs_.values_.state, ra.GetTValue(), fields, n};
    cs_.CreateCall("lll_setlist", args);
    cs_.ReloadTop();
}

void Compiler::CompileClosure() {
    int a = GETARG_A(cs_.instr_);
    auto& ra = stack_.GetR(a);
    auto args = {
        cs_.values_.state,
        cs_.values_.closure,
        cs_.GetBase(),
        ra.GetTValue(),
        cs_.MakeInt(GETARG_Bx(cs_.instr_))
    };
    cs_.CreateCall("lll_closure", args);
    auto& ra1 = stack_.GetR(a + 1);
    CompileCheckcg(ra1.GetTValue());
}

void Compiler::CompileCheckcg(llvm::Value* reg) {
    auto args = {cs_.values_.state, cs_.values_.ci, reg};
    cs_.CreateCall("lll_checkcg", args);
}

}


text:
{% import "macros.html" as macros %}

        {%- if method.isDeprecated -%}

            Deprecated

        {%- endif -%}
        {$ method.name $}

  {%- if method.description -%}

      {$ method.description | marked | safe $}

  {%- endif -%}

  {%- if method.params.length -%}

      Parameters

  {% for parameter in method.params %}

        {$ parameter.name $}
        {%- if parameter.isOptional -%}
          ?
        {%- endif -%}

      {$ parameter.type $}

        {$ parameter.description | marked | safe $}

  {% endfor %}
  {%- endif -%}

  {%- if method.type and method.type !== "void" -%}

      Returns

      {$ method.type $}

        {$ method.returns.description | marked | safe $}

  {%- endif -%}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using SilverlightMappingToolBasic.UI.SuperGraph.View.MessageBox;
using SilverlightMappingToolBasic.UI.SuperGraph.View.PropertiesEditorSupportClasses;
using SilverlightMappingToolBasic.UI.ViewModel;
using Telerik.Windows.Controls;
using Telerik.Windows.Documents;
using Telerik.Windows.Documents.FormatProviders.Html;
using Telerik.Windows.Documents.FormatProviders.Html.Import;
using Telerik.Windows.Documents.Layout;
using Telerik.Windows.Documents.Model;
using SelectionChangedEventArgs = Telerik.Windows.Controls.SelectionChangedEventArgs;
using Telerik.Windows.Documents.UI.Extensibility;
using System.ComponentModel.Composition.Hosting;

using Telerik.Windows.Controls.RichTextBoxUI.Dialogs;
using Telerik.Windows.Controls.RichTextBoxUI;
using Telerik.Windows.Documents.Proofing;
using EditCustomDictionaryDialog = Telerik.Windows.Controls.RichTextBoxUI.Dialogs.EditCustomDictionaryDialog;

namespace SilverlightMappingToolBasic.UI.SuperGraph.View.RichTextSupportClasses
{
    public partial class TelerikRichTextEditor : UserControl
    {
        private HtmlFormatProvider _htmlFormatProvider;
        private int _descriptionWidth;
        private int _descriptionHeight;
        private InsertPictureDialog _insertPictureDialog;

        public InsertPictureDialog InsertPictureDialog
        {
            get
            {
                if (_insertPictureDialog == null)
                {
                    _insertPictureDialog = new InsertPictureDialog();
                }
                return _insertPictureDialog;
            }
        }

        public HtmlFormatProvider HtmlFormatProvider
        {
            get
            {
                if (_htmlFormatProvider == null)
                {
                    _htmlFormatProvider = new HtmlFormatProvider();
                    _htmlFormatProvider.ExportSettings.StylesExportMode = StylesExportMode.Inline;
                    _htmlFormatProvider.ExportSettings.DocumentExportLevel = DocumentExportLevel.Fragment;
                    _htmlFormatProvider.ExportSettings.ExportBoldAsStrong = true;
                    _htmlFormatProvider.ExportSettings.ExportEmptyDocumentAsEmptyString = true;
                    _htmlFormatProvider.ExportSettings.ExportFontStylesAsTags = true;
                    _htmlFormatProvider.ExportSettings.ExportHeadingsAsTags = true;
                    _htmlFormatProvider.ExportSettings.ExportItalicAsEm = true;
                    _htmlFormatProvider.ExportSettings.ExportStyleMetadata = false;
                    _htmlFormatProvider.ExportSettings.ExportLocalOrStyleValueSource = false;
                    _htmlFormatProvider.ExportSettings.ImageExportMode = ImageExportMode.ImageExportingEvent;
                    _htmlFormatProvider.ExportSettings.ImageExporting += ExportSettingsOnImageExporting;

                    _htmlFormatProvider.ExportSettings.StyleRepositoryExportMode = StyleRepositoryExportMode.DontExportStyles;
                    _htmlFormatProvider.ImportSettings.UseDefaultStylesheetForFontProperties = false;
                    _htmlFormatProvider.ImportSettings.UseHtmlHeadingStyles = false;
                    _htmlFormatProvider.ImportSettings.LoadImageFromUrl += ImportSettingsOnLoadImageFromUrl;
                }
                return _htmlFormatProvider;
            }
        }

        private void ImportSettingsOnLoadImageFromUrl(object sender, LoadImageEventArgs e)
        {
            try
            {
                if (e.Url != null)
                {
                    var extension = System.IO.Path.GetExtension(e.Url);
                    var uri = new Uri(e.Url, UriKind.RelativeOrAbsolute);
                    var client = new WebClient();
                    client.OpenReadCompleted += (s, a) =>
                    {
                        if (a.Error == null)
                        {
                            try
                            {
                                e.ImageElement.Init(a.Result, extension.Remove(0,1));
                            }
                            catch
                            {
                                //Handle errors
                            }
                        }
                        else
                        {
                            //External URL
                        }
                    };
                    client.OpenReadAsync(uri);
                }
            }
            catch
            {
                //Handle errors
            }
        }

        private void ExportSettingsOnImageExporting(object sender, ImageExportingEventArgs e)
        {
            e.Src = e.Image.UriSource.ToString();
            if (e.Image.Height.Equals(10) && e.Image.Width.Equals(10))
            {

            }

        }

        public INodeProperties NodeProperties
        {
            get
            {
                var context = DataContext as INodeProperties;
                if (context != null)
                {
                    return context;
                }
                return null;
            }
        }

        public TelerikRichTextEditor()
        {
            InitializeComponent();
            InsertPictureDialog.InsertClicked += InsertPictureDialogOnInsertClicked;
            RadRichTextBox.IsImageMiniToolBarEnabled = false;

            RadCompositionInitializer.Catalog = new TypeCatalog(
                // format providers - we only use the HtmlFormatProvider
                //typeof(XamlFormatProvider),
                //typeof(RtfFormatProvider),
                //typeof(DocxFormatProvider),
                //typeof(PdfFormatProvider),
                typeof(HtmlFormatProvider),
                //typeof(TxtFormatProvider),

                // mini toolbars
                typeof(SelectionMiniToolBar),
                typeof(ImageMiniToolBar),

                // context menu
                typeof(Telerik.Windows.Controls.RichTextBoxUI.ContextMenu),

                // the default English spellchecking dictionary
                typeof(RadEn_USDictionary),

                // dialogs
                typeof(AddNewBibliographicSourceDialog),
                typeof(ChangeEditingPermissionsDialog),
                typeof(EditCustomDictionaryDialog),
                typeof(FindReplaceDialog),
                typeof(FloatingBlockPropertiesDialog),
                typeof(FontPropertiesDialog),
                //typeof(ImageEditorDialog), //we don't use the image editor dialog
                typeof(CodeFormattingDialog),
                typeof(InsertCaptionDialog),
                typeof(InsertCrossReferenceWindow),
                typeof(InsertDateTimeDialog),
                typeof(InsertTableDialog),
                typeof(InsertTableOfContentsDialog),
                typeof(ManageBibliographicSourcesDialog),
                typeof(ManageBookmarksDialog),
                typeof(ManageStylesDialog),
                typeof(NotesDialog),
                typeof(ProtectDocumentDialog),
                typeof(RadInsertHyperlinkDialog),
                typeof(RadInsertSymbolDialog),
                typeof(RadParagraphPropertiesDialog),
                typeof(SetNumberingValueDialog),
                typeof(SpellCheckingDialog),
                typeof(StyleFormattingPropertiesDialog),
                typeof(TableBordersDialog),
                typeof(TablePropertiesDialog),
                typeof(TabStopsPropertiesDialog),
                typeof(UnprotectDocumentDialog),
                typeof(WatermarkSettingsDialog)
            );
        }

        private void InsertPictureDialogOnInsertClicked(object sender, InsertImageEventArgs e)
        {
            var image = new ImageInline();
            image.UriSource = e.Url;
            image.Extension = Path.GetExtension(e.Url.ToString());
            image.Width = e.Width;
            image.Height = e.Height;
            // Insert the image at current caret position.
            RadRichTextBox.InsertInline(image);
        }

        public RadDocument RadDocument
        {
            get
            {
                return RadRichTextBox.Document;
            }
        }

        private void SetupNewDocument(RadDocument document)
        {
            document.LayoutMode = DocumentLayoutMode.Flow;
            //document.ParagraphDefaultSpacingAfter = 10;
            document.SectionDefaultPageMargin = new Padding(95);
        }

        private bool IsSupportedImageFormat(string extension)
        {
            if (extension != null)
            {
                extension = extension.ToLower();
            }

            return extension == ".jpg" ||
                extension == ".jpeg" ||
                extension == ".png" ||
                extension == ".bmp";
        }

        private void UserControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (NodeProperties != null)
            {
                LoadHtml(NodeProperties.Description);
            }
            else
            {
                RadRichTextBox.Document = new RadDocument();
            }
        }

        public void LoadHtml(string description)
        {
            var html = new HtmlAgilityPack.HtmlDocument();
            html.LoadHtml(description);

            var doc = HtmlFormatProvider.Import(description);

            SetupNewDocument(doc);
            RadRichTextBox.Document = doc;
        }

        public string GetRawText()
        {
            var description = HtmlFormatProvider.Export(RadRichTextBox.Document);

            //if (_descriptionWidth > 0)
            //{
            //    //custom sizing provided
            //    return string.Format(@"
{2}
", _descriptionWidth, _descriptionHeight, description);
            //}
            if (string.IsNullOrWhiteSpace(description))
            {
                //no content, return empty
                return string.Empty;
            }
            return description;
            ////no custom sizing but want to mark it up as coming from the RichTextEdit rather than the advanced
            //return string.Format(@"
{0}
", description);
        }

        ///
        /// This method is provided for when populating the HtmlEditor in Advanced (Raw) mode, it doesn't insert the GlymaNodeDescription DIV around the content
        ///
        /// <returns></returns>
        public string GetRawTextForAdvancedMode()
        {
            var description = HtmlFormatProvider.Export(RadRichTextBox.Document);
            if (description.Length > 8000)
            {
                SuperMessageBoxService.ShowError("Save Description Failed", "Sorry, your description is too long.");
                description = NodeProperties.Description;
            }
            if (string.IsNullOrWhiteSpace(description))
            {
                //no content, return empty
                return string.Empty;
            }
            else
            {
                return description;
            }
        }

        //private void WidthSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    var item = WidthSelector.SelectedItem as RadRibbonComboBoxItem;
        //    if (item != null)
        //    {
        //        int.TryParse(item.Tag.ToString(), out _descriptionWidth);
        //    }
        //    else
        //    {
        //        _descriptionWidth = 0;
        //    }
        //}

        //private void WidthSelector_LostFocus(object sender, RoutedEventArgs e)
        //{
        //    if (WidthSelector.Text != "Default")
        //    {
        //        int temp;
        //        if (int.TryParse(WidthSelector.Text, out temp))
        //        {
        //            _descriptionWidth = temp;
        //        }
        //        else if (!string.IsNullOrEmpty(WidthSelector.Text))
        //        {
        //            WidthSelector.Text = _descriptionWidth.ToString();
        //        }
        //    }
        //}

        //private void HeightSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    var item = HeightSelector.SelectedItem as RadRibbonComboBoxItem;
        //    if (item != null)
        //    {
        //        int.TryParse(item.Tag.ToString(), out _descriptionHeight);
        //    }
        //    else
        //    {
        //        _descriptionHeight = 0;
        //    }
        //}

        //private void HeightSelector_LostFocus(object sender, RoutedEventArgs e)
        //{
        //    if (HeightSelector.Text != "Default")
        //    {
        //        int temp;
        //        if (int.TryParse(HeightSelector.Text, out temp))
        //        {
        //            _descriptionHeight = temp;
        //        }
        //        else if (!string.IsNullOrEmpty(HeightSelector.Text))
        //        {
        //            HeightSelector.Text = _descriptionHeight.ToString();
        //        }
        //    }
        //}

        private void RadRibbonButton_Click(object sender, RoutedEventArgs e)
        {
            if (!RadRichTextBox.Document.Selection.IsEmpty)
            {
                var selected = RadRichTextBox.Document.Selection.GetSelectedSingleInline() as ImageInline;
                if (selected != null)
                {
                    InsertPictureDialog.DataContext = selected;
                }
            }
            else
            {
                InsertPictureDialog.DataContext = new ImageInline();
            }
            InsertPictureDialog.ShowDialog();
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.github.farhan3.jclickerquiz.common</title>
<meta name="date" content="2015-03-16">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.github.farhan3.jclickerquiz.common

Class Summary

Class
Description

Protocol

This protocol handles communication between the client and server.

Enum Summary

Enum
Description

Option

Available options.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
class HackathonStanford < BadgeBase
  describe "Stanford Hackathon",
           skill:       'Hacking',
           description: "Participated in Stanford's premier Hackathon, organized by the ACM, SVI Hackspace and BASES.",
           for:         "participating in Stanford's premier Hackathon, organized by the ACM, SVI Hackspace and BASES.",
           image_name:  'hackathonStanford.png'

  def reasons
    @reasons ||= begin
      links = []
      user.facts.each do |fact|
        if fact.tagged?('hackathon', 'university') && fact.metadata[:school] == 'Stanford'
          links << { fact.name => fact.url }
        end
      end
      { links: links }
    end
  end
end


text:
// @flow

/**
 * Does the last story item id submitted by the client match the last one in
 * the database. If not, then the user is submitting an out of date entry. So
 * fail it.
 */
const doesLastStoryIDMatch = (storyItems, userLastStoryItemID) => {
  if (!storyItems.length) return true;

  const lastStoryItemID = storyItems[storyItems.length - 1];

  if (!lastStoryItemID) return true;

  return userLastStoryItemID === lastStoryItemID;
};

/**
 * Does the last saved story item user match the one currently adding a new
 * entry
 */
const wasThisUserLastUser = (storyItemsByID, lastStoryItemID, userName) => {
  if (!lastStoryItemID) return false;

  const story = storyItemsByID[lastStoryItemID];

  if (!story) throw new Error('Could not get a story item at the given id');

  return story.userName === userName;
};

/**
 * Return an error for the new story item if there is an error. Checks:
 * - The story item id has not already been added
 * - The last story item the user wrote against matches the last one saved here
 * - This user was not the last author
 */
const getStoryEntryError = (
  { storyItems, storyItemsByID },
  { userName, userLastStoryItemID, id }
) => {
  if (storyItems.includes(id)) {
    return { error: 'STORY_ITEM_ALREADY_ADDED' };
  }

  if (!doesLastStoryIDMatch(storyItems, userLastStoryItemID)) {
    return { error: 'LAST_STORY_ID_MISMATCH' };
  }

  if (wasThisUserLastUser(storyItemsByID, userLastStoryItemID, userName)) {
    return { error: 'WAS_LAST_USER' };
  }

  return { error: null };
};

/**
 * Create a blank story with the given id
 */
const createNewStory = (db, storyID) =>
  db.set(['storiesByID', storyID], {
    id: storyID,
    storyItems: [],
    storyItemsByID: {},
  });

export const Query = {
  getStoryItems: ({ id }: { id: string }, db) =>
    db
      .get(['storiesByID', id])
      .then((story) => {
        if (story) return story;

        // Here we are creating the story, in future we will throw here instead
        return createNewStory(db, id);
      })
      .then((story) => {
        if (!story.storyItems) return [];

        return story.storyItems.map(storyItemID => story.storyItemsByID[storyItemID]);
      }),
};

export const Mutation = {
  setStoryItem: (
    {
      storyID, storyItemID, text, userName, lastStoryItemID,
    },
    db
  ) =>
    db
      .get(['storiesByID', storyID])
      .then((story) => {
        if (story) return story;

        // Here we are creating the story, in future we will throw here instead
        return createNewStory(db, storyID);
      })
      .then((story) => {
        const storyItem = {
          id: storyItemID,
          text,
          userName,
        };

        const newStoryItems = story.storyItems || [];
        const storyItemsByID = Object.assign({}, story.storyItemsByID || {});

        const { error } = getStoryEntryError(
          { storyItems: newStoryItems, storyItemsByID },
          { userName, userLastStoryItemID: lastStoryItemID, id: storyItem.id }
        );

        if (error) {
          return Query.getStoryItems({ id: storyID }, db).then(storyItems => ({
            error,
            storyItems,
          }));
        }

        newStoryItems.push(storyItem.id);

        storyItemsByID[storyItemID] = storyItem;

        return db
          .update(['storiesByID', storyID], {
            storyItems: newStoryItems,
            storyItemsByID,
          })
          .then(() => Query.getStoryItems({ id: storyID }, db))
          .then(storyItems => ({
            error: null,
            storyItems,
          }));
      }),
};


text:
from limbo.apps.datatables.tables import *
from limbo.apps.datatables.rendering import *
from limbo.apps.datatables.util import *
from limbo.apps.datatables.fields import *


text:
<?php

namespace MongoDB\GridFS\Exception;

use MongoDB\Exception\RuntimeException;

use function sprintf;

class CorruptFileException extends RuntimeException
{
    /**
     * Thrown when a chunk doesn't contain valid data.
     */
    public static function invalidChunkData(int $chunkIndex): self
    {
        return new static(sprintf('Invalid data found for index "%d"', $chunkIndex));
    }

    /**
     * Thrown when a chunk is not found for an expected index.
     *
     * @param integer $expectedIndex Expected index number
     * @return self
     */
    public static function missingChunk(int $expectedIndex)
    {
        return new static(sprintf('Chunk not found for index "%d"', $expectedIndex));
    }

    /**
     * Thrown when a chunk has an unexpected index number.
     *
     * @param integer $index         Actual index number (i.e. "n" field)
     * @param integer $expectedIndex Expected index number
     * @return self
     */
    public static function unexpectedIndex(int $index, int $expectedIndex)
    {
        return new static(sprintf('Expected chunk to have index "%d" but found "%d"', $expectedIndex, $index));
    }

    /**
     * Thrown when a chunk has an unexpected data size.
     *
     * @param integer $size         Actual size (i.e. "data" field length)
     * @param integer $expectedSize Expected size
     * @return self
     */
    public static function unexpectedSize(int $size, int $expectedSize)
    {
        return new static(sprintf('Expected chunk to have size "%d" but found "%d"', $expectedSize, $size));
    }
}


text:
package org.iotivity.base.examples;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;

/**
 * SimpleBase is a sample OCF Base layer application.
 * It can handle message and bluetooth manually.
 */
public class SimpleBase extends Activity implements DrawerFragment.DrawerCallbacks {

    private static final String TAG = "OIC_SIMPLE_BASE";
    private DrawerFragment      mDrawerFragment;

    private CharSequence        mTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simplebase);

        mDrawerFragment = (DrawerFragment) getFragmentManager()
                .findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        mDrawerFragment.setUp(R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));
    }

    @Override
    public void onDrawerItemSelected(int position) {
        Fragment fragment;
        switch (position) {
            case 0:
                mTitle = getString(R.string.title_message);
                fragment = new MessageFragment();
                break;
            case 1:
                mTitle = getString(R.string.title_bluetooth);
                fragment = new BluetoothFragment();
                break;
            case 2:
                mTitle = getString(R.string.title_cloud);
                fragment = new CloudFragment();
                break;
            case 3:
                mTitle = getString(R.string.title_template);
                fragment = new TemplateFragment();
                break;
            default:
                mTitle = getString(R.string.title_message);
                fragment = new MessageFragment();
                break;
        }
        getFragmentManager().beginTransaction()
                            .replace(R.id.container, fragment)
                            .commit();

        getActionBar().setTitle(mTitle);
    }

    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.d(TAG, "onNewIntent with changes sending broadcast IN ");

        Intent i = new Intent();
        i.setAction(intent.getAction());
        i.putExtra(NfcAdapter.EXTRA_NDEF_MESSAGES,
                intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES));
        sendBroadcast(i);
        Log.d(TAG, "Initialize Context again resetting");
    }
}


text:
No users match this pattern!

Users that match the given pattern:

        {{user.username}}


text:
package com.spotify.flo.contrib.styx;

import com.fasterxml.jackson.annotation.JsonProperty;
import io.norberg.automatter.AutoMatter;

@AutoMatter
interface StructuredLogMessage {
  @AutoMatter
  interface Styx {
    @JsonProperty String component_id();
    @JsonProperty String workflow_id();
    @JsonProperty String docker_args();
    @JsonProperty String docker_image();
    @JsonProperty String commit_sha();
    @JsonProperty String parameter();
    @JsonProperty String execution_id();
    @JsonProperty String trigger_id();
    @JsonProperty String trigger_type();

    static StyxBuilder newBuilder() {
      return new StyxBuilder();
    }
  }

  @AutoMatter
  interface Task {
    @JsonProperty String id();
    @JsonProperty String name();
    @JsonProperty String args();

    static TaskBuilder newBuilder() {
      return new TaskBuilder();
    }
  }

  @AutoMatter
  interface Workflow {
    @JsonProperty Styx styx();
    @JsonProperty String framework();
    @JsonProperty Task task();

    static WorkflowBuilder newBuilder() {
      return new WorkflowBuilder().framework("flo");
    }
  }

  @JsonProperty String time();
  @JsonProperty String severity();
  @JsonProperty String logger();
  @JsonProperty String thread();
  @JsonProperty String message();
  @JsonProperty Workflow workflow();

  static StructuredLogMessageBuilder newBuilder() {
    return new StructuredLogMessageBuilder();
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:paddingLeft="7dip"
    android:paddingRight="7dip"
    android:paddingBottom="0dip"
    android:paddingTop="0dip"
    android:gravity="end|right">

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="106dp"
        android:layout_height="106dp"

        >

        <ImageView
            android:id="@+id/profile_picture"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scaleType="centerCrop"
            android:src="@drawable/mati_profile"
            android:layout_gravity="center"

            android:padding="6dp"
            />

        <ImageView
            android:id="@+id/frame_contact"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scaleType="centerCrop"
            android:src="@drawable/object_frame_1x1"
            android:layout_gravity="center"

            />

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:paddingLeft="8dip"
            android:paddingRight="8dip"
            android:paddingTop="3dip"
            android:paddingBottom="8dip"

            >

            <TextView
                android:id="@+id/contact_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"

                android:textColor="#FFFFFFFF"
                android:textSize="12sp"
                android:textStyle="bold"
                android:text="New contact name"

                android:background="@color/black_overlay"
                android:layout_gravity="center"

                android:paddingLeft="8dip"
                android:paddingRight="8dip"
                />
        </FrameLayout>

        <ImageView
            android:id="@+id/icon_edit_profile"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scaleType="centerCrop"
            android:src="@drawable/ic_action_email"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"
            android:paddingLeft="7dp"
            android:paddingRight="7dp"
            android:paddingBottom="7dp"
            android:paddingTop="7dp"
            android:onClick="onItemSelectedClicked"

            />

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="106dp"

        >

        <ImageView
            android:id="@+id/frame_tx_record"
            android:layout_width="match_parent"
            android:layout_height="106dp"
            android:scaleType="centerCrop"

            android:layout_gravity="center"
            android:background="@drawable/object_frame_3x1_filled"
            />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_alignParentRight="true"

            >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:paddingLeft="10dip"
                android:paddingRight="10dip"
                android:paddingTop="10dip">

                <ImageButton
                    android:id="@+id/amount"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center_vertical|end"
                    android:paddingBottom="1dip"
                    android:paddingTop="2dip"
                    android:src="@drawable/abc_menu_hardkey_panel_mtrl_mult"
                    android:layout_gravity="end" />
            </LinearLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:paddingLeft="10dip"
                android:paddingRight="10dip"
                android:gravity="center"
                android:weightSum="1">

                <TextView
                    android:id="@+id/text_view_phrase"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center_vertical"
                    android:textColor="#FF666666"
                    android:textSize="14sp"
                    android:textStyle="normal"
                    android:text="Matias Furszyfer want to add you!!"
                    android:layout_gravity="start"
                    android:paddingBottom="1dip"
                    android:paddingTop="1dip" />

            </RelativeLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:paddingLeft="10dip"
                android:paddingRight="10dip" android:paddingBottom="2dip" android:paddingTop="2dip">

                <Space

                    android:layout_width="wrap_content"
                    android:layout_height="7dp"
                    android:gravity="center_vertical"
                    android:layout_gravity="start"
                    android:paddingBottom="5dip"
                    android:paddingTop="5dip" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingLeft="10dip"
                android:paddingRight="10dip"
                android:paddingBottom="7dip"
                android:layout_gravity="bottom">
                <ImageView
                    android:id="@+id/action_cancel"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_action_cancel_grey"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentBottom="true"
                    android:layout_weight="1"/>
                <ImageView
                    android:id="@+id/action_accept"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_action_accept_grey"
                    android:layout_alignParentRight="true"
                    android:layout_alignParentBottom="true"
                    android:layout_weight="1"/>
            </LinearLayout>
        </LinearLayout>
    </RelativeLayout>
</LinearLayout>


text:
extract () {
  # Extract any provided archive
  # https://gist.github.com/Jaxmetalmax/f0ec6d2f86474d8d319b
  if [ -f $1 ] ; then
    case $1 in
      *.tar.bz2) tar xjf $1 ;;
      *.tar.gz) tar xzf $1 ;;
      *.bz2) bunzip2 $1 ;;
      *.rar) rar x $1 ;;
      *.gz) gunzip $1 ;;
      *.tar) tar xf $1 ;;
      *.tbz2) tar xjf $1 ;;
      *.tgz) tar xzf $1 ;;
      *.zip) unzip $1 ;;
      *.Z) uncompress $1 ;;
      *) echo "'$1' cannot be extracted via extract()" ;;
    esac
  else
    echo "'$1' is not a valid file"
  fi
}

function _get_computer_id {
  # Hash the computer mac address to determine a unique id.
  # https://unix.stackexchange.com/questions/144812/generate-consistent-machine-unique-id
  echo $(
    ip a |
    sed '\|^ *link[^ ]* |!d;s|||;s| .*||' |  # extract mac addresses
    sha256sum |  # hash the results
    awk '{print $1}'  # remove trailing dashe introduced by sha256sum
  )
}

function _change_background {
  pic_dir="/home/rll/Pictures"
  echo "Scanning $pic_dir"
  pic_file=$(find $pic_dir | grep jpg | shuf -n1)
  echo "Changing background to $pic_file"
  #gconftool-2 --type string --set /desktop/gnome/background/picture_filename "${pic_file}"
  gsettings set org.gnome.desktop.background picture-uri $pic_file
}

function _does_command_exist {
  # Test for a given command. Return 1 if the command exist on the system, 0 otherwise.
  type $1 > /dev/null 2>&1
  if [ $? -eq 0 ]
  then
    return 0
  else
    return 1
  fi
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Rhizocarpon ignobile Th. Fr.

### Remarks
null


text:
package org.jkiss.dbeaver.registry.driver;

import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;

import java.util.Collection;
import java.util.StringTokenizer;

/**
 * DriverUtils
 */
public class DriverUtils
{

    public static boolean isBetaVersion(@NotNull String versionInfo) {
        return versionInfo.contains("beta") || versionInfo.contains("alpha");
    }

    @Nullable
    public static String findLatestVersion(@NotNull Collection<String> allVersions) {
        String latest = null;
        for (String version : allVersions) {
            if (isBetaVersion(version)) {
                continue;
            }
            if (latest == null || compareVersions(version, latest) > 0) {
                latest = version;
            }
        }
        if (latest == null) {
            // Now use beta versions too
            for (String version : allVersions) {
                if (latest == null || compareVersions(version, latest) > 0) {
                    latest = version;
                }
            }
        }
        return latest;
    }

    public static int compareVersions(@NotNull String v1, @NotNull String v2) {
        StringTokenizer st1 = new StringTokenizer(v1, ".-_");
        StringTokenizer st2 = new StringTokenizer(v2, ".-_");
        while (st1.hasMoreTokens() && st2.hasMoreTokens()) {
            String t1 = st1.nextToken();
            String t2 = st2.nextToken();
            try {
                int cmp = Integer.parseInt(t1) - Integer.parseInt(t2);
                if (cmp != 0) {
                    return cmp;
                }
            } catch (NumberFormatException e) {
                // Non-numeric versions - use lexicographical compare
                int cmp = t1.compareTo(t2);
                if (cmp != 0) {
                    return cmp;
                }
            }
        }
        if (st1.hasMoreTokens()) {
            return 1;
        } else if (st2.hasMoreTokens()) {
            return -1;
        } else {
            return 0;
        }
    }
}


text:
package org.apache.hadoop.hdfs.server.namenode.metrics;

import java.io.IOException;
import java.util.Random;

import junit.framework.TestCase;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DFSTestUtil;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.HdfsConfiguration;

/**
 * Test case for FilesInGetListingOps metric in Namenode
 */
public class TestNNMetricFilesInGetListingOps extends TestCase {
  private static final Configuration CONF = new HdfsConfiguration();
  static {
    CONF.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, 100);
    CONF.setInt(DFSConfigKeys.DFS_BYTES_PER_CHECKSUM_KEY, 1);
    CONF.setLong(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1L);
    CONF.setInt(DFSConfigKeys.DFS_NAMENODE_REPLICATION_INTERVAL_KEY, 1);
  }

  private MiniDFSCluster cluster;
  private NameNodeMetrics nnMetrics;
  private DistributedFileSystem fs;
  private Random rand = new Random();

  @Override
  protected void setUp() throws Exception {
    cluster = new MiniDFSCluster.Builder(CONF).build();
    cluster.waitActive();
    cluster.getNameNode();
    nnMetrics = NameNode.getNameNodeMetrics();
    fs = (DistributedFileSystem) cluster.getFileSystem();
  }

  @Override
  protected void tearDown() throws Exception {
    cluster.shutdown();
  }

  /** create a file with a length of fileLen */
  private void createFile(String fileName, long fileLen, short replicas) throws IOException {
    Path filePath = new Path(fileName);
    DFSTestUtil.createFile(fs, filePath, fileLen, replicas, rand.nextLong());
  }

  public void testFilesInGetListingOps() throws Exception {
    createFile("/tmp1/t1", 3200, (short)3);
    createFile("/tmp1/t2", 3200, (short)3);
    createFile("/tmp2/t1", 3200, (short)3);
    createFile("/tmp2/t2", 3200, (short)3);
    cluster.getNameNode().getListing("/tmp1", HdfsFileStatus.EMPTY_NAME, false);
    assertEquals(2,nnMetrics.numFilesInGetListingOps.getCurrentIntervalValue());
    cluster.getNameNode().getListing("/tmp2", HdfsFileStatus.EMPTY_NAME, false) ;
    assertEquals(4,nnMetrics.numFilesInGetListingOps.getCurrentIntervalValue());
  }
}


text:
using System;
using System.Collections.Generic;
using System.Net;
using NathanAlden.Proxy.Http;

namespace NathanAlden.Proxy.HttpClient
{
    public interface IHttpClient
    {
        IPEndPoint Endpoint { get; }

        (GetRequestLineResult result, RequestLine requestLine) GetRequestLine();
        (GetResponseStatusLineResult result, ResponseStatusLine responseStatusLine) GetResponseStatusLine();
        (GetHeadersResult result, IEnumerable<Header> headers) GetHeaders();
        void WriteRequestLine(RequestLine requestLine);
        void WriteResponseStatusLine(ResponseStatusLine responseStatusLine);
        void WriteHeader(string name, string value);
        void WriteHeaders(IEnumerable<Header> headers);
        void WriteHeaders(params Header[] headers);
        void WriteNewLine();
        ArraySegment<byte> Read();
        void Write(ArraySegment<byte> arraySegment);
        void Flush();
        void Close();
    }
}


text:
jvm hausing for [bower](http://bower.io/) components.

## install

Bowhaus can be deployed as a standalone jar that can be built by executing

```bash
sbt assembly
```

In the repos base directory. This will generate a `bowhaus.jar` file in the `target` directory.

The server stores bower components in redis so you will need to provide the server with a few flags to inform it where to resolve the redis host,
among other things

```bash
java -jar bowhaus.jar -p <port> -r <redis_connection_string> -n <redis_key_prefix>
```

`-p` tells bowhaus which port to listen on as an http server ( defaults to `8080` )

`-r` tells bowhaus how to connect to redis ( defaults to the factory defaults for `redis-server` )

`-n` provides a namespace which is prefixed on all generated redis keys ( defaults to `testing`)

## usage

Bowhaus works a url shortener for bower components

### Register components

```bash
curl 'http://localhost:8080/packages' -d 'name=foo&url=git://bar.com/foo.git'
```

This will return a `201` ( created )  status. If a component with the same name exists a `409` ( conflict ) status is returned.

### Listing components

```bash
curl 'http://localhost:8080/packages'
```

This will list all of the registered components in json format

### Getting a single component

```bash
curl 'http://localhost:8080/packages/foo'
```

This will get the json representation of a named component

Doug Tangren (softprops) 2013


text:
package org.lambadaframework.runtime.router.types;

import org.lambadaframework.jaxrs.model.ResourceMethod;
import org.lambadaframework.runtime.models.Request;

public class ConsumedTypes implements RouterType {
    @Override
    public boolean isMatching(Request request, ResourceMethod resourceMethod) {
        return resourceMethod.getConsumedTypes().contains(request.getConsumedMediaType());
    }
}


text:
#ifndef TENSORFLOW_LITE_EXPERIMENTAL_MICROFRONTEND_LIB_NOISE_REDUCTION_UTIL_H_
#define TENSORFLOW_LITE_EXPERIMENTAL_MICROFRONTEND_LIB_NOISE_REDUCTION_UTIL_H_

#include "tensorflow/lite/experimental/microfrontend/lib/noise_reduction.h"

#ifdef __cplusplus
extern "C" {
#endif

struct NoiseReductionConfig {
  // scale the signal up by 2^(smoothing_bits) before reduction
  int smoothing_bits;
  // smoothing coefficient for even-numbered channels
  float even_smoothing;
  // smoothing coefficient for odd-numbered channels
  float odd_smoothing;
  // fraction of signal to preserve (1.0 disables this module)
  float min_signal_remaining;
};

// Populates the NoiseReductionConfig with "sane" default values.
void NoiseReductionFillConfigWithDefaults(struct NoiseReductionConfig* config);

// Allocates any buffers.
int NoiseReductionPopulateState(const struct NoiseReductionConfig* config,
                                struct NoiseReductionState* state,
                                int num_channels);

// Frees any allocated buffers.
void NoiseReductionFreeStateContents(struct NoiseReductionState* state);

#ifdef __cplusplus
}  // extern "C"
#endif

#endif  // TENSORFLOW_LITE_EXPERIMENTAL_MICROFRONTEND_LIB_NOISE_REDUCTION_UTIL_H_


text:
package org.jasig.maven.notice;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.jasig.maven.notice.lookup.LicenseLookup;

/**
 * Utility for loading the LicenseLookup JAXBContext as a singleton
 *
 * @author Eric Dalquist
 * @version $Revision$
 */
public final class LicenseLookupContext {
    private static final Package LICENSE_LOOKUP_PACKAGE = LicenseLookup.class.getPackage();
    private static JAXBContext JAXB_CONTEXT;

    private static synchronized JAXBContext getJaxbContext() {
        if (JAXB_CONTEXT == null) {
            try {
                JAXB_CONTEXT = JAXBContext.newInstance(LICENSE_LOOKUP_PACKAGE.getName());
            } catch (JAXBException e) {
                throw new IllegalStateException(
                        "Failed to load JAXBContext for package: " + LICENSE_LOOKUP_PACKAGE, e);
            }
        }

        return JAXB_CONTEXT;
    }

    public static Unmarshaller getUnmarshaller() {
        try {
            final JAXBContext jaxbContext = getJaxbContext();
            return jaxbContext.createUnmarshaller();
        } catch (JAXBException e) {
            throw new IllegalStateException(
                    "Failed to load JAXBContext for package: " + LICENSE_LOOKUP_PACKAGE, e);
        }
    }

    public static Marshaller getMarshaller() {
        try {
            final JAXBContext jaxbContext = getJaxbContext();
            final Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(
                    "jaxb.schemaLocation",
                    "https://source.jasig.org/schemas/maven-notice-plugin/license-lookup https://source.jasig.org/schemas/maven-notice-plugin/license-lookup/license-lookup-v1.0.xsd");
            marshaller.setProperty("jaxb.formatted.output", true);
            return marshaller;
        } catch (JAXBException e) {
            throw new IllegalStateException(
                    "Failed to load JAXBContext for package: " + LICENSE_LOOKUP_PACKAGE, e);
        }
    }

    private LicenseLookupContext() {}
}


text:
![No longer maintained](https://img.shields.io/badge/Maintenance-OFF-red.svg)
### [DEPRECATED] This repository is no longer maintained
> While this project is fully functional, the dependencies are no longer up to date. You are still welcome to explore, learn, and use the code provided here.
>
> Modus is dedicated to supporting the community with innovative ideas, best-practice patterns, and inspiring open source solutions. Check out the latest [Modus Labs](https://labs.moduscreate.com?utm_source=github&utm_medium=readme&utm_campaign=deprecated) projects.

[![Modus Labs](https://res.cloudinary.com/modus-labs/image/upload/h_80/v1531492623/labs/logo-black.png)](https://labs.moduscreate.com?utm_source=github&utm_medium=readme&utm_campaign=deprecated)

---
# React Native Device Module

Orientation methods & events plus device information.

Note: Currently for iOS only.

## Introduction

The purpose of this module is to provide some basic but important features for React Native, that are not provided by React Native proper, in a neat package.  The module is inspired the Device singleton in the browser/JavaScript.  It provides events for orientation change, suspend/resume, as well as methods for locking the display orientation (e.g. Portrait only) and for obtaining information about the device (screen width & height, curent orientation, device model, etc.).

Why implement suspend and resume when React Native already provides a similar facility?  If you use this module's facility, your code will be portable between Android and iOS.  React Native's implementaiton is via AppStateIOS, or specific to IOS.  See: https://facebook.github.io/react-native/docs/appstateios.html

## Installation

### iOS

In Xcode, right click on your project sources and select "Add files..."  In the open file dialog, select the MCDevice-ios folder from react-native-device.  Before clicking the add button, click the Options button and be sure "Create Groups" is selected.

## Use (JavaScript module)

```javascript
import Device from 'react-native-device';

// Device will fire a deviceready event after it is asynchronously initialized.
//
// Device will have the following properties (only after deviceready event is fired):
//
// height: 414
// identifier: "Simulator"  (might be iPhone 4, iPad Mini 2, etc.)
// localizedModel: "iPhone"
// model: "iPhone"
// name: "iPhone Simulator"
// orientation: "LandscapeLeft"
// orientationMask: "All"
// systemName: "iPhone OS"
// systemVersion: "9.2"
// userInterfaceIdiom: "Phone"
// width: 736

React.DeviceEventEmitter.addListener('deviceready', () => {
	React.DeviceEventEmitter.addListener('orientationchange', () => {
	    console.log('orientationchange ' + Device.orientation + ' ' + Device.width + ' x ' + Device.height);
	});
	React.DeviceEventEmitter.addListener('suspend', () => { console.log('suspend')});
	React.DeviceEventEmitter.addListener('resume', () => { console.log('resume')});
});

// When Device fires an event, the properties values are valid within the event handler and until the next event.

// to force the application to render to a specific orientation:

Device.lockOrientation(orientation)

// orientation may be one of the following strings:
// "Portrait" or "Landscape" or "Landscape" or "LandscapeLeft" or "LandscapeRight"
// or "PortraitUpsideDown"

// to allow the application to render any orientation:

Device.unlockOrientation()

```

## Use (Native module)

```javascript
import React from 'react-native'
let Device = React.NativeModules.MCDevice

// to listen to app suspend and resume events:
React.NativeAppEventEmitter.addListener('suspend', () => { console.log('suspend')});
React.NativeAppEventEmitter.addListener('resume', () => { console.log('resume')});

// to listen for orientation change events:
React.NativeAppEventEmitter.addListener('orientationchange', () => {
	console.log('Orientation Changed')
});

// (you might listen for orientationchange in your componentDidMount method)

// to force the application to render to a specific orientation:

Device.lockOrientation(orientation)

// orientation may be one of the following strings:
// "Portrait" or "Landscape" or "Landscape" or "LandscapeLeft" or "LandscapeRight"
// or "PortraitUpsideDown"

// to allow the application to render any orientation:

Device.unlockOrientation()

// Device provides a single asynchronous method to query for information about the device:

Device.info(callback: function(info: object));

// The returned info object contains information about the device.  An example info object:
//
// height: 414
// identifier: "Simulator"  (might be iPhone 4, iPad Mini 2, etc.)
// localizedModel: "iPhone"
// model: "iPhone"
// name: "iPhone Simulator"
// orientation: "LandscapeLeft"
// orientationMask: "All"
// systemName: "iPhone OS"
// systemVersion: "9.2"
// userInterfaceIdiom: "Phone"
// width: 736
```

See the demo application in the example directory.

## License

This module is free to use under the MIT license.  See LICENSE in this git repository for the actual license terms.

## Credits

* Mike Schwartz - @ModusSchwartz


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta name="robots" content="noindex, nofollow" />
  <meta http-equiv="x-ua-compatible" content="ie=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />

  <title>Get Your Market Property Value!</title>

  <link rel="stylesheet" href="css/bower.min.css" />
  <link rel="stylesheet" href="css/app.min.css" />

        <form id="form-search" method="get" onsubmit="return false;">

How Much Is Your
Property Worth?

Get Your FREE Market Analysis
Report Today!

            <input type="text" name="address" id="autocomplete" placeholder="Enter your address" onFocus="geolocate()" class="form-control input" />

        </form>

    <form id="form-value" method="get" onsubmit="return false;">

        Please help us with a few more details...

        We are almost ready to provide you with your
        FREE full market analysis of your property...

        <input type="text" name="name" placeholder="Name" class="form-control max-350" />

        <input type="text" name="email" placeholder="Email" class="form-control max-350" />

        <input type="text" name="phone" placeholder="Phone" class="form-control max-350" />

        Reason for Search

        <select name="reason" id="reason" class="form-control max-350">
          <option value=""></option>
          <option value="Just curious">Just curious</option>
          <option value="Looking to sell in 1 month">Looking to sell in 1 month</option>
          <option value="Looking to sell in 2 months">Looking to sell in 2 months</option>
          <option value="Looking to sell in 3 months">Looking to sell in 3 months</option>
          <option value="Looking to sell in 6-12 months">Looking to sell in 6-12 months</option>
        </select>

        <input type="hidden" name="address" id="address" />
        <button type="button" class="btn btn-primary btn-step2">

          View Market Value
        </button>

          Start search over »

    </form>

Congratulations!

Your FREE Home Value Report
was provided by...

        Adam Kimbrell

        Realtor - REK Realty

        (727) 344-9625

        AKSELLSFLRE@gmail.com


text:
using System;
using System.Linq;
using Newtonsoft.Json;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.IO.Serialization.Converters;
using osu.Game.Online.Rooms.RoomStatuses;
using osu.Game.Users;
using osu.Game.Utils;

namespace osu.Game.Online.Rooms
{
    public class Room : IDeepCloneable<Room>
    {
        [Cached]
        [JsonProperty("id")]
        public readonly Bindable<long?> RoomID = new Bindable<long?>();

        [Cached]
        [JsonProperty("name")]
        public readonly Bindable<string> Name = new Bindable<string>();

        [Cached]
        [JsonProperty("host")]
        public readonly Bindable<User> Host = new Bindable<User>();

        [Cached]
        [JsonProperty("playlist")]
        public readonly BindableList<PlaylistItem> Playlist = new BindableList<PlaylistItem>();

        [Cached]
        [JsonProperty("channel_id")]
        public readonly Bindable<int> ChannelId = new Bindable<int>();

        [Cached]
        [JsonIgnore]
        public readonly Bindable<RoomCategory> Category = new Bindable<RoomCategory>();

        // Todo: osu-framework bug (https://github.com/ppy/osu-framework/issues/4106)
        [JsonProperty("category")]
        [JsonConverter(typeof(SnakeCaseStringEnumConverter))]
        private RoomCategory category
        {
            get => Category.Value;
            set => Category.Value = value;
        }

        [Cached]
        [JsonIgnore]
        public readonly Bindable<int?> MaxAttempts = new Bindable<int?>();

        [Cached]
        [JsonIgnore]
        public readonly Bindable<RoomStatus> Status = new Bindable<RoomStatus>(new RoomStatusOpen());

        [Cached]
        [JsonIgnore]
        public readonly Bindable<RoomAvailability> Availability = new Bindable<RoomAvailability>();

        [Cached]
        [JsonIgnore]
        public readonly Bindable<MatchType> Type = new Bindable<MatchType>();

        // Todo: osu-framework bug (https://github.com/ppy/osu-framework/issues/4106)
        [JsonConverter(typeof(SnakeCaseStringEnumConverter))]
        [JsonProperty("type")]
        private MatchType type
        {
            get => Type.Value;
            set => Type.Value = value;
        }

        [Cached]
        [JsonIgnore]
        public readonly Bindable<int?> MaxParticipants = new Bindable<int?>();

        [Cached]
        [JsonProperty("current_user_score")]
        public readonly Bindable<PlaylistAggregateScore> UserScore = new Bindable<PlaylistAggregateScore>();

        [JsonProperty("has_password")]
        public readonly BindableBool HasPassword = new BindableBool();

        [Cached]
        [JsonProperty("recent_participants")]
        public readonly BindableList<User> RecentParticipants = new BindableList<User>();

        [Cached]
        [JsonProperty("participant_count")]
        public readonly Bindable<int> ParticipantCount = new Bindable<int>();

        #region Properties only used for room creation request

        [Cached(Name = nameof(Password))]
        [JsonProperty("password")]
        public readonly Bindable<string> Password = new Bindable<string>();

        [Cached]
        [JsonIgnore]
        public readonly Bindable<TimeSpan?> Duration = new Bindable<TimeSpan?>();

        [JsonProperty("duration")]
        private int? duration
        {
            get => (int?)Duration.Value?.TotalMinutes;
            set
            {
                if (value == null)
                    Duration.Value = null;
                else
                    Duration.Value = TimeSpan.FromMinutes(value.Value);
            }
        }

        #endregion

        // Only supports retrieval for now
        [Cached]
        [JsonProperty("ends_at")]
        public readonly Bindable<DateTimeOffset?> EndDate = new Bindable<DateTimeOffset?>();

        // Todo: Find a better way to do this (https://github.com/ppy/osu-framework/issues/1930)
        [JsonProperty("max_attempts", DefaultValueHandling = DefaultValueHandling.Ignore)]
        private int? maxAttempts
        {
            get => MaxAttempts.Value;
            set => MaxAttempts.Value = value;
        }

        public Room()
        {
            Password.BindValueChanged(p => HasPassword.Value = !string.IsNullOrEmpty(p.NewValue));
        }

        /// <summary>
        /// Create a copy of this room without online information.
        /// Should be used to create a local copy of a room for submitting in the future.
        /// </summary>
        public Room DeepClone()
        {
            var copy = new Room();

            copy.CopyFrom(this);
            copy.RoomID.Value = null;

            return copy;
        }

        public void CopyFrom(Room other)
        {
            RoomID.Value = other.RoomID.Value;
            Name.Value = other.Name.Value;

            if (other.Category.Value != RoomCategory.Spotlight)
                Category.Value = other.Category.Value;

            if (other.Host.Value != null && Host.Value?.Id != other.Host.Value.Id)
                Host.Value = other.Host.Value;

            ChannelId.Value = other.ChannelId.Value;
            Status.Value = other.Status.Value;
            Availability.Value = other.Availability.Value;
            HasPassword.Value = other.HasPassword.Value;
            Type.Value = other.Type.Value;
            MaxParticipants.Value = other.MaxParticipants.Value;
            ParticipantCount.Value = other.ParticipantCount.Value;
            EndDate.Value = other.EndDate.Value;
            UserScore.Value = other.UserScore.Value;

            if (EndDate.Value != null && DateTimeOffset.Now >= EndDate.Value)
                Status.Value = new RoomStatusEnded();

            other.RemoveExpiredPlaylistItems();

            if (!Playlist.SequenceEqual(other.Playlist))
            {
                Playlist.Clear();
                Playlist.AddRange(other.Playlist);
            }

            if (!RecentParticipants.SequenceEqual(other.RecentParticipants))
            {
                RecentParticipants.Clear();
                RecentParticipants.AddRange(other.RecentParticipants);
            }
        }

        public void RemoveExpiredPlaylistItems()
        {
            // Todo: This is not the best way/place to do this, but the intention is to display all playlist items when the room has ended,
            // and display only the non-expired playlist items while the room is still active. In order to achieve this, all expired items are removed from the source Room.
            // More refactoring is required before this can be done locally instead - DrawableRoomPlaylist is currently directly bound to the playlist to display items in the room.
            if (!(Status.Value is RoomStatusEnded))
                Playlist.RemoveAll(i => i.Expired);
        }

        public bool ShouldSerializeRoomID() => false;
        public bool ShouldSerializeHost() => false;
        public bool ShouldSerializeEndDate() => false;
    }
}


text:
terraform-provider-dns
======================

terraform-provider-dns is a [Terraform][terraform] [plugin][plugin] for querying DNS records.

[terraform]: https://www.terraform.io/
[plugin]: https://www.terraform.io/docs/plugins/

## Installing

### Automatic (macOS, Linux, FreeBSD, OpenBSD)

Use the [automatic setup script](./install.sh):

```sh
curl -fLsS https://github.com/union-wtf/terraform-provider-dns/raw/master/install.sh | bash
```

### Manual

Get the [latest release][releases] for your platform, then create or update your `~/.terraformrc` file:

```
providers {
  dns = "/usr/local/bin/terraform-provider-dns"
}
```

[releases]: https://github.com/union-wtf/terraform-provider-dns/releases

## Example

Here's how to configure an AWS [security group][sg] egress using a DNS hostname:

```tf
data "dns_addresses" "ubuntu_time" {
  hostname = "ntp.ubuntu.com"
}

resource "aws_security_group" "ntp" {
  egress {
    protocol    = "udp"
    from_port   = 123
    to_port     = 123
    cidr_blocks = ["${data.dns_addresses.ubuntu_time.ipv4_cidrs}"]
  }
}
```

[sg]: https://www.terraform.io/docs/providers/aws/r/security_group.html

## Data Sources

### `dns_addresses`

```tf
data "dns_addresses" "example" {
  hostname = "example.com"
}
```

#### Arguments

- `hostname` *(required)* – The hostname to lookup

#### Attributes

- `addresses` – List of resolved IPv4 and IPv6 addresses
- `cidrs` – List of IPv4 and IPv6 addresses formatted in CIDR notation with a full-length prefix (/32 for v4 and /128 for v8)
- `ipv4_addresses` – List of resolved IPv4 addresses
- `ipv6_addresses` – List of resolved IPv6 addresses
- `ipv4_cidrs` – List of resolved IPv4 addresses as /32's
- `ipv6_cidrs` – List of resolved IPv6 addresses as /128's

The `ipv4_cidrs` and `ipv6_cidrs` attributes are provided for contexts that require CIDR notation instead of a bare IP address.

### `dns_cname`

```tf
data "dns_addresses" "example" {
  hostname = "ipv6.google.com"
}
```

#### Arguments

- `hostname` *(required)* – The hostname to lookup

#### Attributes

- `cname` – The resolved CNAME