text:
enum OpCode
{
    // NOTE: the relative order of many of these instructions in their groups is significant
    // NOTE: no instruction should push more than one value onto the stack
    //       regardless of the number of pop's -- required for some optimization
    //       techniques (e.g. see CodeGen::undoSubexpr())

    // --- 1. MISC CONTROL
    opInv0,             //  -- help detect invalid code: don't execute 0
    opEnd,              // end execution and return
    opExit,             // throws eexit()

    // --- 2. CONST LOADERS
    // --- begin primary loaders (it's important that all this kind of loaders
    //     be grouped together or at least recognized by isPrimaryLoader())
    opLoadTypeRef,      // [Type*] +obj
    opLoadNull,         // +null
    opLoad0,            // +int
    opLoad1,            // +int
    opLoadByte,         // [int:u8] +int
    opLoadOrd,          // [int] +int
    opLoadStr,          // [str] +str
    opLoadEmptyVar,     // [variant::Type:u8] + var
    opLoadConstObj,     // [variant::Type:u8, object*] +var
    opLoadOuterObj,     // +stateobj
    opLoadDataSeg,      // +module-obj
    // opLoadInnerObj,      // equivalent to opLoadStkVar 'result'
    opLoadOuterFuncPtr, // [State*] +funcptr -- see also opMkFuncPtr
    opLoadInnerFuncPtr, // [State*] +funcptr
    opLoadStaticFuncPtr,// [State*] +funcptr
    opLoadFuncPtrErr,   // [State*] +funcptr
    opLoadCharFifo,     // [Fifo*] +fifo
    opLoadVarFifo,      // [Fifo*] +fifo

    // --- 3. DESIGNATOR LOADERS
    // --- begin grounded loaders
    opLoadInnerVar,     // [inner.idx:u8] +var
    opLoadOuterVar,     // [outer.idx:u8] +var
    opLoadStkVar,       // [stk.idx:u8] +var
    opLoadArgVar,       // [arg.idx:u8] +var
    opLoadPtrVar,       // [arg.idx:u8] +var
    opLoadResultVar,    // +var
    opLoadVarErr,       // placeholder for var loaders to generate an error
    // --- end primary loaders
    opLoadMember,       // [stateobj.idx:u8] -stateobj +var
    opDeref,            // -ref +var
    // --- end grounded loaders

    opLeaInnerVar,      // [inner.idx:u8] +obj(0) +ptr
    opLeaOuterVar,      // [outer.idx:u8] +obj(0) +ptr
    opLeaStkVar,        // [stk.idx:u8] +obj(0) +ptr
    opLeaArgVar,        // [arg.idx:u8] +obj(0) +ptr
    opLeaPtrVar,        // [arg.idx:u8] +obj +ptr
    opLeaResultVar,     // +obj(0) +ptr
    opLeaMember,        // [stateobj.idx:u8] -stateobj +stateobj +ptr
    opLeaRef,           // -ref +ref +ptr

    // --- 4. STORERS
    opInitInnerVar,     // [inner.idx:u8] -var
    // opInitStkVar,       // [stk.idx:u8] -var
    // --- begin grounded storers
    opStoreInnerVar,    // [inner.idx:u8] -var
    opStoreOuterVar,    // [outer.idx:u8] -var
    opStoreStkVar,      // [stk.idx:u8] -var
    opStoreArgVar,      // [arg.idx:u8] -var
    opStorePtrVar,      // [arg.idx:u8] -var
    opStoreResultVar,   // -var
    opStoreMember,      // [stateobj.idx:u8] -var -stateobj
    opStoreRef,         // -var -ref
    // --- end grounded storers
    opIncStkVar,        // [stk.idx:u8] -- for loop helper

    // --- 5. DESIGNATOR OPS, MISC
    opMkRange,          // -int -int +range -- currently used only in const expressions
    opMkRef,            // -var +ref
    opMkFuncPtr,        // [State*] -obj +funcptr  -- args for opMk*FuncPtr should match respective caller ops
    opMkFarFuncPtr,     // [State*, datasegidx:u8] -obj +funcptr
    opNonEmpty,         // -var +bool
    opPop,              // -var
    opPopPod,           // -int
    opCast,             // [Type*] -var +var
    opIsType,           // [Type*] -var +bool
    opToStr,            // [Type*] -var +str

    // --- 6. STRINGS, VECTORS
    opChrToStr,         // -char +str
    opChrCat,           // -char -str +str
    opStrCat,           // -str -str +str
    opVarToVec,         // -var +vec
    opVarCat,           // -var -vec +vec
    opVecCat,           // -vec -vec +vec
    opStrLen,           // -str +int
    opVecLen,           // -str +int
    opStrHi,            // -str +int
    opVecHi,            // -str +int
    opStrElem,          // -int -str +char
    opVecElem,          // -int -vec +var
    opSubstr,           // -{int,void} -int -str +str
    opSubvec,           // -{int,void} -int -vec +vec
    opStoreStrElem,     // -char -int -ptr -obj
    opStoreVecElem,     // -var -int -ptr -obj
    opDelStrElem,       // -int -ptr -obj
    opDelVecElem,       // -int -ptr -obj
    opDelSubstr,        // -{int,void} -int -ptr -obj
    opDelSubvec,        // -{int,void} -int -ptr -obj
    opStrIns,           // -char -int -ptr -obj
    opVecIns,           // -var -int -ptr -obj
    opSubstrReplace,    // -str -{int,void} -int -ptr -obj
    opSubvecReplace,    // -vec -{int,void} -int -ptr -obj
    // In-place vector concat
    opChrCatAssign,     // -char -ptr -obj
    opStrCatAssign,     // -str -ptr -obj
    opVarCatAssign,     // -var -ptr -obj
    opVecCatAssign,     // -vec -ptr -obj

    // --- 7. SETS
    opElemToSet,        // -var +set
    opSetAddElem,       // -var -set + set
    opElemToByteSet,    // -int +set
    opRngToByteSet,     // -int -int +set
    opByteSetAddElem,   // -int -set +set
    opByteSetAddRng,    // -int -int -set +set
    opInSet,            // -set -var +bool
    opInByteSet,        // -set -int +bool
    opInBounds,         // [Ordinal*] -int +bool
    opInRange,          // -range -int +bool
    opRangeLo,          // -range +int
    opRangeHi,          // -range +int
    opInRange2,         // -int -int -int +bool
    opSetElem,          // -var -set +void
    opByteSetElem,      // -int -set +void
    opDelSetElem,       // -var -ptr -obj
    opDelByteSetElem,   // -int -ptr -obj
    opSetLen,           // -set +int
    opSetKey,           // -int -set +var

    // --- 8. DICTIONARIES
    opPairToDict,       // -var -var +dict
    opDictAddPair,      // -var -var -dict +dict
    opPairToByteDict,   // -var -int +vec
    opByteDictAddPair,  // -var -int -vec +vec
    opDictElem,         // -var -dict +var
    opByteDictElem,     // -int -dict +var
    opInDict,           // -var -dict +bool
    opInByteDict,       // -int -dict +bool
    opStoreDictElem,    // -var -var -ptr -obj
    opStoreByteDictElem,// -var -int -ptr -obj
    opDelDictElem,      // -var -ptr -obj
    opDelByteDictElem,  // -int -ptr -obj
    opDictLen,          // -dict +int
    opDictElemByIdx,    // -int -dict +var
    opDictKeyByIdx,     // -int -dict +var

    // --- 9. FIFOS
    // opLoadCharFifo and opLoadVarFifo are primary loaders, defined in section [2].
    opElemToFifo,       // [Fifo*] -var +fifo
    opFifoEnqChar,      // -char -fifo +fifo
    opFifoEnqVar,       // -var -fifo +fifo
    opFifoEnqChars,     // -str -fifo +fifo
    opFifoEnqVars,      // -vec -fifo +fifo
    opFifoDeqChar,      // -fifo +char
    opFifoDeqVar,       // -fifo +char
    opFifoCharToken,    // -charset -fifo +str

    // --- 10. ARITHMETIC
    opAdd,              // -int -int +int
    opSub,              // -int -int +int
    opMul,              // -int -int +int
    opDiv,              // -int -int +int
    opMod,              // -int -int +int
    opBitAnd,           // -int -int +int
    opBitOr,            // -int -int +int
    opBitXor,           // -int -int +int
    opBitShl,           // -int -int +int
    opBitShr,           // -int -int +int
    // Arithmetic unary
    opNeg,              // -int +int
    opBitNot,           // -int +int
    opNot,              // -bool +bool
    // Arithmetic in-place, in sync with tokAddAssign etc
    opAddAssign,        // -int -ptr -obj
    opSubAssign,        // -int -ptr -obj
    opMulAssign,        // -int -ptr -obj
    opDivAssign,        // -int -ptr -obj
    opModAssign,        // -int -ptr -obj

    // --- 11. BOOLEAN
    opCmpOrd,           // -int -int +{-1,0,1}
    opCmpStr,           // -str -str +{-1,0,1}
    opCmpVar,           // -var -var +{0,1}
    // see isCmpOp()
    opEqual,            // -int +bool
    opNotEq,            // -int +bool
    opLessThan,         // -int +bool
    opLessEq,           // -int +bool
    opGreaterThan,      // -int +bool
    opGreaterEq,        // -int +bool
    // case label helpers
    opCaseOrd,          // -int -int +int +bool
    opCaseRange,        // -int -int -int +int +bool
    opCaseStr,          // -str -str +str +bool
    opCaseVar,          // -var -var +var +bool
    // for loop helpers
    opStkVarGt,         // [stk.idx:u8] -int +bool
    opStkVarGe,         // [stk.idx:u8] -int +bool

    // --- 12. JUMPS, CALLS
    // Jumps; [dst] is a relative 16-bit offset
    opJump,             // [dst:s16]
    opJumpFalse,        // [dst:s16] -bool
    opJumpTrue,         // [dst:s16] -bool
    // Short bool evaluation: pop if jump, leave it otherwise
    opJumpAnd,          // [dst:s16] (-)bool
    opJumpOr,           // [dst:s16] (-)bool

    // don't forget isCaller()
    opChildCall,        // [State*] -var -var ... {+var}
    opSiblingCall,      // [State*] -var -var ... {+var}
    opStaticCall,       // [State*] -var -var ... {+var}
    opMethodCall,       // [State*] -var -var -obj ... {+var}
    opFarMethodCall,    // [State*, datasegidx:u8] -var -var -obj ... {+var}
    opCall,             // [argcount:u8] -var -var -funcptr {+var}

    // --- 13. DEBUGGING, DIAGNOSTICS
    opLineNum,          // [linenum:int]
    opAssert,           // [linenum:int, cond:str] -bool
    opDump,             // [expr:str, type:Type*] -var

    opInv,
    opMaxCode = opInv,
};

inline bool isPrimaryLoader(OpCode op)
    { return (op >= opLoadTypeRef && op <= opLoadVarErr); }

inline bool isGroundedLoader(OpCode op)
    { return op >= opLoadInnerVar && op <= opDeref; }

inline bool isCmpOp(OpCode op)
    { return op >= opEqual && op <= opGreaterEq; }

inline bool isJump(OpCode op)
    { return op >= opJump && op <= opJumpOr; }

inline bool isBoolJump(OpCode op)
    { return op >= opJumpFalse && op <= opJumpOr; }

inline bool isCaller(OpCode op)
    { return op >= opChildCall && op <= opCall; }

inline bool isDiscardable(OpCode op)
    { return isCaller(op) || op == opFifoEnqChar || op == opFifoEnqVar; }

inline bool hasTypeArg(OpCode op);

// --- OpCode Info

enum OpArgType
    { argNone,
      argType, argState, argFarState, argFifo, // order is important, see hasTypeArg()
      argUInt8, argInt, argStr, argVarType8, argVarTypeObj,
      argInnerIdx, argOuterIdx, argStkIdx, argArgIdx, argStateIdx,
      argJump16, argLineNum, argAssert, argDump,
      argMax };

extern umemint opArgSizes[argMax];

struct OpInfo
{
    const char* name;
    OpCode op;
    OpArgType arg;
};

extern OpInfo opTable[];

// --- Code Segment -------------------------------------------------------- //

#define DEFAULT_STACK_SIZE 8192

class CodeSeg: public object
{
    typedef rtobject parent;

    str code;

    template<class T>
        T& atw(memint i)                { return *(T*)code.atw(i); }
    template<class T>
        T at(memint i) const            { return *(T*)code.data(i); }

public:
    State* const state;

#ifdef DEBUG
    bool closed;
#endif

    // Code gen helpers
    template <class T>
        void append(const T& t)         { code.append((const char*)&t, sizeof(T)); }
    void append(const str& s)           { code.append(s); }
    void erase(memint from)             { code.resize(from); }
    void eraseOp(memint offs);
    str cutOp(memint offs);
    void replaceOpAt(memint i, OpCode op);
    OpCode opAt(memint i) const         { return OpCode(at<uchar>(i)); }
    memint opLenAt(memint offs) const;

    jumpoffs& jumpOffsAt(memint i)
        { assert(isJump(opAt(i))); return atw<jumpoffs>(i + 1); }

    Type* typeArgAt(memint i) const;
    State* stateArgAt(memint i) const    { return cast<State*>(typeArgAt(i)); }

    static inline memint opLen(OpCode op)
        { assert(op < opMaxCode); return memint(opArgSizes[opTable[op].arg]) + 1; }

    static inline OpArgType opArgType(OpCode op)
        { assert(op < opMaxCode); return opTable[op].arg; }

    CodeSeg(State*) throw();
    ~CodeSeg() throw();

    State* getStateType() const         { return state; }
    memint size() const                 { return code.size(); }
    bool empty() const                  { return code.empty(); }
    void close();

    const uchar* getCode() const        { assert(closed); return (uchar*)code.data(); }
    void dump(fifo& stm) const;  // in vminfo.cpp
};

template<> inline void CodeSeg::append<OpCode>(const OpCode& op)
    { append<uchar>(uchar(op)); }

// Compiler traps
template<> OpCode CodeSeg::at<OpCode>(memint i) const;
template<> OpCode& CodeSeg::atw<OpCode>(memint i);

inline CodeSeg* State::getCodeSeg() const { return cast<CodeSeg*>(codeseg.get()); }
inline const uchar* State::getCodeStart() const { return getCodeSeg()->getCode(); }

// --- Code Generator ------------------------------------------------------ //

class CodeGen: noncopyable
{
protected:
    Module* const module;
    State* const codeOwner;
    State* const typeReg;  // for calling registerType()
    CodeSeg& codeseg;

    // TODO: keep at least ordinal consts so that some things can be evaluated
    // at compile time or optimized
    struct SimStackItem
    {
        Type* type;
        memint loaderOffs;
        SimStackItem(Type* t, memint o)
            : type(t), loaderOffs(o)  { }
    };

    podvec<SimStackItem> simStack;  // exec simulation stack
    memint locals;                  // number of local vars allocated

    template <class T>
        void add(const T& t)                        { codeseg.append<T>(t); }
    void addOp(OpCode op)                           { codeseg.append<uchar>(op); }
    void addOp(Type*, OpCode op);
    void addOp(Type*, const str& op);
    template <class T>
        void addOp(OpCode op, const T& a)           { addOp(op); add<T>(a); }
    template <class T>
        void addOp(Type* t, OpCode op, const T& a)  { addOp(t, op); add<T>(a); }
    void stkPush(Type*, memint);
    Type* stkPop();
    void stkReplaceType(Type* t);  // only if the opcode is not changed
    Type* stkType()
        { return simStack.back().type; }
    Type* stkType(memint i)
        { return simStack.back(i).type; }
    memint stkLoaderOffs()
        { return simStack.back().loaderOffs; }
    memint stkPrevLoaderOffs()
        { return prevLoaderOffs; }
    memint stkPrimaryLoaderOffs()
        { return primaryLoaders.back(); }
    static void error(const char*);
    static void error(const str&);

    void _loadVar(Variable*, OpCode);

    memint prevLoaderOffs;
    podvec<memint> primaryLoaders;

public:
    CodeGen(CodeSeg&, Module* m, State* treg, bool compileTime) throw();
    ~CodeGen() throw();

    memint getStackLevel()      { return simStack.size(); }
    void endStatement()         { primaryLoaders.clear(); }
    bool isCompileTime()        { return codeOwner == NULL; }
    memint getLocals()          { return locals; }
    State* getCodeOwner()       { return codeOwner; }
    Type* getTopType()          { return stkType(); }
    Type* getTopType(memint i)  { return stkType(i); }
    void justForget()           { stkPop(); } // for branching in the if() function
    memint getCurrentOffs()     { return codeseg.size(); }
    void undoSubexpr();
    Type* undoTypeRef();
    State* undoStateRef();
    Ordinal* undoOrdTypeRef();
    bool canDiscardValue();
    void deinitLocalVar(Variable*);
    void deinitFrame(memint baseLevel); // doesn't change the sim stack
    void popValue();
    bool tryImplicitCast(Type*);
    void implicitCast(Type*, const char* errmsg = NULL);
    void explicitCast(Type*);
    void isType(Type*);
    void mkRange();
    void toStr();

    bool deref();
    void mkref();
    void nonEmpty();
    void loadTypeRefConst(Type*);
    void loadConst(Type* type, const variant&);
    void loadTypeRef(Type*);
    void loadDefinition(Definition*);
    void loadEmptyConst(Type* type);
    void loadSymbol(Symbol*);
    void loadStkVar(StkVar* var)
        { _loadVar(var, opLoadStkVar); }
    void loadArgVar(ArgVar* var)
        { _loadVar(var, opLoadArgVar); }
    void loadPtrVar(PtrVar* var)
        { _loadVar(var, opLoadPtrVar); }
    void loadResultVar(ResultVar* var);
    void loadInnerVar(InnerVar*);
    void loadVariable(Variable*);
    void loadMember(State*, Symbol*);
    void loadMember(State*, State*);
    void loadMember(State*, Variable*);
    void loadThis();
    void loadDataSeg();
    void storeResultVar()
        { stkPop(); addOp(opStoreResultVar); }

    void initStkVar(StkVar*);
    void initInnerVar(InnerVar*);
    void incStkVar(StkVar*);

    Container* elemToVec(Container*);
    void elemCat();
    void cat();
    void loadContainerElem();
    void loadKeyByIndex();
    void loadDictElemByIndex();
    void loadSubvec();
    void length();
    void lo();
    void hi();
    Container* elemToSet();
    Container* rangeToSet();
    void setAddElem();
    void checkRangeLeft();
    void setAddRange();
    Container* pairToDict();
    void checkDictKey();
    void dictAddPair();
    void inCont();
    void inBounds();
    void inRange();
    void inRange2(bool isCaseLabel = false);
    void loadFifo(Fifo*);
    Fifo* elemToFifo();
    void fifoEnq();
    void fifoPush();
    void fifoDeq();
    void fifoToken();

    void arithmBinary(OpCode op);
    void arithmUnary(OpCode op);
    void cmp(OpCode);
    void caseCmp();
    void caseInRange()
        { inRange2(true); }
    void _not(); // 'not' is something reserved, probably only with Apple's GCC

    void stkVarCmp(StkVar*, OpCode);
    void stkVarCmpLength(StkVar* var, StkVar* vec);

    void boolJump(memint target, OpCode op);
    memint boolJumpForward(OpCode op);
    memint jumpForward(OpCode = opJump);
    void resolveJump(memint target);
    void _jump(memint target, OpCode op = opJump);
    void jump(memint target)
        { _jump(target, opJump); }
    void linenum(integer);
    void assertion(integer linenum, const str& cond);
    void dumpVar(const str& expr);
    void programExit();

    void toLea();
    void prevToLea();
    str lvalue();
    void assign(const str& storerCode);
    str arithmLvalue(Token);
    void catLvalue();
    void catAssign();
    str insLvalue();
    void insAssign(const str& storerCode);
    void deleteContainerElem();

    void prolog()  { }
    void epilog()  { end(); }
    void _popArgs(FuncPtr*);
    void call(FuncPtr*);
    void staticCall(State*);

    void end();
    Type* runConstExpr(rtstack& constStack, variant& result); // defined in vm.cpp
};

struct evoidfunc: public exception
{
    evoidfunc() throw();
    ~evoidfunc() throw();
    const char* what() throw();
};

// --- Execution context --------------------------------------------------- //

struct CompilerOptions
{
    bool enableDump;
    bool enableAssert;
    bool lineNumbers;
    bool vmListing;
    bool compileOnly;
    memint stackSize;
    strvec modulePath;

    CompilerOptions() throw();
    void setDebugOpts(bool);
};

class Context;

class ModuleInstance: public symbol
{
public:
    objptr<Module> module;
    objptr<stateobj> obj;
    ModuleInstance(Module* m) throw();
    ~ModuleInstance() throw();
    void run(Context*, rtstack&);
    void finalize();
};

class Context
{
protected:
    symtbl<ModuleInstance> instTable;
    objvec<ModuleInstance> instances;
    ModuleInstance* queenBeeInst;

    ModuleInstance* addModule(Module*);
    str lookupSource(const str& modName);
    void instantiateModules();
    void clear();
    void dump(const str& listingPath);

public:
    CompilerOptions options;

    Context();
    ~Context();

    Module* getModule(const str& name);     // for use by the compiler, "uses" clause
    stateobj* getModuleObject(Module*);     // for initializing module vars in ModuleInstance::run()
    Module* loadModule(const str& filePath);
    variant execute();                      // after compilation only (loadModule())
};

// The Virtual Machine. This routine is used for both evaluating const
// expressions at compile time and, obviously, running runtime code. It is
// reenterant and can be launched concurrently in one process as long as
// the arguments are thread safe. It doesn't use any global/static data.
// Besides, code segments never have any relocatble data elements, so that any
// module can be reused in the multithreaded server environment too.

void runRabbitRun(variant* result, stateobj* dataseg, stateobj* outerobj,
        variant* basep, CodeSeg* codeseg);

struct eexit: public exception
{
    variant result;
    eexit(const variant&) throw();
    ~eexit() throw();
    const char* what() throw();
};

void initVm();
void doneVm();

#endif // __VM_H


text:
require_relative 'test_helper'
require 'cdo/env'

class ENVTest < Minitest::Test

  def test_with_sensitive_values_redacted
    ENV['SAFE'] = 'safe value'
    orig_key = ENV['AWS_SECRET_KEY']
    ENV['AWS_SECRET_KEY'] = 'this should be obfuscated'

    redacted = ENV.with_sensitive_values_redacted

    assert redacted.has_key? 'SAFE'
    assert_equal 'safe value', redacted['SAFE']

    assert redacted.has_key? 'AWS_SECRET_KEY'
    assert_equal '(HIDDEN)', redacted['AWS_SECRET_KEY']

    ENV['AWS_SECRET_KEY'] = orig_key
  end
end

redpajama_set_name: RedPajamaGithub


text:
require 'minitest/autorun'
require 'minitest/capistrano'
require 'capistrano/fanfare'
require 'capistrano/fanfare/bundler'

describe Capistrano::Fanfare::Bundler do
  before do
    @config = Capistrano::Configuration.new
    Capistrano::Fanfare::Bundler.load_into(@config)
    @config.extend(MiniTest::Capistrano::ConfigurationExtension)
    @orig_config = Capistrano::Configuration.instance
    Capistrano::Configuration.instance = @config

    @config.set :current_release, "/srv/gemmy/releases/thisone"
  end

  after do
    Capistrano::Configuration.instance = @orig_config
  end

  describe "for variables" do
    it "sets :bundle_cmd to 'bundle'" do
      @config.fetch(:bundle_cmd).must_equal "bundle"
    end

    it "sets :bundle_shebang to 'ruby-local-exec'" do
      @config.fetch(:bundle_shebang).must_equal "ruby-local-exec"
    end

    it "add :current_path/bin to the default_environment PATH" do
      @config.set :current_path, "/tmp/app/current"

      @config.fetch(:default_environment)['PATH'].must_equal "/tmp/app/current/bin:$PATH"
    end

    it "sets :bundle_binstub_template to the binstub script" do
      @config.set :bundle_shebang, "jruby"

      @config.fetch(:bundle_binstub_template).must_equal <<-BINSTUB
#!/usr/bin/env jruby
#
# This file was generated by capistrano.
#

require 'pathname'
ENV['BUNDLE_GEMFILE'] ||= File.expand_path("../../Gemfile",
  Pathname.new(__FILE__).realpath)

require 'rubygems'

load Gem.bin_path('bundler', 'bundle')
      BINSTUB
    end

    describe ":bundle_flags" do
      after do
        ENV.delete('QUIET')
      end

      it "contains --deployment" do
        @config.fetch(:bundle_flags).must_match /--deployment/
      end

      it "contains --binstubs" do
        @config.fetch(:bundle_flags).must_match /--binstubs/
      end

      it "contains --shebang <shebang_bin>" do
        @config.set :bundle_shebang, "bangbang"

        @config.fetch(:bundle_flags).must_match /--shebang bangbang/
      end

      it "doesn't contain --quiet by default" do
        @config.fetch(:bundle_flags).wont_match /--quiet/
      end

      it "contains --quiet if ENV['QUIET'] is set" do
        ENV['QUIET'] = "yes"

        @config.fetch(:bundle_flags).must_match /--quiet/
      end
    end

    describe ":bundle_without" do
      it "contains :development and :test groups" do
        @config.fetch(:bundle_without).must_include :development
        @config.fetch(:bundle_without).must_include :test
      end

      it "contains all other values from :os_types if the :os_type variable exists" do
        @config.set :os_types, [:fizz, :buzz, :rocketships]
        @config.set :os_type, :rocketshipos

        @config.fetch(:bundle_without).must_include :fizz
        @config.fetch(:bundle_without).must_include :buzz
        @config.fetch(:bundle_without).must_include :development
        @config.fetch(:bundle_without).must_include :test
      end
    end
  end

  describe "for namespace :bundle" do
    it "creates a bundle:install task" do
      @config.must_have_task "bundle:install"
    end

    # trigger was changed from :after to :before in Bundler v1.1.4, so we
    # should be okay with both.
    # source: https://github.com/carlhuda/bundler/commit/5d518bec98d44e474eca37a0fe5fe9b79b5afb19
    it "calls bundle:install task after (or before) deploy:finalize_update" do
      results = []
      results.concat(@config.find_callback(:before, "deploy:finalize_update"))
      results.concat(@config.find_callback(:after, "deploy:finalize_update"))

      results.map { |result| result.source }.must_include "bundle:install"
    end

    describe "task :create_binstub_script" do
      it "creates bin/bundle binstub script" do
        @config.set :shared_path, "/tmp/app/shared"
        @config.set :bundle_binstub_template, "thescript"
        @config.find_and_execute_task("bundle:create_binstub_script")

        @config.must_have_run "mkdir -p /tmp/app/shared/bin"
        @config.must_have_put "/tmp/app/shared/bin/bundle", "thescript"
      end

      it "gets called after deploy:setup task" do
        @config.must_have_callback_after "deploy:setup", "bundle:create_binstub_script"
      end
    end

    describe "task :cp_bundle_binstub" do
      it "copies bin/bundle into current_path" do
        @config.set :shared_path, "/tmp/app/shared"
        @config.set :current_path, "/tmp/app/current"
        @config.find_and_execute_task("bundle:cp_bundle_binstub")

        @config.must_have_run [
          "mkdir -p /tmp/app/current/bin",
          "cp /tmp/app/shared/bin/bundle /tmp/app/current/bin/bundle",
          "chmod 0755 /tmp/app/current/bin/bundle"
        ].join(" && ")
      end

      it "gets called after deploy:update_code task" do
        @config.must_have_callback_before "deploy:finalize_update", "bundle:cp_bundle_binstub"
      end
    end
  end
end


text:
layout: event
category: past
title: DVVF Jugendmeisterschaft in Frankfurt 04/2019
subTitle:
lang: de
ref: 2019-04-dvvf-jugendmeisterschaft
permalink: event-2019-04-dvvf-jugendmeisterschaft
description: |

comments: true
image_count: 0
event_path: 2019-04-dvvf-jugendmeisterschaft

credits:
---


text:
var Auth = require('./auth')
  , OARequest = require('./oarequest')

//  Endpoints
var REST_ROOT     = 'https://api.twitter.com/1.1/'
  , PUB_STREAM    = 'https://stream.twitter.com/1.1/'
  , USER_STREAM   = 'https://userstream.twitter.com/1.1/'
  , SITE_STREAM   = 'https://sitestream.twitter.com/1.1/'
  , MEDIA_UPLOAD  = 'https://upload.twitter.com/1.1/'
  , OA_REQ        = 'https://api.twitter.com/oauth/request_token'
  , OA_ACCESS     = 'https://api.twitter.com/oauth/access_token'

//
//  Twitter
//
var Twitter = function (config) {
  var credentials = {
      oauth_request_url   : OA_REQ
    , oauth_access_url    : OA_ACCESS
    , consumer_key        : config.consumer_key
    , consumer_secret     : config.consumer_secret
    , access_token        : config.access_token
    , access_token_secret : config.access_token_secret
  }

  this.config = config;
  this.config.oauth_request_url = OA_REQ;
  this.config.oauth_access_url = OA_ACCESS;

  //authenticate our oauth client
  this.auth = new Auth(credentials)
}

Twitter.prototype = {
  get: function (path, params, callback) {
    return this.request('GET', path, params, callback)
  },
  post: function (path, params, callback) {
    return this.request('POST', path, params, callback)
  },
  request: function (method, path, params, callback) {
    // if no `params` is specified but a callback is, use default params
    if (typeof params === 'function') {
      callback = params
      params = {}
    }

    // clone `params` object so we can modify it without modifying the user's reference
    var paramsClone = JSON.parse(JSON.stringify(params))

    // special case for media/upload. This lives in a different subdomain.
    if (path === 'media/upload') {
      // build the full url
      var finalPath = MEDIA_UPLOAD + path + '.json'
      console.log("final path " + finalPath);
      return new OARequest(
          this.auth
        , method
        , finalPath
        , paramsClone
      ).end(callback)
    }

    // regex to extract :params from `path`
    var rgxParam = /\/:(\w+)/g
    var missingParamErr = null

    // extract params like from paths like statuses/retweet/:id
    // and replace them with user-supplied params
    path = path.replace(rgxParam, function (hit) {
      var paramName = hit.slice(2)
      var userVal = paramsClone[paramName]

      if (!userVal) {
        missingParamErr = new Error('Twit: Params object is missing a required parameter for this request: `'+paramName+'`')
        return
      }

      // clone this param value, and delete from `paramsClone` so we don't pass it in the querystring or body
      var retVal = '/' + userVal
      delete paramsClone[paramName]

      return retVal
    })
    // build the full url
    var finalPath = REST_ROOT + path + '.json'

    // if we got a missing param, return the error to the user
    if (missingParamErr) {
      return callback(missingParamErr)
    }

    // convert any arrays in `paramsClone` to comma-seperated strings
    var finalParams = this.normalizeParams(paramsClone)

    return new OARequest(
        this.auth
      , method
      , finalPath
      , finalParams
    ).end(callback)
  },
  stream: function (path, params) {
    var stream_endpoint_map = {
      user: USER_STREAM,
      site: SITE_STREAM
    }

    var ROOT = stream_endpoint_map[path] || PUB_STREAM

    var streamPath = ROOT + path + '.json'
    var finalParams = this.normalizeParams(params)

    return new OARequest(this.auth, 'POST', streamPath, finalParams).persist()
  },
  normalizeParams: function (params) {
    var normalized = params
    if (params && typeof params === 'object') {
      Object.keys(params).forEach(function (key) {
        var value = params[key]
        // replace any arrays in `params` with comma-separated string
        if (Array.isArray(value))
          normalized[key] = value.join(',')
      })
    } else if (!params) {
      normalized = {}
    }
    return normalized
  },
  setAuth: function (auth) {
    var self = this
    var authKeys = [ 'consumer_key', 'consumer_secret', 'access_token', 'access_token_secret' ];

    // update config
    authKeys.forEach(function (authKey) {
      if (auth[authKey]) {
        self.config[authKey] = auth[authKey]
      }
    })

    // create a new auth object
    this.auth = new Auth(this.config)
  },
  getAuth: function () {
    return this.config
  }
}

module.exports = Twitter


text:
const jade = require('jade');
const { markdown } = require('markdown');
const fs = require('fs');
const vm = require('vm');
const { exec } = require('child_process');
const PDFDocument = require('../');

process.chdir(__dirname);

if (!fs.existsSync('img')) {
  fs.mkdirSync('img');
}

const files = [
  '../README.md',
  'getting_started.md',
  'vector.md',
  'text.md',
  'images.md',
  'annotations.md'
];

// shared lorem ipsum text so we don't need to copy it into every example
const lorem =
  'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in suscipit purus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus nec hendrerit felis. Morbi aliquam facilisis risus eu lacinia. Sed eu leo in turpis fringilla hendrerit. Ut nec accumsan nisl. Suspendisse rhoncus nisl posuere tortor tempus et dapibus elit porta. Cras leo neque, elementum a rhoncus ut, vestibulum non nibh. Phasellus pretium justo turpis. Etiam vulputate, odio vitae tincidunt ultricies, eros odio dapibus nisi, ut tincidunt lacus arcu eu elit. Aenean velit erat, vehicula eget lacinia ut, dignissim non tellus. Aliquam nec lacus mi, sed vestibulum nunc. Suspendisse potenti. Curabitur vitae sem turpis. Vestibulum sed neque eget dolor dapibus porttitor at sit amet sem. Fusce a turpis lorem. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;';

const extractHeaders = function(tree) {
  const headers = [];

  for (let index = 0; index < tree.length; index++) {
    const node = tree[index];
    if (node[0] === 'header' && (headers.length === 0 || node[1].level > 1)) {
      if (node[1].level > 2) {
        node[1].level = 2;
      }
      const hash = node[2].toLowerCase().replace(/\s+/g, '_');
      node[1].id = hash;
      headers.push({
        hash,
        title: node[2]
      });
    }
  }

  return headers;
};

let imageIndex = 0;
const generateImages = function(tree) {
  // find code blocks
  const codeBlocks = [];
  for (var node of tree) {
    if (node[0] === 'code_block') {
      codeBlocks.push(node[1]);
    }
  }

  for (node of tree) {
    if (node[0] === 'para' && Array.isArray(node[1]) && node[1][0] === 'img') {
      // compile the code
      const attrs = node[1][1];
      let code = codeBlocks[attrs.alt];
      delete attrs.height; // used for pdf generation

      // create a PDF and run the example
      const doc = new PDFDocument();
      const f = `img/${imageIndex++}`;
      var file = fs.createWriteStream(`${f}.pdf`);
      doc.pipe(file);

      doc.translate(doc.x, doc.y);
      doc.scale(0.8);
      doc.x = doc.y = 0;

      vm.runInNewContext(code, {
        doc,
        lorem
      });

      delete attrs.title;
      delete attrs.alt;
      attrs.href = `${f}.png`;

      // write the PDF, convert to PNG using the mac `sips`
      // command line tool, and trim with graphicsmagick

      file.on('finish', () =>
        exec(`sips -s format png ${f}.pdf --out ${f}.png`, function() {
          fs.unlink(`${f}.pdf`);
          exec(`gm convert ${f}.png -trim ${f}.png`);
        })
      );
    }
  }
};

const pages = [];
for (let file of Array.from(files)) {
  let content = fs.readFileSync(file, 'utf8');

  // turn github highlighted code blocks into normal markdown code blocks
  content = content.replace(
    /^```javascript\n((:?.|\n)*?)\n```/gm,
    (m, $1) => `    ${$1.split('\n').join('\n    ')}`
  );

  const tree = markdown.parse(content);
  const headers = extractHeaders(tree);
  generateImages(tree);

  file = file.replace(/README\.md/, 'index').replace(/\.md$/, '');

  pages.push({
    file,
    url: `/docs/${file}.html`,
    title: headers[0].title,
    headers: headers.slice(1),
    content: markdown.toHTML(tree)
  });
}

for (let index = 0; index < pages.length; index++) {
  const page = pages[index];
  page.pages = pages;
  page.index = index;
  const html = jade.renderFile('template.jade', page);
  fs.writeFileSync(page.file + '.html', html, 'utf8');
}


text:
"""
Toil script to move TCGA data into an S3 bucket.

Dependencies
Curl:       apt-get install curl
Docker:     wget -qO- https://get.docker.com/ | sh
Toil:       pip install toil
S3AM:       pip install --pre s3am
"""
import argparse
import glob
import hashlib
import os
import shutil
import subprocess
from toil.job import Job

def build_parser():
    parser = argparse.ArgumentParser(description=main.__doc__, formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('-g', '--genetorrent', default=None, required=True,
                        help='Path to a file with one analysis ID per line for data hosted on CGHub.')
    parser.add_argument('-k', '--genetorrent_key', default=None, required=True,
                        help='Path to a CGHub key that has access to the TCGA data being requested. An exception will'
                             'be thrown if "-g" is set but not this argument.')
    parser.add_argument('--s3_dir', default=None, required=True, help='S3 Bucket. e.g. tcga-data')
    parser.add_argument('--ssec', default=None, required=True, help='Path to Key File for SSE-C Encryption')
    parser.add_argument('--sudo', dest='sudo', default=None, action='store_true',
                        help='Docker usually needs sudo to execute locally, but not when running Mesos or when '
                             'the user is a member of a Docker group.')
    return parser

# Convenience Functions
def generate_unique_key(master_key_path, url):
    """
    master_key_path: str    Path to the BD2K Master Key (for S3 Encryption)
    url: str                S3 URL (e.g. https://s3-us-west-2.amazonaws.com/bucket/file.txt)

    Returns: str            32-byte unique key generated for that URL
    """
    with open(master_key_path, 'r') as f:
        master_key = f.read()
    assert len(master_key) == 32, 'Invalid Key! Must be 32 characters. ' \
                                  'Key: {}, Length: {}'.format(master_key, len(master_key))
    new_key = hashlib.sha256(master_key + url).digest()
    assert len(new_key) == 32, 'New key is invalid and is not 32 characters: {}'.format(new_key)
    return new_key

def docker_call(work_dir, tool_parameters, tool, java_opts=None, sudo=False, outfile=None):
    """
    Makes subprocess call of a command to a docker container.

    tool_parameters: list   An array of the parameters to be passed to the tool
    tool: str               Name of the Docker image to be used (e.g. quay.io/ucsc_cgl/samtools)
    java_opts: str          Optional commands to pass to a java jar execution. (e.g. '-Xmx15G')
    outfile: file           Filehandle that stderr will be passed to
    sudo: bool              If the user wants the docker command executed as sudo
    """
    base_docker_call = 'docker run --log-driver=none --rm -v {}:/data'.format(work_dir).split()
    if sudo:
        base_docker_call = ['sudo'] + base_docker_call
    if java_opts:
        base_docker_call = base_docker_call + ['-e', 'JAVA_OPTS={}'.format(java_opts)]
    try:
        if outfile:
            subprocess.check_call(base_docker_call + [tool] + tool_parameters, stdout=outfile)
        else:
            subprocess.check_call(base_docker_call + [tool] + tool_parameters)
    except subprocess.CalledProcessError:
        raise RuntimeError('docker command returned a non-zero exit status. Check error logs.')
    except OSError:
        raise RuntimeError('docker not found on system. Install on all nodes.')

def parse_genetorrent(path_to_config):
    """
    Parses genetorrent config file.  Returns list of samples: [ [id1, id1 ], [id2, id2], ... ]
    Returns duplicate of ids to follow UUID/URL standard.
    """
    samples = []
    with open(path_to_config, 'r') as f:
        for line in f.readlines():
            if not line.isspace():
                samples.append(line.strip())
    return samples

# Job Functions
def start_batch(job, input_args):
    """
    This function will administer 5 jobs at a time then recursively call itself until subset is empty
    """
    samples = parse_genetorrent(input_args['genetorrent'])
    # for analysis_id in samples:
    job.addChildJobFn(download_and_transfer_sample, input_args, samples, cores=1, disk='30G')

def download_and_transfer_sample(job, input_args, samples):

    """
    Downloads a sample from CGHub via GeneTorrent, then uses S3AM to transfer it to S3

    input_args: dict        Dictionary of input arguments
    analysis_id: str        An analysis ID for a sample in CGHub
    """
    if len(samples) > 1:
        a = samples[len(samples)/2:]
        b = samples[:len(samples)/2]
        job.addChildJobFn(download_and_transfer_sample, input_args, a, disk='30G')
        job.addChildJobFn(download_and_transfer_sample, input_args, b, disk='30G')
    else:
        analysis_id = samples[0]
        work_dir = job.fileStore.getLocalTempDir()
        folder_path = os.path.join(work_dir, os.path.basename(analysis_id))
        sudo = input_args['sudo']
        # Acquire genetorrent key and download sample
        shutil.copy(input_args['genetorrent_key'], os.path.join(work_dir, 'cghub.key'))
        parameters = ['-vv', '-c', 'cghub.key', '-d', analysis_id]
        docker_call(tool='quay.io/ucsc_cgl/genetorrent:3.8.7--9911761265b6f08bc3ef09f53af05f56848d805b',
                    work_dir=work_dir, tool_parameters=parameters, sudo=sudo)
        try:
            sample = glob.glob(os.path.join(folder_path, '*tar*'))[0]
        except KeyError as e:
            print 'No tarfile found inside of folder: '.format(e)
            raise
        # Upload sample to S3AM
        key_path = input_args['ssec']
        if sample.endswith('gz'):
            sample_name = analysis_id + '.tar.gz'
            shutil.move(sample, os.path.join(work_dir, sample_name))
        else:
            sample_name = analysis_id + '.tar'
            shutil.move(sample, os.path.join(work_dir, sample_name))
        # Parse s3_dir to get bucket and s3 path
        s3_dir = input_args['s3_dir']
        bucket_name = s3_dir.lstrip('/').split('/')[0]
        base_url = 'https://s3-us-west-2.amazonaws.com/'
        url = os.path.join(base_url, bucket_name, sample_name)
        # Generate keyfile for upload
        with open(os.path.join(work_dir, 'temp.key'), 'wb') as f_out:
            f_out.write(generate_unique_key(key_path, url))
        # Upload to S3 via S3AM
        s3am_command = ['s3am',
                        'upload',
                        '--sse-key-file', os.path.join(work_dir, 'temp.key'),
                        'file://{}'.format(os.path.join(work_dir, sample_name)),
                        's3://' + bucket_name + '/']
        subprocess.check_call(s3am_command)

def main():
    """
    This is a Toil pipeline to transfer TCGA data into an S3 Bucket

    Data is pulled down with Genetorrent and transferred to S3 via S3AM.
    """
    # Define Parser object and add to toil
    parser = build_parser()
    Job.Runner.addToilOptions(parser)
    args = parser.parse_args()
    # Store inputs from argparse
    inputs = {'genetorrent': args.genetorrent,
              'genetorrent_key': args.genetorrent_key,
              'ssec': args.ssec,
              's3_dir': args.s3_dir,
              'sudo': args.sudo}
    # Sanity checks
    if args.ssec:
        assert os.path.isfile(args.ssec)
    if args.genetorrent:
        assert os.path.isfile(args.genetorrent)
    if args.genetorrent_key:
        assert os.path.isfile(args.genetorrent_key)
    # Start Pipeline
    Job.Runner.startToil(Job.wrapJobFn(start_batch, inputs), args)

if __name__ == '__main__':
    main()


text:
// Package dynamic provides a client interface to arbitrary Kubernetes
// APIs that exposes common high level operations and exposes common
// metadata.
package dynamic

import (
	"encoding/json"
	"errors"
	"io"
	"net/url"
	"strings"

	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/unversioned"
	"k8s.io/kubernetes/pkg/api/v1"
	"k8s.io/kubernetes/pkg/client/restclient"
	"k8s.io/kubernetes/pkg/conversion/queryparams"
	"k8s.io/kubernetes/pkg/runtime"
	"k8s.io/kubernetes/pkg/runtime/serializer"
	"k8s.io/kubernetes/pkg/watch"
)

// Client is a Kubernetes client that allows you to access metadata
// and manipulate metadata of a Kubernetes API group.
type Client struct {
	cl *restclient.RESTClient
}

type ClientWithParameterCodec struct {
	client         *Client
	parameterCodec runtime.ParameterCodec
}

// NewClient returns a new client based on the passed in config. The
// codec is ignored, as the dynamic client uses it's own codec.
func NewClient(conf *restclient.Config) (*Client, error) {
	// avoid changing the original config
	confCopy := *conf
	conf = &confCopy

	codec := dynamicCodec{}

	// TODO: it's questionable that this should be using anything other than unstructured schema and JSON
	conf.ContentType = runtime.ContentTypeJSON
	conf.AcceptContentTypes = runtime.ContentTypeJSON
	streamingInfo, _ := api.Codecs.StreamingSerializerForMediaType("application/json;stream=watch", nil)
	conf.NegotiatedSerializer = serializer.NegotiatedSerializerWrapper(runtime.SerializerInfo{Serializer: codec}, streamingInfo)

	if conf.APIPath == "" {
		conf.APIPath = "/api"
	}

	if len(conf.UserAgent) == 0 {
		conf.UserAgent = restclient.DefaultKubernetesUserAgent()
	}

	if conf.QPS == 0.0 {
		conf.QPS = 5.0
	}
	if conf.Burst == 0 {
		conf.Burst = 10
	}

	cl, err := restclient.RESTClientFor(conf)
	if err != nil {
		return nil, err
	}

	return &Client{cl: cl}, nil
}

// Resource returns an API interface to the specified resource for this client's
// group and version. If resource is not a namespaced resource, then namespace
// is ignored.
func (c *Client) Resource(resource *unversioned.APIResource, namespace string) *ResourceClient {
	return &ResourceClient{
		cl:       c.cl,
		resource: resource,
		ns:       namespace,
	}
}

// ParameterCodec wraps a parameterCodec around the Client.
func (c *Client) ParameterCodec(parameterCodec runtime.ParameterCodec) *ClientWithParameterCodec {
	return &ClientWithParameterCodec{
		client:         c,
		parameterCodec: parameterCodec,
	}
}

// Resource returns an API interface to the specified resource for this client's
// group and version. If resource is not a namespaced resource, then namespace
// is ignored. The ResourceClient inherits the parameter codec of c.
func (c *ClientWithParameterCodec) Resource(resource *unversioned.APIResource, namespace string) *ResourceClient {
	return &ResourceClient{
		cl:             c.client.cl,
		resource:       resource,
		ns:             namespace,
		parameterCodec: c.parameterCodec,
	}
}

// ResourceClient is an API interface to a specific resource under a
// dynamic client.
type ResourceClient struct {
	cl             *restclient.RESTClient
	resource       *unversioned.APIResource
	ns             string
	parameterCodec runtime.ParameterCodec
}

// List returns a list of objects for this resource.
func (rc *ResourceClient) List(opts runtime.Object) (*runtime.UnstructuredList, error) {
	result := new(runtime.UnstructuredList)
	parameterEncoder := rc.parameterCodec
	if parameterEncoder == nil {
		parameterEncoder = defaultParameterEncoder
	}
	err := rc.cl.Get().
		NamespaceIfScoped(rc.ns, rc.resource.Namespaced).
		Resource(rc.resource.Name).
		VersionedParams(opts, parameterEncoder).
		Do().
		Into(result)
	return result, err
}

// Get gets the resource with the specified name.
func (rc *ResourceClient) Get(name string) (*runtime.Unstructured, error) {
	result := new(runtime.Unstructured)
	err := rc.cl.Get().
		NamespaceIfScoped(rc.ns, rc.resource.Namespaced).
		Resource(rc.resource.Name).
		Name(name).
		Do().
		Into(result)
	return result, err
}

// Delete deletes the resource with the specified name.
func (rc *ResourceClient) Delete(name string, opts *v1.DeleteOptions) error {
	return rc.cl.Delete().
		NamespaceIfScoped(rc.ns, rc.resource.Namespaced).
		Resource(rc.resource.Name).
		Name(name).
		Body(opts).
		Do().
		Error()
}

// DeleteCollection deletes a collection of objects.
func (rc *ResourceClient) DeleteCollection(deleteOptions *v1.DeleteOptions, listOptions runtime.Object) error {
	parameterEncoder := rc.parameterCodec
	if parameterEncoder == nil {
		parameterEncoder = defaultParameterEncoder
	}
	return rc.cl.Delete().
		NamespaceIfScoped(rc.ns, rc.resource.Namespaced).
		Resource(rc.resource.Name).
		VersionedParams(listOptions, parameterEncoder).
		Body(deleteOptions).
		Do().
		Error()
}

// Create creates the provided resource.
func (rc *ResourceClient) Create(obj *runtime.Unstructured) (*runtime.Unstructured, error) {
	result := new(runtime.Unstructured)
	err := rc.cl.Post().
		NamespaceIfScoped(rc.ns, rc.resource.Namespaced).
		Resource(rc.resource.Name).
		Body(obj).
		Do().
		Into(result)
	return result, err
}

// Update updates the provided resource.
func (rc *ResourceClient) Update(obj *runtime.Unstructured) (*runtime.Unstructured, error) {
	result := new(runtime.Unstructured)
	if len(obj.GetName()) == 0 {
		return result, errors.New("object missing name")
	}
	err := rc.cl.Put().
		NamespaceIfScoped(rc.ns, rc.resource.Namespaced).
		Resource(rc.resource.Name).
		Name(obj.GetName()).
		Body(obj).
		Do().
		Into(result)
	return result, err
}

// Watch returns a watch.Interface that watches the resource.
func (rc *ResourceClient) Watch(opts runtime.Object) (watch.Interface, error) {
	parameterEncoder := rc.parameterCodec
	if parameterEncoder == nil {
		parameterEncoder = defaultParameterEncoder
	}
	return rc.cl.Get().
		Prefix("watch").
		NamespaceIfScoped(rc.ns, rc.resource.Namespaced).
		Resource(rc.resource.Name).
		VersionedParams(opts, parameterEncoder).
		Watch()
}

func (rc *ResourceClient) Patch(name string, pt api.PatchType, data []byte) (*runtime.Unstructured, error) {
	result := new(runtime.Unstructured)
	err := rc.cl.Patch(pt).
		NamespaceIfScoped(rc.ns, rc.resource.Namespaced).
		Resource(rc.resource.Name).
		Name(name).
		Body(data).
		Do().
		Into(result)
	return result, err
}

// dynamicCodec is a codec that wraps the standard unstructured codec
// with special handling for Status objects.
type dynamicCodec struct{}

func (dynamicCodec) Decode(data []byte, gvk *unversioned.GroupVersionKind, obj runtime.Object) (runtime.Object, *unversioned.GroupVersionKind, error) {
	obj, gvk, err := runtime.UnstructuredJSONScheme.Decode(data, gvk, obj)
	if err != nil {
		return nil, nil, err
	}

	if _, ok := obj.(*unversioned.Status); !ok && strings.ToLower(gvk.Kind) == "status" {
		obj = &unversioned.Status{}
		err := json.Unmarshal(data, obj)
		if err != nil {
			return nil, nil, err
		}
	}

	return obj, gvk, nil
}

func (dynamicCodec) Encode(obj runtime.Object, w io.Writer) error {
	return runtime.UnstructuredJSONScheme.Encode(obj, w)
}

// paramaterCodec is a codec converts an API object to query
// parameters without trying to convert to the target version.
type parameterCodec struct{}

func (parameterCodec) EncodeParameters(obj runtime.Object, to unversioned.GroupVersion) (url.Values, error) {
	return queryparams.Convert(obj)
}

func (parameterCodec) DecodeParameters(parameters url.Values, from unversioned.GroupVersion, into runtime.Object) error {
	return errors.New("DecodeParameters not implemented on dynamic parameterCodec")
}

var defaultParameterEncoder runtime.ParameterCodec = parameterCodec{}

type versionedParameterEncoderWithV1Fallback struct{}

func (versionedParameterEncoderWithV1Fallback) EncodeParameters(obj runtime.Object, to unversioned.GroupVersion) (url.Values, error) {
	ret, err := api.ParameterCodec.EncodeParameters(obj, to)
	if err != nil && runtime.IsNotRegisteredError(err) {
		// fallback to v1
		return api.ParameterCodec.EncodeParameters(obj, v1.SchemeGroupVersion)
	}
	return ret, err
}

func (versionedParameterEncoderWithV1Fallback) DecodeParameters(parameters url.Values, from unversioned.GroupVersion, into runtime.Object) error {
	return errors.New("DecodeParameters not implemented on versionedParameterEncoderWithV1Fallback")
}

// VersionedParameterEncoderWithV1Fallback is useful for encoding query
// parameters for thirdparty resources. It tries to convert object to the
// specified version before converting it to query parameters, and falls back to
// converting to v1 if the object is not registered in the specified version.
// For the record, currently API server always treats query parameters sent to a
// thirdparty resource endpoint as v1.
var VersionedParameterEncoderWithV1Fallback runtime.ParameterCodec = versionedParameterEncoderWithV1Fallback{}


text:
// +build !ignore_autogenerated

// This file was autogenerated by deepcopy-gen. Do not edit it manually!

package resource

import (
	conversion "k8s.io/kubernetes/pkg/conversion"
	inf "speter.net/go/exp/math/dec/inf"
)

func DeepCopy_resource_Quantity(in Quantity, out *Quantity, c *conversion.Cloner) error {
	if in.Amount != nil {
		in, out := in.Amount, &out.Amount
		*out = new(inf.Dec)
		if newVal, err := c.DeepCopy(*in); err != nil {
			return err
		} else {
			**out = newVal.(inf.Dec)
		}
	} else {
		out.Amount = nil
	}
	out.Format = in.Format
	return nil
}

func DeepCopy_resource_QuantityProto(in QuantityProto, out *QuantityProto, c *conversion.Cloner) error {
	out.Format = in.Format
	out.Scale = in.Scale
	if in.Bigint != nil {
		in, out := in.Bigint, &out.Bigint
		*out = make([]byte, len(in))
		copy(*out, in)
	} else {
		out.Bigint = nil
	}
	return nil
}


text:
/**
 * Manually written TypeScript definition file for @google-cloud/monitoring
 * since it doesn't exist yet.
 */
/// <reference types="gapi.client.monitoring" />

declare module '@google-cloud/monitoring' {
  interface Timestamp {
    seconds: number;
    nanos?: number;
  }

  class MetricServiceClient {
    /** Return a fully-qualified project resource name string. */
    projectPath(projectId: string): string;

    /**
     * Simplified type definition for listTimeSeries method.
     * https://cloud.google.com/nodejs/docs/reference/monitoring/0.7.x/v3.MetricServiceClient#listTimeSeries
     */
    listTimeSeries(request: {
      name: string,
      filter: string,
      interval: {startTime: Timestamp, endTime: Timestamp},
      aggregation?: {
        alignmentPeriod?: {
          seconds: number,
        },
        perSeriesAligner?: string,
        crossSeriesReducer?: string,
      }
    }): Promise<[gapi.client.monitoring.TimeSeries[]]>;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace CSharpGL
{
    /// <summary>
    /// Get picked geometry.
    /// </summary>
    abstract class PickerBase
    {
        /// <summary>
        /// Get picked geometry.
        /// </summary>
        /// <param name="node"></param>
        /// <param name="positionBuffer"></param>
        public PickerBase(PickableNode node, VertexBuffer positionBuffer)
        {
            this.Node = node;
            this.PositionBuffer = positionBuffer;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="arg"></param>
        /// <param name="stageVertexId">The last vertex's id that constructs the picked primitive.
        /// <para>This id is in scene's all <see cref="IPickable"/>s' order.</para></param>
        /// <param name="baseId">Index of first vertex of the buffer that The geometry belongs to.
        /// <para>This id is in scene's all <see cref="IPickable"/>s' order.</para></param>
        /// <returns></returns>
        public abstract PickedGeometry GetPickedGeometry(PickingEventArgs arg, uint stageVertexId, uint baseId);

        /// <summary>
        ///
        /// </summary>
        public PickableNode Node { get; private set; }

        /// <summary>
        ///
        /// </summary>
        public VertexBuffer PositionBuffer { get; set; }

        protected vec3[] FillPickedGeometrysPosition(uint firstIndex, int indexCount)
        {
            var positionIndexes = new uint[indexCount];
            for (uint i = 0; i < indexCount; i++)
            {
                positionIndexes[i] = firstIndex + i;
            }

            return FillPickedGeometrysPosition(positionIndexes);
        }

        protected vec3[] FillPickedGeometrysPosition(uint[] positionIndexes)
        {
            VertexBuffer[] buffers = this.Node.PickingRenderMethod.PositionBuffers;
            IEnumerable<IndexesInBuffer> workItems = buffers.GetWorkItems(positionIndexes);
            var positions = new List<vec3>();
            foreach (var item in workItems)
            {
                VertexBuffer buffer = buffers[item.whichBuffer];
                IntPtr pointer = buffer.MapBuffer(MapBufferAccess.ReadOnly);
                unsafe
                {
                    var array = (vec3*)pointer.ToPointer();
                    foreach (var indexInBuffer in item.indexesInBuffer)
                    {
                        positions.Add(array[indexInBuffer]);
                    }
                }
                buffer.UnmapBuffer();
            }

            return positions.ToArray();
        }

    }
}


text:
# FlightNode.DataCollection.Domain

Domain logic for all of FlightNode's data collection needs, including management of

* bird data reports
* volunteer hours
* locations

Modeled using the [onion architecture](http://jeffreypalermo.com/blog/the-onion-architecture-part-1/)


text:
namespace ui {

namespace {

// To test the handling of |EventRewriter|s through |EventSource|,
// we rewrite and test event types.
class TestEvent : public Event {
 public:
  explicit TestEvent(EventType type)
      : Event(type, base::TimeTicks(), 0), unique_id_(next_unique_id_++) {}
  ~TestEvent() override {}
  int unique_id() const { return unique_id_; }

 private:
  static int next_unique_id_;
  int unique_id_;
};

int TestEvent::next_unique_id_ = 0;

// TestEventRewriteProcessor is set up with a sequence of event types,
// and fails if the events received via OnEventFromSource() do not match
// this sequence. These expected event types are consumed on receipt.
class TestEventRewriteProcessor : public test::TestEventProcessor {
 public:
  TestEventRewriteProcessor() {}
  ~TestEventRewriteProcessor() override { CheckAllReceived(); }

  void AddExpectedEvent(EventType type) { expected_events_.push_back(type); }
  // Test that all expected events have been received.
  void CheckAllReceived() { EXPECT_TRUE(expected_events_.empty()); }

  // EventProcessor:
  EventDispatchDetails OnEventFromSource(Event* event) override {
    EXPECT_FALSE(expected_events_.empty());
    EXPECT_EQ(expected_events_.front(), event->type());
    expected_events_.pop_front();
    return EventDispatchDetails();
  }

 private:
  std::list<EventType> expected_events_;
  DISALLOW_COPY_AND_ASSIGN(TestEventRewriteProcessor);
};

// Trivial EventSource that does nothing but send events.
class TestEventRewriteSource : public EventSource {
 public:
  explicit TestEventRewriteSource(EventProcessor* processor)
      : processor_(processor) {}
  EventProcessor* GetEventProcessor() override { return processor_; }
  void Send(EventType type) {
    std::unique_ptr<Event> event(new TestEvent(type));
    (void)SendEventToProcessor(event.get());
  }

 private:
  EventProcessor* processor_;
};

// This EventRewriter always returns the same status, and if rewriting, the
// same event type; it is used to test simple rewriting, and rewriter addition,
// removal, and sequencing. Consequently EVENT_REWRITE_DISPATCH_ANOTHER is not
// supported here (calls to NextDispatchEvent() would continue indefinitely).
class TestConstantEventRewriter : public EventRewriter {
 public:
  TestConstantEventRewriter(EventRewriteStatus status, EventType type)
      : status_(status), type_(type) {
    CHECK_NE(EVENT_REWRITE_DISPATCH_ANOTHER, status);
  }

  EventRewriteStatus RewriteEvent(
      const Event& event,
      std::unique_ptr<Event>* rewritten_event) override {
    if (status_ == EVENT_REWRITE_REWRITTEN)
      rewritten_event->reset(new TestEvent(type_));
    return status_;
  }
  EventRewriteStatus NextDispatchEvent(
      const Event& last_event,
      std::unique_ptr<Event>* new_event) override {
    NOTREACHED();
    return status_;
  }

 private:
  EventRewriteStatus status_;
  EventType type_;
};

// This EventRewriter runs a simple state machine; it is used to test
// EVENT_REWRITE_DISPATCH_ANOTHER.
class TestStateMachineEventRewriter : public EventRewriter {
 public:
  TestStateMachineEventRewriter() : last_rewritten_event_(0), state_(0) {}
  void AddRule(int from_state, EventType from_type,
               int to_state, EventType to_type, EventRewriteStatus to_status) {
    RewriteResult r = {to_state, to_type, to_status};
    rules_.insert(std::pair<RewriteCase, RewriteResult>(
        RewriteCase(from_state, from_type), r));
  }
  EventRewriteStatus RewriteEvent(
      const Event& event,
      std::unique_ptr<Event>* rewritten_event) override {
    RewriteRules::iterator find =
        rules_.find(RewriteCase(state_, event.type()));
    if (find == rules_.end())
      return EVENT_REWRITE_CONTINUE;
    if ((find->second.status == EVENT_REWRITE_REWRITTEN) ||
        (find->second.status == EVENT_REWRITE_DISPATCH_ANOTHER)) {
      last_rewritten_event_ = new TestEvent(find->second.type);
      rewritten_event->reset(last_rewritten_event_);
    } else {
      last_rewritten_event_ = 0;
    }
    state_ = find->second.state;
    return find->second.status;
  }
  EventRewriteStatus NextDispatchEvent(
      const Event& last_event,
      std::unique_ptr<Event>* new_event) override {
    EXPECT_TRUE(last_rewritten_event_);
    const TestEvent* arg_last = static_cast<const TestEvent*>(&last_event);
    EXPECT_EQ(last_rewritten_event_->unique_id(), arg_last->unique_id());
    const TestEvent* arg_new = static_cast<const TestEvent*>(new_event->get());
    EXPECT_FALSE(arg_new && arg_last->unique_id() == arg_new->unique_id());
    return RewriteEvent(last_event, new_event);
  }

 private:
  typedef std::pair<int, EventType> RewriteCase;
  struct RewriteResult {
    int state;
    EventType type;
    EventRewriteStatus status;
  };
  typedef std::map<RewriteCase, RewriteResult> RewriteRules;
  RewriteRules rules_;
  TestEvent* last_rewritten_event_;
  int state_;
};

}  // namespace

TEST(EventRewriterTest, EventRewriting) {
  // TestEventRewriter r0 always rewrites events to ET_CANCEL_MODE;
  // it is placed at the beginning of the chain and later removed,
  // to verify that rewriter removal works.
  TestConstantEventRewriter r0(EVENT_REWRITE_REWRITTEN, ET_CANCEL_MODE);

  // TestEventRewriter r1 always returns EVENT_REWRITE_CONTINUE;
  // it is placed at the beginning of the chain to verify that a
  // later rewriter sees the events.
  TestConstantEventRewriter r1(EVENT_REWRITE_CONTINUE, ET_UNKNOWN);

  // TestEventRewriter r2 has a state machine, primarily to test
  // |EVENT_REWRITE_DISPATCH_ANOTHER|.
  TestStateMachineEventRewriter r2;

  // TestEventRewriter r3 always rewrites events to ET_CANCEL_MODE;
  // it is placed at the end of the chain to verify that previously
  // rewritten events are not passed further down the chain.
  TestConstantEventRewriter r3(EVENT_REWRITE_REWRITTEN, ET_CANCEL_MODE);

  TestEventRewriteProcessor p;
  TestEventRewriteSource s(&p);
  s.AddEventRewriter(&r0);
  s.AddEventRewriter(&r1);
  s.AddEventRewriter(&r2);

  // These events should be rewritten by r0 to ET_CANCEL_MODE.
  p.AddExpectedEvent(ET_CANCEL_MODE);
  s.Send(ET_MOUSE_DRAGGED);
  p.AddExpectedEvent(ET_CANCEL_MODE);
  s.Send(ET_MOUSE_PRESSED);
  p.CheckAllReceived();

  // Remove r0, and verify that it's gone and that events make it through.
  s.AddEventRewriter(&r3);
  s.RemoveEventRewriter(&r0);
  r2.AddRule(0, ET_SCROLL_FLING_START,
             0, ET_SCROLL_FLING_CANCEL, EVENT_REWRITE_REWRITTEN);
  p.AddExpectedEvent(ET_SCROLL_FLING_CANCEL);
  s.Send(ET_SCROLL_FLING_START);
  p.CheckAllReceived();
  s.RemoveEventRewriter(&r3);

  // Verify EVENT_REWRITE_DISPATCH_ANOTHER using a state machine
  // (that happens to be analogous to sticky keys).
  r2.AddRule(0, ET_KEY_PRESSED,
             1, ET_KEY_PRESSED, EVENT_REWRITE_CONTINUE);
  r2.AddRule(1, ET_MOUSE_PRESSED,
             0, ET_MOUSE_PRESSED, EVENT_REWRITE_CONTINUE);
  r2.AddRule(1, ET_KEY_RELEASED,
             2, ET_KEY_RELEASED, EVENT_REWRITE_DISCARD);
  r2.AddRule(2, ET_MOUSE_RELEASED,
             3, ET_MOUSE_RELEASED, EVENT_REWRITE_DISPATCH_ANOTHER);
  r2.AddRule(3, ET_MOUSE_RELEASED,
             0, ET_KEY_RELEASED, EVENT_REWRITE_REWRITTEN);
  p.AddExpectedEvent(ET_KEY_PRESSED);
  s.Send(ET_KEY_PRESSED);
  s.Send(ET_KEY_RELEASED);
  p.AddExpectedEvent(ET_MOUSE_PRESSED);
  s.Send(ET_MOUSE_PRESSED);

  // Removing rewriters r1 and r3 shouldn't affect r2.
  s.RemoveEventRewriter(&r1);
  s.RemoveEventRewriter(&r3);

  // Continue with the state-based rewriting.
  p.AddExpectedEvent(ET_MOUSE_RELEASED);
  p.AddExpectedEvent(ET_KEY_RELEASED);
  s.Send(ET_MOUSE_RELEASED);
  p.CheckAllReceived();
}

}  // namespace ui


text:
<?xml version="1.0" encoding="UTF-8"?>
<content>
    <container name="smapSelector" block="alfa" widget="static">
        <component name="siteList" class="Energine\shop\components\SiteList">
            <params>
                <param name="rights" type="hidden">2</param>
                <param name="config" type="hidden">
                    <configuration>
                        <state name="main">
                            <fields>
                                <field name="site_id" type="int"></field>
                                <field name="site_name" type="string"></field>
                                <field name="site_host" type="string"></field>
                            </fields>
                        </state>
                    </configuration>
                </param>
            </params>
        </component>
        <component name="categoryDivEditor" class="Energine\shop\components\CategoryEditor">
            <params>
                <param name="rights" type="hidden">2</param>
                <param name="state" type="hidden">main</param>
            </params>
        </component>
    </container>
</content>


text:
cask 'captur' do
  version '2.4'
  sha256 '1f6f19806290c1c366701a8391fdc26cae3b1a54e3d54d715e420346eeb66648'

  # dropboxusercontent.com is the official download host per the vendor homepage
  url "https://dl.dropboxusercontent.com/u/27027504/captur-#{version}.dmg.zip"
  name 'Captur'
  homepage 'http://cambhlumbulunk.blogspot.co.uk/p/captur.html'
  license :gratis

  container nested: "captur-#{version}.dmg"

  app '64 Bit/Captur.app'
end


text:
/**
 * This is the DirectSocket package of the SmartSockets library.
 *
 * MORE
 */
package ibis.smartsockets.direct;


text:
require "firebell/version"

module Firebell
  class NoTokenError < StandardError; end

  def self.configure
    yield configuration
    configuration
  end

  def self.configuration
    @@configuration ||= Configuration.new
  end

  class Configuration
    attr_writer :host, :url, :notify_release_stages
    attr_accessor :token, :release_stage

    def host
      @host ||= "https://firebellapp.com"
    end

    def path
      @path ||= "/api/v1/events"
    end

    def url
      @url ||= "#{host}#{path}"
    end

    def notify_release_stages
      @notify_release_stages ||= []
    end
  end
end

require "firebell/client"


text:
require 'contracts'
require 'rakuna/provides/output'

module Rakuna
  module Provides
    module HTML
      include Contracts
      include Rakuna::Provides::Output

      Contract None => ArrayOf[Array]
      def content_types_provided
        @content_types_provided ||= super << ['text/html', :to_html]
      end

      Contract None => String
      def to_html
        output
      end
    end
  end
end


text:
/* eslint-disable no-var */
// Simple JavaScript Templating
// Paul Miller (http://paulmillr.com)
// http://underscorejs.org
// (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors

// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
var settings = {
  evaluate    : /<%([\s\S]+?)%>/g,
  interpolate : /<%=([\s\S]+?)%>/g,
  escape      : /<%-([\s\S]+?)%>/g
}

// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/

// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
  '\'':      '\'',
  '\\':     '\\',
  '\r':     'r',
  '\n':     'n',
  '\t':     't',
  '\u2028': 'u2028',
  '\u2029': 'u2029'
}

var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g

// List of HTML entities for escaping.
var htmlEntities = {
  '&': '&',
  '<': '<',
  '>': '>',
  '"': '"',
  '\'': '''
}

var entityRe = new RegExp('[&<>"\']', 'g')

var escapeExpr = function(string) {
  if (string === null) {return ''}
  return ('' + string).replace(entityRe, function(match) {
    return htmlEntities[match]
  })
}

var counter = 0

// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
var tmpl = function(text, data) {
  var render

  // Combine delimiters into one regular expression via alternation.
  var matcher = new RegExp([
    (settings.escape || noMatch).source,
    (settings.interpolate || noMatch).source,
    (settings.evaluate || noMatch).source
  ].join('|') + '|$', 'g')

  // Compile the template source, escaping string literals appropriately.
  var index = 0
  var source = '__p+=\''
  text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
    source += text.slice(index, offset)
      .replace(escaper, function(match) { return '\\' + escapes[match] })

    if (escape) {
      source += '\'+\n((__t=(' + escape + '))==null?\'\':escapeExpr(__t))+\n\''
    }
    if (interpolate) {
      source += '\'+\n((__t=(' + interpolate + '))==null?\'\':__t)+\n\''
    }
    if (evaluate) {
      source += '\';\n' + evaluate + '\n__p+=\''
    }
    index = offset + match.length
    return match
  })
  source += '\';\n'

  // If a variable is not specified, place data values in local scope.
  if (!settings.variable) {source = 'with(obj||{}){\n' + source + '}\n'}

  source = 'var __t,__p=\'\',__j=Array.prototype.join,' +
    'print=function(){__p+=__j.call(arguments,\'\');};\n' +
    source + 'return __p;\n//# sourceURL=/microtemplates/source[' + counter++ + ']'

  try {
    /*jshint -W054 */
    // TODO: find a way to avoid eval
    render = new Function(settings.variable || 'obj', 'escapeExpr', source)
  } catch (e) {
    e.source = source
    throw e
  }

  if (data) {return render(data, escapeExpr)}
  var template = function(data) {
    return render.call(this, data, escapeExpr)
  }

  // Provide the compiled function source as a convenience for precompilation.
  template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'

  return template
}
tmpl.settings = settings

export default tmpl