text:
using namespace swift;

/// Instructions which read from memory, e.g. loads, or function calls without
/// side effects.
using ReadSet = llvm::SmallPtrSet<SILInstruction *, 8>;

/// Instructions which (potentially) write memory.
using WriteSet = SmallVector<SILInstruction *, 8>;

/// Returns true if the \p MayWrites set contains any memory writes which may
/// alias with the memory addressed by \a LI.
static bool mayWriteTo(AliasAnalysis *AA, WriteSet &MayWrites, LoadInst *LI) {
  for (auto *W : MayWrites)
    if (AA->mayWriteToMemory(W, LI->getOperand())) {
      DEBUG(llvm::dbgs() << "  mayWriteTo\n" << *W << " to " << *LI << "\n");
      return true;
    }
  return false;
}

/// Returns true if the \p MayWrites set contains any memory writes which may
/// alias with any memory which is read by \p AI.
static bool mayWriteTo(AliasAnalysis *AA, SideEffectAnalysis *SEA,
                       WriteSet &MayWrites, ApplyInst *AI) {
  SideEffectAnalysis::FunctionEffects E;
  SEA->getEffects(E, AI);
  assert(E.getMemBehavior(RetainObserveKind::IgnoreRetains) <=
         SILInstruction::MemoryBehavior::MayRead &&
         "apply should only read from memory");
  if (E.getGlobalEffects().mayRead() && !MayWrites.empty()) {
    // We don't know which memory is read in the callee. Therefore we bail if
    // there are any writes in the loop.
    return true;
  }

  for (unsigned Idx = 0, End = AI->getNumArguments(); Idx < End; ++Idx) {
    auto &ArgEffect = E.getParameterEffects()[Idx];
    if (!ArgEffect.mayRead())
      continue;

    SILValue Arg = AI->getArgument(Idx);

    // Check if the memory addressed by the argument may alias any writes.
    for (auto *W : MayWrites) {
      if (AA->mayWriteToMemory(W, Arg)) {
        DEBUG(llvm::dbgs() << "  mayWriteTo\n" << *W << " to " << *AI << "\n");
        return true;
      }
    }
  }
  return false;
}

static void removeWrittenTo(AliasAnalysis *AA, ReadSet &Reads,
                            SILInstruction *ByInst) {

  // We can ignore retains, cond_fails, and dealloc_stacks.
  if (isa<StrongRetainInst>(ByInst) || isa<RetainValueInst>(ByInst) ||
      isa<CondFailInst>(ByInst) || isa<DeallocStackInst>(ByInst))
    return;

  SmallVector<SILInstruction *, 8> RS(Reads.begin(), Reads.end());
  for (auto R : RS) {
    auto *LI = dyn_cast<LoadInst>(R);
    if (LI && !AA->mayWriteToMemory(ByInst, LI->getOperand()))
      continue;

    DEBUG(llvm::dbgs() << "  mayWriteTo\n" << *ByInst << " to " << *R << "\n");
    Reads.erase(R);
  }
}

static bool hasLoopInvariantOperands(SILInstruction *I, SILLoop *L) {
  auto Opds = I->getAllOperands();

  return std::all_of(Opds.begin(), Opds.end(), [=](Operand &Op) {

    ValueBase *Def = Op.get();

    // Operand is defined outside the loop.
    if (auto *Inst = dyn_cast<SILInstruction>(Def))
      return !L->contains(Inst->getParent());
    if (auto *Arg = dyn_cast<SILArgument>(Def))
      return !L->contains(Arg->getParent());

    return false;
  });
}

/// Check if an address does not depend on other values in a basic block.
static SILInstruction *addressIndependent(SILValue Addr) {
  Addr = stripCasts(Addr);
  if (GlobalAddrInst *SGAI = dyn_cast<GlobalAddrInst>(Addr))
    return SGAI;
  if (StructElementAddrInst *SEAI = dyn_cast<StructElementAddrInst>(Addr))
    return addressIndependent(SEAI->getOperand());
  return nullptr;
}

/// Check if two addresses can potentially access the same memory.
/// For now, return true when both can be traced to the same global variable.
static bool addressCanPairUp(SILValue Addr1, SILValue Addr2) {
  SILInstruction *Origin1 = addressIndependent(Addr1);
  return Origin1 && Origin1 == addressIndependent(Addr2);
}

/// Move cond_fail down if it can potentially help register promotion later.
static bool sinkCondFail(SILLoop *Loop) {
  // Only handle innermost loops for now.
  if (!Loop->getSubLoops().empty())
    return false;

  bool Changed = false;
  for (auto *BB : Loop->getBlocks()) {
    // A list of CondFails that can be moved down.
    SmallVector<CondFailInst*, 4> CFs;
    // A pair of load and store that are independent of the CondFails and
    // can potentially access the same memory.
    LoadInst *LIOfPair = nullptr;
    bool foundPair = false;

    for (auto &Inst : *BB) {
      if (foundPair) {
        // Move CFs to right before Inst.
        for (unsigned I = 0, E = CFs.size(); I < E; I++) {
          DEBUG(llvm::dbgs() << "sinking cond_fail down ");
          DEBUG(CFs[I]->dump());
          DEBUG(llvm::dbgs() << "  before ");
          DEBUG(Inst.dump());
          CFs[I]->moveBefore(&Inst);
        }
        Changed = true;

        foundPair = false;
        LIOfPair = nullptr;
      }

      if (auto CF = dyn_cast<CondFailInst>(&Inst)) {
        CFs.push_back(CF);
      } else if (auto LI = dyn_cast<LoadInst>(&Inst)) {
        if (addressIndependent(LI->getOperand())) {
          LIOfPair = LI;
        } else {
          CFs.clear();
          LIOfPair = nullptr;
        }
      } else if (auto SI = dyn_cast<StoreInst>(&Inst)) {
        if (addressIndependent(SI->getDest())) {
          if (LIOfPair &&
              addressCanPairUp(SI->getDest(), LIOfPair->getOperand()))
            foundPair = true;
        } else {
          CFs.clear();
          LIOfPair = nullptr;
        }
      } else if (Inst.mayHaveSideEffects()) {
        CFs.clear();
        LIOfPair = nullptr;
      }
    }
  }
  return Changed;
}

/// Checks if \p Inst has no side effects which prevent hoisting.
/// The \a SafeReads set contain instructions which we already proved to have
/// no such side effects.
static bool hasNoSideEffect(SILInstruction *Inst, ReadSet &SafeReads) {
  // We can (and must) hoist cond_fail instructions if the operand is
  // invariant. We must hoist them so that we preserve memory safety. A
  // cond_fail that would have protected (executed before) a memory access
  // must - after hoisting - also be executed before said access.
  if (isa<CondFailInst>(Inst))
    return true;

  // Can't hoist if the instruction could read from memory and is not marked
  // as safe.
  if (SafeReads.count(Inst))
    return true;

  if (Inst->getMemoryBehavior() == SILInstruction::MemoryBehavior::None)
    return true;

  return false;
}

static bool canHoistInstruction(SILInstruction *Inst, SILLoop *Loop,
                                ReadSet &SafeReads) {
  // Can't hoist terminators.
  if (isa<TermInst>(Inst))
    return false;

  // Can't hoist allocation and dealloc stacks.
  if (isa<AllocationInst>(Inst) || isa<DeallocStackInst>(Inst))
    return false;

  // Can't hoist instructions which may have side effects.
  if (!hasNoSideEffect(Inst, SafeReads))
    return false;

  // The operands need to be loop invariant.
  if (!hasLoopInvariantOperands(Inst, Loop)) {
    DEBUG(llvm::dbgs() << "   loop variant operands\n");
    return false;
  }

  return true;
}

static bool hoistInstructions(SILLoop *Loop, DominanceInfo *DT,
                              ReadSet &SafeReads, bool RunsOnHighLevelSil) {
  auto Preheader = Loop->getLoopPreheader();
  if (!Preheader)
    return false;

  DEBUG(llvm::dbgs() << " Hoisting instructions.\n");

  auto HeaderBB = Loop->getHeader();
  bool Changed = false;

  // Traverse the dominator tree starting at the loop header. Hoisting
  // instructions as we go.
  auto DTRoot = DT->getNode(HeaderBB);
  SmallVector<SILBasicBlock *, 8> ExitingBBs;
  Loop->getExitingBlocks(ExitingBBs);
  for (llvm::df_iterator<DominanceInfoNode *> It = llvm::df_begin(DTRoot),
                                              E = llvm::df_end(DTRoot);
       It != E;) {
    auto *CurBB = It->getBlock();

    // Don't decent into control-dependent code. Only traverse into basic blocks
    // that dominate all exits.
    if (!std::all_of(ExitingBBs.begin(), ExitingBBs.end(),
                     [=](SILBasicBlock *ExitBB) {
          if (DT->dominates(CurBB, ExitBB))
            return true;
          return false;
        })) {
      DEBUG(llvm::dbgs() << "  skipping conditional block " << *CurBB << "\n");
      It.skipChildren();
      continue;
    }

    // We now that the block is guaranteed to be executed. Hoist if we can.
    for (auto InstIt = CurBB->begin(), E = CurBB->end(); InstIt != E; ) {
      SILInstruction *Inst = &*InstIt;
      ++InstIt;
      DEBUG(llvm::dbgs() << "  looking at " << *Inst);
      if (canHoistInstruction(Inst, Loop, SafeReads)) {
        DEBUG(llvm::dbgs() << "   hoisting to preheader.\n");
        Changed = true;
        Inst->moveBefore(Preheader->getTerminator());
      } else if (RunsOnHighLevelSil) {
        ArraySemanticsCall semCall(Inst);
        switch (semCall.getKind()) {
        case ArrayCallKind::kGetCount:
        case ArrayCallKind::kGetCapacity:
          if (hasLoopInvariantOperands(Inst, Loop) &&
              semCall.canHoist(Preheader->getTerminator(), DT)) {
            Changed = true;
            semCall.hoist(Preheader->getTerminator(), DT);
          }
          break;
        default:
          break;
        }
      }
    }

    // Next block in dominator tree.
    ++It;
  }
  return Changed;
}

static bool sinkFixLifetime(SILLoop *Loop, DominanceInfo *DomTree,
                            SILLoopInfo *LI) {
  DEBUG(llvm::errs() << " Sink fix_lifetime attempt\n");
  auto Preheader = Loop->getLoopPreheader();
  if (!Preheader)
    return false;

  // Only handle innermost loops for now.
  if (!Loop->getSubLoops().empty())
    return false;

  // Only handle single exit blocks for now.
  auto *ExitBB = Loop->getExitBlock();
  if (!ExitBB)
    return false;
  auto *ExitingBB = Loop->getExitingBlock();
  if (!ExitingBB)
    return false;

  // We can sink fix_lifetime instructions if there are no reference counting
  // instructions in the loop.
  SmallVector<FixLifetimeInst *, 16> FixLifetimeInsts;
  for (auto *BB : Loop->getBlocks()) {
    for (auto &Inst : *BB) {
      if (auto FLI = dyn_cast<FixLifetimeInst>(&Inst)) {
        FixLifetimeInsts.push_back(FLI);
      } else if (Inst.mayHaveSideEffects() && !isa<LoadInst>(&Inst) &&
                 !isa<StoreInst>(&Inst)) {
        DEBUG(llvm::errs() << "  mayhavesideeffects because of" << Inst);
        DEBUG(Inst.getParent()->dump());
        return false;
      }
    }
  }

  // Sink the fix_lifetime instruction.
  bool Changed = false;
  for (auto *FLI : FixLifetimeInsts)
    if (DomTree->dominates(FLI->getOperand()->getParentBlock(),
                           Preheader)) {
      auto Succs = ExitingBB->getSuccessors();
      for (unsigned EdgeIdx = 0; EdgeIdx <  Succs.size(); ++EdgeIdx) {
        SILBasicBlock *BB = Succs[EdgeIdx];
        if (BB == ExitBB) {
          auto *SplitBB = splitCriticalEdge(ExitingBB->getTerminator(), EdgeIdx,
                                            DomTree, LI);
          auto *OutsideBB = SplitBB ? SplitBB : ExitBB;
          // Update the ExitBB.
          ExitBB = OutsideBB;
          DEBUG(llvm::errs() << "  moving fix_lifetime to exit BB " << *FLI);
          FLI->moveBefore(&*OutsideBB->begin());
          Changed = true;
        }
      }
    } else {
      DEBUG(llvm::errs() << "  does not dominate " << *FLI);
    }

  return Changed;
}

namespace {
/// \brief Summary of may writes occurring in the loop tree rooted at \p
/// Loop. This includes all writes of the sub loops and the loop itself.
struct LoopNestSummary {
  SILLoop *Loop;
  WriteSet MayWrites;

  LoopNestSummary(SILLoop *Curr) : Loop(Curr) {}

  void copySummary(LoopNestSummary &Other) {
    MayWrites.append(Other.MayWrites.begin(), Other.MayWrites.end());
  }

  LoopNestSummary(const LoopNestSummary &) = delete;
  LoopNestSummary &operator=(const LoopNestSummary &) = delete;
  LoopNestSummary(LoopNestSummary &&) = delete;
};

/// \brief Optimize the loop tree bottom up propagating loop's summaries up the
/// loop tree.
class LoopTreeOptimization {
  llvm::DenseMap<SILLoop *, std::unique_ptr<LoopNestSummary>>
      LoopNestSummaryMap;
  SmallVector<SILLoop *, 8> BotUpWorkList;
  SILLoopInfo *LoopInfo;
  AliasAnalysis *AA;
  SideEffectAnalysis *SEA;
  DominanceInfo *DomTree;
  bool Changed;

  /// True if LICM is done on high-level SIL, i.e. semantic calls are not
  /// inlined yet. In this case some semantic calls can be hoisted.
  bool RunsOnHighLevelSil;

public:
  LoopTreeOptimization(SILLoop *TopLevelLoop, SILLoopInfo *LI,
                       AliasAnalysis *AA, SideEffectAnalysis *SEA,
                       DominanceInfo *DT,
                       bool RunsOnHighLevelSil)
      : LoopInfo(LI), AA(AA), SEA(SEA), DomTree(DT), Changed(false),
        RunsOnHighLevelSil(RunsOnHighLevelSil) {
    // Collect loops for a recursive bottom-up traversal in the loop tree.
    BotUpWorkList.push_back(TopLevelLoop);
    for (unsigned i = 0; i < BotUpWorkList.size(); ++i) {
      auto *L = BotUpWorkList[i];
      for (auto *SubLoop : *L)
        BotUpWorkList.push_back(SubLoop);
    }
  }

  /// \brief Optimize this loop tree.
  bool optimize();

protected:
  /// \brief Propagate the sub-loops' summaries up to the current loop.
  void propagateSummaries(std::unique_ptr<LoopNestSummary> &CurrSummary);

  /// \brief Collect a set of reads that can be hoisted to the loop's preheader.
  void analyzeCurrentLoop(std::unique_ptr<LoopNestSummary> &CurrSummary,
                          ReadSet &SafeReads);

  /// \brief Optimize the current loop nest.
  void optimizeLoop(SILLoop *CurrentLoop, ReadSet &SafeReads);
};
} // end anonymous namespace

bool LoopTreeOptimization::optimize() {
  // Process loops bottom up in the loop tree.
  while (!BotUpWorkList.empty()) {
    SILLoop *CurrentLoop = BotUpWorkList.pop_back_val();
    DEBUG(llvm::dbgs() << "Processing loop " << *CurrentLoop);

    // Collect all summary of all sub loops of the current loop. Since we
    // process the loop tree bottom up they are guaranteed to be available in
    // the map.
    auto CurrLoopSummary = llvm::make_unique<LoopNestSummary>(CurrentLoop);
    propagateSummaries(CurrLoopSummary);

    // Analyze the current loop for reads that can be hoisted.
    ReadSet SafeReads;
    analyzeCurrentLoop(CurrLoopSummary, SafeReads);

    optimizeLoop(CurrentLoop, SafeReads);

    // Store the summary for parent loops to use.
    LoopNestSummaryMap[CurrentLoop] = std::move(CurrLoopSummary);
  }
  return Changed;
}

void LoopTreeOptimization::propagateSummaries(
    std::unique_ptr<LoopNestSummary> &CurrSummary) {
  for (auto *SubLoop : *CurrSummary->Loop) {
    assert(LoopNestSummaryMap.count(SubLoop) && "Must have data for sub loops");
    CurrSummary->copySummary(*LoopNestSummaryMap[SubLoop]);
    LoopNestSummaryMap.erase(SubLoop);
  }
}

void LoopTreeOptimization::analyzeCurrentLoop(
    std::unique_ptr<LoopNestSummary> &CurrSummary, ReadSet &SafeReads) {
  WriteSet &MayWrites = CurrSummary->MayWrites;
  SILLoop *Loop = CurrSummary->Loop;
  DEBUG(llvm::dbgs() << " Analyzing accesses.\n");

  // Contains function calls in the loop, which only read from memory.
  SmallVector<ApplyInst *, 8> ReadOnlyApplies;

  for (auto *BB : Loop->getBlocks()) {
    for (auto &Inst : *BB) {
      // Ignore fix_lifetime instructions.
      if (isa<FixLifetimeInst>(&Inst))
        continue;

      // Collect loads.
      auto LI = dyn_cast<LoadInst>(&Inst);
      if (LI) {
        if (!mayWriteTo(AA, MayWrites, LI))
          SafeReads.insert(LI);
        continue;
      }
      if (auto *AI = dyn_cast<ApplyInst>(&Inst)) {
        // In contrast to load instructions, we first collect all read-only
        // function calls and add them later to SafeReads.
        SideEffectAnalysis::FunctionEffects E;
        SEA->getEffects(E, AI);

        auto MB = E.getMemBehavior(RetainObserveKind::ObserveRetains);
        if (MB <= SILInstruction::MemoryBehavior::MayRead)
          ReadOnlyApplies.push_back(AI);
      }
      if (Inst.mayHaveSideEffects()) {
        MayWrites.push_back(&Inst);
        // Remove clobbered loads we have seen before.
        removeWrittenTo(AA, SafeReads, &Inst);
      }
    }
  }
  for (auto *AI : ReadOnlyApplies) {
    if (!mayWriteTo(AA, SEA, MayWrites, AI))
      SafeReads.insert(AI);
  }
}

void LoopTreeOptimization::optimizeLoop(SILLoop *CurrentLoop,
                                        ReadSet &SafeReads) {
  Changed |= sinkCondFail(CurrentLoop);
  Changed |= hoistInstructions(CurrentLoop, DomTree, SafeReads,
                               RunsOnHighLevelSil);
  Changed |= sinkFixLifetime(CurrentLoop, DomTree, LoopInfo);
}

namespace {
/// Hoist loop invariant code out of innermost loops.
class LICM : public SILFunctionTransform {

public:
  LICM(bool RunsOnHighLevelSil) : RunsOnHighLevelSil(RunsOnHighLevelSil) {}

  /// True if LICM is done on high-level SIL, i.e. semantic calls are not
  /// inlined yet. In this case some semantic calls can be hoisted.
  /// We only hoist semantic calls on high-level SIL because we can be sure that
  /// e.g. an Array as SILValue is really immutable (including its content).
  bool RunsOnHighLevelSil;

  StringRef getName() override {
    return RunsOnHighLevelSil ? "High-level Loop Invariant Code Motion" :
                                "Loop Invariant Code Motion";
  }

  void run() override {
    SILFunction *F = getFunction();
    SILLoopAnalysis *LA = PM->getAnalysis<SILLoopAnalysis>();
    SILLoopInfo *LoopInfo = LA->get(F);

    if (LoopInfo->empty()) {
      DEBUG(llvm::dbgs() << "No loops in " << F->getName() << "\n");
      return;
    }

    DominanceAnalysis *DA = PM->getAnalysis<DominanceAnalysis>();
    AliasAnalysis *AA = PM->getAnalysis<AliasAnalysis>();
    SideEffectAnalysis *SEA = PM->getAnalysis<SideEffectAnalysis>();
    DominanceInfo *DomTree = nullptr;

    DEBUG(llvm::dbgs() << "Processing loops in " << F->getName() << "\n");
    bool Changed = false;

    for (auto *TopLevelLoop : *LoopInfo) {
      if (!DomTree) DomTree = DA->get(F);
      LoopTreeOptimization Opt(TopLevelLoop, LoopInfo, AA, SEA, DomTree,
                               RunsOnHighLevelSil);
      Changed |= Opt.optimize();
    }

    if (Changed) {
      LA->lockInvalidation();
      DA->lockInvalidation();
      PM->invalidateAnalysis(F, SILAnalysis::InvalidationKind::FunctionBody);
      LA->unlockInvalidation();
      DA->unlockInvalidation();
    }
  }
};
} // end anonymous namespace

SILTransform *swift::createLICM() {
  return new LICM(false);
}

SILTransform *swift::createHighLevelLICM() {
  return new LICM(true);
}


text:
import { Component, OnInit } from '@angular/core';
import { MdDialogRef } from '@angular/material';

@Component({
  selector: 'app-edit-card-dialogbox',
  templateUrl: './edit-card-dialogbox.component.html',
  styleUrls: ['./edit-card-dialogbox.component.css']
})
export class EditCardDialogboxComponent implements OnInit {
  public oldContent: string;
  constructor(public dialogRef: MdDialogRef<EditCardDialogboxComponent>) { }

  public ngOnInit() {
    //
  }

}

redpajama_set_name: RedPajamaGithub


text:
import { Component, PropTypes, Children } from 'react';
import { MapControl } from 'react-leaflet';
import { Map } from 'leaflet';
import Dumb from './Control.Dumb';
import { render } from 'react-dom';

export default class Control extends MapControl {
  static propTypes = {
    children: PropTypes.node,
    map: PropTypes.instanceOf(Map),
    popupContainer: PropTypes.object,
    position: PropTypes.string
  };

  constructor(props){
    super(props);
  }

  componentWillMount() {
    const { children: _children, map: _map, popupContainer, ...props } = this.props;

    this.leafletElement = new Dumb(props);
  }
 componentDidMount(){
    super.componentDidMount();
    this.renderContent();
  }

  componentDidUpdate(next) {
    super.componentDidUpdate(next);
    this.renderContent();
  }

  renderContent() {
    const container = this.leafletElement.getContainer();
    render(
      Children.only(this.props.children),
      container
    );
  }

  render() {
    return null;
  }

}


text:
namespace WisejWeb.TestBoundControls
{
    partial class MainForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region WisejWeb Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.syncedListsButton = new Wisej.Web.Button();
            this.treeListViewButton = new Wisej.Web.Button();
            this.autoTreeViewButton = new Wisej.Web.Button();
            this.stripWindowButton = new Wisej.Web.Button();
            this.workPanel = new Wisej.Web.Panel();
            this.menuBar1 = new Wisej.Web.MenuBar();
            this.SuspendLayout();
            //
            // syncedListsButton
            //
            this.syncedListsButton.Location = new System.Drawing.Point(13, 13);
            this.syncedListsButton.Name = "syncedListsButton";
            this.syncedListsButton.Size = new System.Drawing.Size(100, 23);
            this.syncedListsButton.TabIndex = 0;
            this.syncedListsButton.Text = "Synced Lists";
            this.syncedListsButton.Click += new System.EventHandler(this.syncedListsButton_Click);
            //
            // treeListViewButton
            //
            this.treeListViewButton.Location = new System.Drawing.Point(139, 13);
            this.treeListViewButton.Name = "treeListViewButton";
            this.treeListViewButton.Size = new System.Drawing.Size(100, 23);
            this.treeListViewButton.TabIndex = 1;
            this.treeListViewButton.Text = "TreeListView";
            this.treeListViewButton.Click += new System.EventHandler(this.treeListViewButton_Click);
            //
            // autoTreeViewButton
            //
            this.autoTreeViewButton.Location = new System.Drawing.Point(265, 13);
            this.autoTreeViewButton.Name = "autoTreeViewButton";
            this.autoTreeViewButton.Size = new System.Drawing.Size(100, 23);
            this.autoTreeViewButton.TabIndex = 2;
            this.autoTreeViewButton.Text = "TreeView";
            this.autoTreeViewButton.Click += new System.EventHandler(this.autoTreeViewButton_Click);
            //
            // stripWindowButton
            //
            this.stripWindowButton.Location = new System.Drawing.Point(391, 12);
            this.stripWindowButton.Name = "stripWindowButton";
            this.stripWindowButton.Size = new System.Drawing.Size(100, 23);
            this.stripWindowButton.TabIndex = 3;
            this.stripWindowButton.Text = "Strip Window";
            this.stripWindowButton.Click += new System.EventHandler(this.stripWindowButton_Click);
            //
            // workPanel
            //
            this.workPanel.Anchor = ((Wisej.Web.AnchorStyles)((((Wisej.Web.AnchorStyles.Top | Wisej.Web.AnchorStyles.Bottom)
            | Wisej.Web.AnchorStyles.Left)
            | Wisej.Web.AnchorStyles.Right)));
            //this.workPanel.Dock = Wisej.Web.DockStyle.Fill;
            this.workPanel.Location = new System.Drawing.Point(0, 49);
            this.workPanel.Name = "workPanel";
            this.workPanel.Size = new System.Drawing.Size(1003, 438);
            this.workPanel.TabIndex = 4;
            //
            // menuBar1
            //
            this.menuBar1.Location = new System.Drawing.Point(0, 0);
            this.menuBar1.Name = "menuBar1";
            this.menuBar1.Size = new System.Drawing.Size(1003, 22);
            this.menuBar1.TabIndex = 5;
            this.menuBar1.TabStop = false;
            //
            // MainForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 14F);
            this.AutoScaleMode = Wisej.Web.AutoScaleMode.Font;
            this.AutoSize = true;
            this.ClientSize = new System.Drawing.Size(1003, 522);
            this.Controls.Add(this.stripWindowButton);
            this.Controls.Add(this.autoTreeViewButton);
            this.Controls.Add(this.treeListViewButton);
            this.Controls.Add(this.syncedListsButton);
            this.Controls.Add(this.workPanel);
            this.Controls.Add(this.menuBar1);
            this.Name = "MainForm";
            this.Text = "Main Form";
            this.Load += new System.EventHandler(this.MainForm_Load);
            this.ResumeLayout(false);

        }

        #endregion

        private Wisej.Web.Button syncedListsButton;
        private Wisej.Web.Button treeListViewButton;
        private Wisej.Web.Button autoTreeViewButton;
        private Wisej.Web.Button stripWindowButton;
        private Wisej.Web.Panel workPanel;
        private Wisej.Web.MenuBar menuBar1;
    }
}


text:
package com.netflix.aegisthus.output;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.netflix.Aegisthus;
import com.netflix.aegisthus.io.writable.AegisthusKeySortingComparator;
import com.netflix.aegisthus.io.writable.RowWritable;
import org.apache.cassandra.db.Column;
import org.apache.cassandra.db.CounterColumn;
import org.apache.cassandra.db.DeletedColumn;
import org.apache.cassandra.db.ExpiringColumn;
import org.apache.cassandra.db.OnDiskAtom;
import org.apache.cassandra.db.RangeTombstone;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.BytesType;
import org.apache.cassandra.db.marshal.TypeParser;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.exceptions.SyntaxException;
import org.apache.cassandra.serializers.MarshalException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.TaskID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.NumberFormat;
import java.util.Collections;
import java.util.List;

public class JsonOutputFormat extends CustomFileNameFileOutputFormat<BytesWritable, RowWritable> {
    private static final Logger LOG = LoggerFactory.getLogger(JsonOutputFormat.class);
    private static final NumberFormat NUMBER_FORMAT = NumberFormat.getInstance();

    static {
        NUMBER_FORMAT.setMinimumIntegerDigits(5);
        NUMBER_FORMAT.setGroupingUsed(false);
    }

    @SuppressWarnings("unchecked")
    private AbstractType<ByteBuffer> getConverter(Configuration conf, String key) {
        String converterType = conf.get(key);
        if (Strings.isNullOrEmpty(key)) {
            return BytesType.instance;
        }

        try {
            return (AbstractType<ByteBuffer>) TypeParser.parse(converterType);
        } catch (SyntaxException | ConfigurationException e) {
            throw Throwables.propagate(e);
        }
    }

    @Override
    public synchronized String getCustomFileName(TaskAttemptContext context, String name, String extension) {
        TaskID taskId = context.getTaskAttemptID().getTaskID();
        int partition = taskId.getId();
        return "aeg-" + NUMBER_FORMAT.format(partition) + extension;
    }

    @Override
    public RecordWriter<BytesWritable, RowWritable> getRecordWriter(final TaskAttemptContext context)
            throws IOException {
        // No extension on the aeg json format files for historical reasons
        Path workFile = getDefaultWorkFile(context, "");
        Configuration conf = context.getConfiguration();
        FileSystem fs = workFile.getFileSystem(conf);
        final long maxColSize = conf.getLong(Aegisthus.Feature.CONF_MAXCOLSIZE, -1);
        final FSDataOutputStream outputStream = fs.create(workFile, false);
        final JsonFactory jsonFactory = new JsonFactory();
        final AbstractType<ByteBuffer> keyNameConverter = getConverter(conf, Aegisthus.Feature.CONF_KEYTYPE);
        final AbstractType<ByteBuffer> columnNameConverter = getConverter(conf, Aegisthus.Feature.CONF_COLUMNTYPE);
        final AbstractType<ByteBuffer> columnValueConverter = getConverter(
                conf,
                Aegisthus.Feature.CONF_COLUMN_VALUE_TYPE
        );
        final boolean legacyColumnNameFormatting =
                conf.getBoolean(Aegisthus.Feature.CONF_LEGACY_COLUMN_NAME_FORMATTING, false);

        return new RecordWriter<BytesWritable, RowWritable>() {
            private int errorLogCount = 0;

            private String getString(AbstractType<ByteBuffer> converter, ByteBuffer buffer) {
                try {
                    return converter.getString(buffer);
                } catch (MarshalException e) {
                    if (errorLogCount < 100) {
                        LOG.error("Unable to use converter '{}'", converter, e);
                        errorLogCount++;
                    }
                    return BytesType.instance.getString(buffer);
                }
            }

            private String getString(AbstractType<ByteBuffer> converter, byte[] bytes) {
                return getString(converter, ByteBuffer.wrap(bytes));
            }

            @Override
            public void write(BytesWritable key, RowWritable rowWritable) throws IOException, InterruptedException {
                JsonGenerator jsonGenerator = jsonFactory.createGenerator(outputStream);
                jsonGenerator.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);

                String keyName = getString(keyNameConverter, key.getBytes());
                outputStream.writeBytes(keyName);
                outputStream.writeByte('\t');

                jsonGenerator.writeStartObject();
                jsonGenerator.writeObjectFieldStart(keyName);
                jsonGenerator.writeNumberField("deletedAt", rowWritable.getDeletedAt());
                jsonGenerator.writeArrayFieldStart("columns");

                List<OnDiskAtom> columns = rowWritable.getColumns();
                if (maxColSize != -1) {
                    long columnSize = 0;
                    for (OnDiskAtom atom : columns) {
                        columnSize += atom.serializedSizeForSSTable();
                    }

                    // If the column size exceeds the maximum, write out the error message and replace columns with an
                    // empty list so they will not be output
                    if (columnSize > maxColSize) {
                        jsonGenerator.writeString("error");
                        jsonGenerator.writeString(
                                String.format("row too large: %,d bytes - limit %,d bytes", columnSize, maxColSize)
                        );
                        jsonGenerator.writeNumber(0);

                        columns = Collections.emptyList();

                        context.getCounter("aegisthus", "rowsTooBig").increment(1L);
                    }
                }

                for (OnDiskAtom atom : columns) {
                    if (atom instanceof Column) {
                        jsonGenerator.writeStartArray();
                        String columnName = getString(columnNameConverter, atom.name());
                        if (legacyColumnNameFormatting) {
                            columnName = AegisthusKeySortingComparator.legacyColumnNameFormat(columnName);
                        }
                        jsonGenerator.writeString(columnName);
                        jsonGenerator.writeString(getString(columnValueConverter, ((Column) atom).value()));
                        jsonGenerator.writeNumber(((Column) atom).timestamp());

                        if (atom instanceof DeletedColumn) {
                            jsonGenerator.writeString("d");
                        } else if (atom instanceof ExpiringColumn) {
                            jsonGenerator.writeString("e");
                            jsonGenerator.writeNumber(((ExpiringColumn) atom).getTimeToLive());
                            jsonGenerator.writeNumber(atom.getLocalDeletionTime());
                        } else if (atom instanceof CounterColumn) {
                            jsonGenerator.writeString("c");
                            jsonGenerator.writeNumber(((CounterColumn) atom).timestampOfLastDelete());
                        }
                        jsonGenerator.writeEndArray();
                    } else if (atom instanceof RangeTombstone) {
                        LOG.debug("Range Tombstones are not output in the json format");
                    } else {
                        throw new IllegalStateException("Unknown atom type for atom: " + atom);
                    }
                }
                jsonGenerator.writeEndArray();
                jsonGenerator.writeEndObject(); // End key object
                jsonGenerator.writeEndObject(); // Outer json
                jsonGenerator.close();

                outputStream.writeByte('\n');
            }

            @Override
            public void close(TaskAttemptContext context) throws IOException, InterruptedException {
                outputStream.close();
            }
        };
    }
}


text:
/**
 * i18n.js
 *
 * This will setup the i18n language files and locale data for your plugin.
 *
 */

import { addLocaleData } from 'react-intl';
import { reduce } from 'lodash';

// Import config
import { languages } from './config/languages.json';

/**
 * Try to require translation file.
 *
 * @param language {String}
 */
const requireTranslations = language => {
  try {
    return require(`./translations/${language}.json`); // eslint-disable-line global-require
  } catch (error) {
    console.error(`Unable to load "${language}" translation. Please make sure "${language}.json" file exists in "admin/public/app/translations" folder.`); // eslint-disable-line no-console
    return false;
  }
};

/**
 * Try to require the language in `react-intl` locale data
 * and add locale data if it has been found.
 *
 * @param language {String}
 */
const addLanguageLocaleData = language => {
  try {
    const localeData = require(`react-intl/locale-data/${language}`); // eslint-disable-line global-require
    addLocaleData(localeData);
    return true;
  } catch (error) {
    console.warn(`⚠ It looks like the language "${language}" is not supported by "react-intl" module.`); // eslint-disable-line no-console
    return false;
  }
};

/**
 * Dynamically generate `translationsMessages object`.
 */
const translationMessages = reduce(languages, (result, language) => {
  const obj = result;
  obj[language] = requireTranslations(language);
  addLanguageLocaleData(language);
  return obj;
}, {});

export {
  languages,
  translationMessages,
};


text:
package it.conteit.scoresmanager.gui.registry;

import it.conteit.scoresmanager.data.IDay;
import it.conteit.scoresmanager.data.IScore;

public interface IRegistryListener {
	public void daySelected(IDay d);
	public void scoreSelected(IScore s, IDay d);
}


text:
function widget:GetInfo()
    return {
        name      = "Hides the default interface",
        desc      = "",
        author    = "gajop",
        license   = "MIT",
        layer     = 1001,
        enabled   = true,
    }
end

local gameMode
local function SetGameMode(gameMode)
    if gameMode == "play" then
        --Spring.SendCommands("Console 0")
    else
        --Spring.SendCommands("Console 1")
    end
end

function widget:Initialize()
    if not Game.gameName:find("SpringBoard Core") then
        widgetHandler:RemoveWidget(self)
    end
    gameMode = Spring.GetGameRulesParam("gameMode")
    SetGameMode(gameMode)

    -- remove Springs default UI stuff
    Spring.SendCommands("ResBar 0", "ToolTip 0", "Clock 0", "Info 0")
    Spring.SendCommands("showhealthbars 0")
    gl.SlaveMiniMap(true)
    gl.ConfigMiniMap(-1,-1,-1,-1)
end

-- sets status to ready & hide pre-game UI
function widget:GameSetup()
    return true, true
end

function widget:Update()
    local newGameMode = Spring.GetGameRulesParam("gameMode")
    if gameMode ~= newGameMode then
        gameMode = newGameMode
        SetGameMode(gameMode)
    end
end


text:
var onRun = function(context) {
  log('Select all exportable in current page.');

  var doc = context.document
  // Unselect everything
  doc.currentPage().deselectAllLayers()

  var exportables = doc.currentPage().exportableLayers()
  for (var i = 0; i < exportables.length; i++) {
    var exportable = exportables.objectAtIndex(i)
    log("  " + exportable.name())
    exportable.select_byExpandingSelection(true, true)
  }
};


text:
static_assert( std::is_trivial<std::byte>::value, "" );   // P0767
#else
static_assert( std::is_pod<std::byte>::value, "" );
#endif
static_assert(!std::is_arithmetic<std::byte>::value, "" );
static_assert(!std::is_integral<std::byte>::value, "" );

static_assert(!std::is_same<std::byte,          char>::value, "" );
static_assert(!std::is_same<std::byte,   signed char>::value, "" );
static_assert(!std::is_same<std::byte, unsigned char>::value, "" );

// The standard doesn't outright say this, but it's pretty clear that it has to be true.
static_assert(sizeof(std::byte) == 1, "" );

int main () {}


text:
import os, json, unittest, time, shutil, sys, socket
import h2o
import h2o_browse as h2b, h2o_rf as h2f, h2o_exec, h2o_gbm, h2o_util

def parseS3File(node=None, bucket=None, filename=None, keyForParseResult=None,
    timeoutSecs=20, retryDelaySecs=2, pollTimeoutSecs=30, **kwargs):
    ''' Parse a file stored in S3 bucket'''
    if not bucket  : raise Exception('No S3 bucket')
    if not filename: raise Exception('No filename in bucket')
    if not node: node = h2o.nodes[0]

    import_result = node.import_s3(bucket)
    s3_key = [f['key'] for f in import_result['succeeded'] if f['file'] == filename ][0]

    if keyForParseResult is None:
        myKeyForParseResult = s3_key + '.hex'
    else:
        myKeyForParseResult = keyForParseResult
    p = node.parse(s3_key, myKeyForParseResult,
        timeoutSecs, retryDelaySecs,
        pollTimeoutSecs=pollTimeoutSecs, **kwargs)

    # do SummaryPage here too, just to get some coverage
    node.summary_page(myKeyForParseResult)
    return p

# normally we don't want inspect to print during verboseprint. verbose=True to get it
# in specific tests
def runInspect(node=None, key=None, timeoutSecs=30, verbose=False, **kwargs):
    if not key: raise Exception('No key for Inspect')
    if not node: node = h2o.nodes[0]
    a = node.inspect(key, timeoutSecs=timeoutSecs, **kwargs)
    if verbose:
        print "inspect of %s:" % key, h2o.dump_json(a)
    return a

def runSummary(node=None, key=None, timeoutSecs=30, **kwargs):
    if not key: raise Exception('No key for Summary')
    if not node: node = h2o.nodes[0]
    return node.summary_page(key, timeoutSecs=timeoutSecs, **kwargs)

# Not working in H2O yet, but support the test
def runStore2HDFS(node=None, key=None, timeoutSecs=5, **kwargs):
    if not key: raise Exception('No key for Inspect')
    if not node: node = h2o.nodes[0]
    # FIX! currently there is no such thing as a timeout on node.inspect
    return node.Store2HDFS(key, **kwargs)

# since we'll be doing lots of execs on a parsed file, not useful to have parse+exec
# retryDelaySecs isn't used,
def runExec(node=None, timeoutSecs=20, **kwargs):
    if not node: node = h2o.nodes[0]
    # no such thing as GLMView..don't use retryDelaySecs
    a = node.exec_query(timeoutSecs, **kwargs)
    # temporary?
    if h2o.beta_features:
        h2o.check_sandbox_for_errors()
    return a

def runKMeans(node=None, parseResult=None, timeoutSecs=20, retryDelaySecs=2, **kwargs):
    if not parseResult: raise Exception('No parseResult for KMeans')
    if not node: node = h2o.nodes[0]
    return node.kmeans(parseResult['destination_key'], None, timeoutSecs, retryDelaySecs, **kwargs)

def runGLM(node=None, parseResult=None, timeoutSecs=20, retryDelaySecs=2, **kwargs):
    if not parseResult: raise Exception('No parseResult for GLM')
    if not node: node = h2o.nodes[0]
    return node.GLM(parseResult['destination_key'],
        timeoutSecs, retryDelaySecs, **kwargs)

def runGLMScore(node=None, key=None, model_key=None, timeoutSecs=20, **kwargs):
    if not node: node = h2o.nodes[0]
    return node.GLMScore(key, model_key, timeoutSecs, **kwargs)

def runGLMGrid(node=None, parseResult=None, timeoutSecs=60, retryDelaySecs=2, **kwargs):
    if not parseResult: raise Exception('No parseResult for GLMGrid')
    if not node: node = h2o.nodes[0]
    # no such thing as GLMGridView..don't use retryDelaySecs
    return node.GLMGrid(parseResult['destination_key'], timeoutSecs, **kwargs)

def runPCA(node=None, parseResult=None, timeoutSecs=600, **kwargs):
    if not parseResult: raise Exception('No parseResult for PCA')
    if not node: node = h2o.nodes[0]
    data_key = parseResult['destination_key']
    return node.pca(data_key=data_key, timeoutSecs=timeoutSecs, **kwargs)

def runNNetScore(node=None, key=None, model=None, timeoutSecs=600, **kwargs):
    if not node: node = h2o.nodes[0]
    return node.neural_net_score(key, model, timeoutSecs=timeoutSecs, **kwargs)

def runNNet(node=None, parseResult=None, timeoutSecs=600, **kwargs):
    if not parseResult: raise Exception('No parseResult for Neural Net')
    if not node: node = h2o.nodes[0]
    data_key = parseResult['destination_key']
    return node.neural_net(data_key=data_key, timeoutSecs=timeoutSecs, **kwargs)

def runDeepLearning(node=None, parseResult=None, timeoutSecs=600, **kwargs):
    if not parseResult: raise Exception('No parseResult for Deep Learning')
    if not node: node = h2o.nodes[0]
    data_key = parseResult['destination_key']
    return node.deep_learning(data_key=data_key, timeoutSecs=timeoutSecs, **kwargs)

def runGBM(node=None, parseResult=None, timeoutSecs=500, **kwargs):
    if not parseResult: raise Exception('No parseResult for GBM')
    if not node: node = h2o.nodes[0]
    data_key = parseResult['destination_key']
    return node.gbm(data_key=data_key, timeoutSecs=timeoutSecs, **kwargs)

def runPredict(node=None, data_key=None, model_key=None, timeoutSecs=500, **kwargs):
    if not data_key: raise Exception('No data_key for run Predict')
    if not node: node = h2o.nodes[0]
    return node.generate_predictions(data_key, model_key, timeoutSecs=timeoutSecs,**kwargs)

def runSpeeDRF(node=None, parseResult=None, ntrees=5, max_depth=10, timeoutSecs=20, **kwargs):
    if not parseResult: raise Exception("No parseResult for SpeeDRF")
    if not node: node = h2o.nodes[0]
    Key = parseResult['destination_key']
    return node.speedrf(Key, ntrees=ntrees, max_depth=max_depth, timeoutSecs=timeoutSecs, **kwargs)

# rfView can be used to skip the rf completion view
# for creating multiple rf jobs
def runRF(node=None, parseResult=None, trees=5, timeoutSecs=20, **kwargs):
    if not parseResult: raise Exception('No parseResult for RF')
    if not node: node = h2o.nodes[0]
    Key = parseResult['destination_key']
    return node.random_forest(Key, trees, timeoutSecs, **kwargs)

def runRFTreeView(node=None, n=None, data_key=None, model_key=None, timeoutSecs=20, **kwargs):
    if not node: node = h2o.nodes[0]
    return node.random_forest_treeview(n, data_key, model_key, timeoutSecs, **kwargs)

def runGBMView(node=None, model_key=None, timeoutSecs=300, retryDelaySecs=2, **kwargs):
    if not node: node = h2o.nodes[0]
    if not model_key:
        raise Exception("\nNo model_key was supplied to the gbm view!")
    gbmView = node.gbm_view(model_key, timeoutSecs=timeoutSecs)
    return gbmView

def runNeuralView(node=None, model_key=None, timeoutSecs=300, retryDelaySecs=2, **kwargs):
    if not node: node = h2o.nodes[0]
    if not model_key:
        raise Exception("\nNo model_key was supplied to the neural view!")
    neuralView = node.neural_view(model_key, timeoutSecs=timeoutSecs, retryDelaysSecs=retryDelaysecs)
    return neuralView

def runPCAView(node=None, modelKey=None, timeoutSecs=300, retryDelaySecs=2, **kwargs):
    if not node: node = h2o.nodes[0]
    if not modelKey:
        raise Exception("\nNo modelKey was supplied to the pca view!")
    pcaView = node.pca_view(modelKey, timeoutSecs=timeoutSecs)
    return pcaView

def runGLMView(node=None, modelKey=None, timeoutSecs=300, retryDelaySecs=2, **kwargs):
    if not node: node = h2o.nodes[0]
    if not modelKey:
        raise Exception("\nNo modelKey was supplied to the glm view!")
    glmView = node.glm_view(modelKey,timeoutSecs=timeoutSecs, retryDelaySecs=retryDelaySecs)
    return glmView

def runRFView(node=None, data_key=None, model_key=None, ntree=None,
    timeoutSecs=15, retryDelaySecs=2, doSimpleCheck=True,
    noPrint=False, **kwargs):
    if not node: node = h2o.nodes[0]

    # kind of wasteful re-read, but maybe good for testing
    rfView = node.random_forest_view(data_key, model_key, ntree=ntree, timeoutSecs=timeoutSecs, **kwargs)
    if doSimpleCheck:
        h2f.simpleCheckRFView(node, rfView, noPrint=noPrint)
    return rfView

def runRFScore(node=None, data_key=None, model_key=None, ntree=None,
    timeoutSecs=15, retryDelaySecs=2, doSimpleCheck=True, **kwargs):
    if not node: node = h2o.nodes[0]

    # kind of wasteful re-read, but maybe good for testing
    rfView = node.random_forest_score(data_key, model_key, timeoutSecs, **kwargs)
    if doSimpleCheck:
        h2f.simpleCheckRFView(node, rfView, noPrint=noPrint)
    return rfView

def runStoreView(node=None, timeoutSecs=30, noPrint=None, **kwargs):
    if not node: node = h2o.nodes[0]
    storeView = node.store_view(timeoutSecs, **kwargs)
    if not noPrint:
        for s in storeView['keys']:
            print "StoreView: key:", s['key']
            if 'rows' in s:
                h2o.verboseprint("StoreView: rows:", s['rows'], "value_size_bytes:", s['value_size_bytes'])
    print node, 'storeView has', len(storeView['keys']), 'keys'
    return storeView

def port_live(ip, port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((ip,port))
        s.shutdown(2)
        return True
    except:
        return False

def wait_for_live_port(ip, port, retries=3):
    h2o.verboseprint("Waiting for {0}:{1} {2}times...".format(ip,port,retries))
    if not port_live(ip,port):
        count = 0
        while count < retries:
            if port_live(ip,port):
                count += 1
            else:
                count = 0
            time.sleep(1)
            dot()
    if not port_live(ip,port):
        raise Exception("[h2o_cmd] Error waiting for {0}:{1} {2}times...".format(ip,port,retries))

# checks the key distribution in the cloud, and prints warning if delta against avg
# is > expected
def checkKeyDistribution():
    c = h2o.nodes[0].get_cloud()
    nodes = c['nodes']
    print "Key distribution post parse, should be balanced"
    # get average
    totalKeys = 0
    for n in nodes:
        totalKeys += int(n['num_keys'])
    avgKeys = (totalKeys + 0.0)/len(nodes)
    # if more than 5% difference from average, print warning
    for n in nodes:
        print 'num_keys:', n['num_keys'], 'value_size_bytes:', n['value_size_bytes'],\
            'name:', n['name']
        delta = (abs(avgKeys - int(n['num_keys']))/avgKeys)
        if delta > 0.10:
            print "WARNING. avgKeys:", avgKeys, "and n['num_keys']:", n['num_keys'], "have >", "%.1f" % (100 * delta), "% delta"

# I use these in testdir_hosts/test_parse_nflx_loop_s3n_hdfs.py
# and testdir_multi_jvm/test_benchmark_import.py
# might be able to use more widely
def columnInfoFromInspect(key, exceptionOnMissingValues=True, **kwargs):
    inspect = runInspect(key=key, **kwargs)

    if h2o.beta_features:
        num_rows = inspect['numRows']
        num_cols = inspect['numCols']
        keyNA = 'naCnt'
    else:
        num_rows = inspect['num_rows']
        num_cols = inspect['num_cols']
        keyNA = 'num_missing_values'

    cols = inspect['cols']
    # type
    # key
    # row_size
    # value_size_bytes
    # cols
    # rows
    missingValuesDict = {}
    constantValuesDict = {}
    enumSizeDict = {}
    colNameDict = {}
    colTypeDict = {}
    # all dictionaries created are keyed by col index
    print "Column Summary:"
    for k,c in enumerate(cols):
        # offset
        # base
        # scale
        # mean
        # variance
        # enum_domain_size
        colNameDict[k] = c['name']
        colTypeDict[k] = c['type']
        msg = "%s %d" % (c['name'], k)
        msg += " type: %s" % c['type']
        printMsg = False

        if h2o.beta_features:
            if c['type'] == 'Enum':
                # enums now have 'NaN' returned for min/max

                # if isinstance(c['min'], basestring) or isinstance(c['max'], basestring):
                #     raise Exception("Didn't expect 'min': %s or 'max': %s to be str or unicode" % (c['min'], c['max']))
                cardinality = c['cardinality']
                msg += (" cardinality: %d" % cardinality)
                # inspect2 doesn't have cardinality but this is equivalent
                enumSizeDict[k] = cardinality
                printMsg = True

        else:
            if c['type'] == 'enum':
                msg += (" enum_domain_size: %d" % c['enum_domain_size'])
                enumSizeDict[k] = c['enum_domain_size']
                printMsg = True

        if c[keyNA] != 0:
            pct = ((c[keyNA] + 0.0)/ num_rows) * 100
            msg += (" %s: %s (%0.1f%s)" % (keyNA, c[keyNA], pct, '%'))
            missingValuesDict[k] = c[keyNA]
            printMsg = True

        if c['min']==c['max'] and (c['type']!='Enum' and c['type']!='enum'):
            msg += (" constant value (min=max): %s" % c['min'])
            constantValuesDict[k] = c['min']
            printMsg = True

        # if the naCnt = num_rows, that means it's likely forced NAs..so detect that
        if c[keyNA]==num_rows:
            msg += (" constant value (na count = num rows): %s" % c['min'])
            constantValuesDict[k] = c['min']
            printMsg = True

        if printMsg: # don't print ints or floats if ok
            print msg

    if missingValuesDict:
        m = [str(k) + ":" + str(v) for k,v in missingValuesDict.iteritems()]
        print len(missingValuesDict), "columns with missing values", ", ".join(m)
        ### raise Exception("Looks like columns got flipped to NAs: " + ", ".join(m))

    if constantValuesDict:
        m = [str(k) + ":" + str(v) for k,v in constantValuesDict.iteritems()]
        print len(constantValuesDict), "columns with constant values", ", ".join(m)

    print "\n" + key, \
        "    num_rows:", "{:,}".format(num_rows), \
        "    num_cols:", "{:,}".format(num_cols)

    if missingValuesDict and exceptionOnMissingValues:
        m = [str(k) + ":" + str(v) for k,v in missingValuesDict.iteritems()]
        raise Exception("Looks like columns got flipped to NAs: " + ", ".join(m))

    if num_cols != len(colNameDict):
        raise Exception("num_cols: %s doesn't agree with len(colNameDict): %s" % (num_cols, len(colNameDict)))

    return (missingValuesDict, constantValuesDict, enumSizeDict, colTypeDict, colNameDict)

def infoFromInspect(inspect, csvPathname):
    if not inspect:
        raise Exception("inspect is empty for infoFromInspect")

    # need more info about this dataset for debug
    cols = inspect['cols']
    # look for nonzero num_missing_values count in each col
    if h2o.beta_features:
        keyNA = 'naCnt'
    else:
        keyNA = 'num_missing_values'
    missingValuesList = []
    for i, colDict in enumerate(cols):
        num_missing_values = colDict[keyNA]
        if num_missing_values != 0:
            print "%s: col: %d, %s: %d" % (csvPathname, i, keyNA, num_missing_values)
            missingValuesList.append(num_missing_values)

    if h2o.beta_features:
        # no type per col in inspect2
        numCols = inspect['numCols']
        numRows = inspect['numRows']
        byteSize = inspect['byteSize']

        print "\n" + csvPathname, "numCols: %s, numRows: %s, byteSize: %s" % \
               (numCols, numRows, byteSize)

    else:
        num_cols = inspect['num_cols']
        num_rows = inspect['num_rows']
        row_size = inspect['row_size']
        ptype = inspect['type']
        value_size_bytes = inspect['value_size_bytes']
        response = inspect['response']
        ptime = response['time']

        print "\n" + csvPathname, "num_cols: %s, num_rows: %s, row_size: %s, ptype: %s, value_size_bytes: %s" % \
               (num_cols, num_rows, row_size, ptype, value_size_bytes)

    return missingValuesList

# summary doesn't have the # of rows
# we need it to see if na count = number of rows. min/max/mean/sigma/zeros then are ignored (undefined?)
# while we're at it, let's cross check numCols
# if we don't pass these extra params, just ignore
def infoFromSummary(summaryResult, noPrint=False, numCols=None, numRows=None):
    if not summaryResult:
        raise Exception("summaryResult is empty for infoFromSummary")
    if h2o.beta_features:
        # names = summaryResult['names']
        # means = summaryResult['means']
        summaries = summaryResult['summaries']

        # what if we didn't get the full # of cols in this summary view?
        # I guess the test should deal with that
        if 1==0 and numCols and (len(summaries)!=numCols):
            raise Exception("Expected numCols: %s cols in summary. Got %s" % (numCols, len(summaries)))

        for column in summaries:
            colname = column['colname']
            coltype = column['type']
            nacnt = column['nacnt']
            stats = column['stats']
            stattype = stats['type']
            h2o_exec.checkForBadFP(nacnt, 'nacnt for colname: %s stattype: %s' % (colname, stattype))

            if stattype == 'Enum':
                cardinality = stats['cardinality']
                h2o_exec.checkForBadFP(cardinality, 'cardinality for colname: %s stattype: %s' % (colname, stattype))

            else:
                mean = stats['mean']
                sd = stats['sd']
                zeros = stats['zeros']
                mins = stats['mins']
                maxs = stats['maxs']
                pct = stats['pct']
                pctile = stats['pctile']

                # check for NaN/Infinity in some of these
                # apparently we can get NaN in the mean for a numerica col with all NA?
                h2o_exec.checkForBadFP(mean, 'mean for colname: %s stattype: %s' % (colname, stattype), nanOkay=True, infOkay=True)
                h2o_exec.checkForBadFP(sd, 'sd for colname: %s stattype %s' % (colname, stattype), nanOkay=True, infOkay=True)
                h2o_exec.checkForBadFP(zeros, 'zeros for colname: %s stattype %s' % (colname, stattype))

                if numRows and (nacnt==numRows):
                    print "%s is all NAs with type: %s. no checking for min/max/mean/sigma" % (colname, stattype)
                else:
                    if not mins:
                        print h2o.dump_json(column)
                        # raise Exception ("Why is min[] empty for a %s col (%s) ? %s %s %s" % (mins, stattype, colname, nacnt, numRows))
                        print "Why is min[] empty for a %s col (%s) ? %s %s %s" % (mins, stattype, colname, nacnt, numRows)
                    if not maxs:
                        # this is failing on maprfs best buy...why? (va only?)
                        print h2o.dump_json(column)
                        # raise Exception ("Why is max[] empty for a %s col? (%s) ? %s %s %s" % (maxs, stattype, colname, nacnt, numRows))
                        print "Why is max[] empty for a %s col? (%s) ? %s %s %s" % (maxs, stattype, colname, nacnt, numRows)

            hstart = column['hstart']
            hstep = column['hstep']
            hbrk = column['hbrk']
            hcnt = column['hcnt']

            if not noPrint:
                print "\n\n************************"
                print "colname:", colname
                print "coltype:", coltype
                print "nacnt:", nacnt

                print "stattype:", stattype
                if stattype == 'Enum':
                    print "cardinality:", cardinality
                else:
                    print "mean:", mean
                    print "sd:", sd
                    print "zeros:", zeros
                    print "mins:", mins
                    print "maxs:", maxs
                    print "pct:", pct
                    print "pctile:", pctile

                # histogram stuff
                print "hstart:", hstart
                print "hstep:", hstep
                print "hbrk:", hbrk
                print "hcnt:", hcnt

    else:
        summary = summaryResult['summary']
        columnList = summary['columns']
        # can't get the right number of columns in summary? have to ask for more cols (does va support >  1000)
        if 1==0 and numCols and (len(columnList)!=numCols):
            raise Exception("Expected numCols: %s cols in summary. Got %s" % (numCols, len(columnList)))
        for column in columnList:
            N = column['N']
            # self.assertEqual(N, rowCount)
            name = column['name']
            stype = column['type']
            histogram = column['histogram']
            bin_size = histogram['bin_size']
            bin_names = histogram['bin_names']
            # if not noPrint:
            #     for b in bin_names:
            #        print "bin_name:", b

            bins = histogram['bins']
            nbins = histogram['bins']
            if not noPrint:
                print "\n\n************************"
                print "N:", N
                print "name:", name
                print "type:", stype
                print "bin_size:", bin_size
                print "len(bin_names):", len(bin_names), bin_names
                print "len(bins):", len(bins), bins
                print "len(nbins):", len(nbins), nbins

            # not done if enum
            if stype != "enum":
                zeros = column['zeros']
                na = column['na']
                maxs = column['max']
                mins = column['min']
                mean = column['mean']
                sigma = column['sigma']
                if not noPrint:
                    print "zeros:", zeros
                    print "na:", na
                    print "maxs:", maxs
                    print "mins:", mins
                    print "mean:", mean
                    print "sigma:", sigma

                if numRows and (na==numRows):
                    print "%s is all NAs with type: %s. no checking for min/max/mean/sigma" % (name, stype)
                else:
                    if not mins:
                        print h2o.dump_json(column)
                        raise Exception ("Why is min[] empty for a %s col (%s) ? %s %s %s" % (mins, stype, N, na, numRows))
                    if not maxs:
                        print h2o.dump_json(column)
                        # bestbuy dataset in maprfs is failing this ..for va only? not sure why. some nas?
                        print "Why is max[] empty for a %s col? (%s) ? %s %s %s" % (maxs, stype, N, na, numRows)

                # sometimes we don't get percentiles? (if 0 or 1 bins?)
                if len(bins) >= 2:
                    percentiles = column['percentiles']
                    thresholds = percentiles['thresholds']
                    values = percentiles['values']

                    if not noPrint:
                        # h2o shows 5 of them, ordered
                        print "len(max):", len(maxs), maxs
                        print "len(min):", len(mins), mins
                        print "len(thresholds):", len(thresholds), thresholds
                        print "len(values):", len(values), values

                    for v in values:
                        # 0 is the most max or most min
                       if not v >= mins[0]:
                            m = "Percentile value %s should all be >= the min dataset value %s" % (v, mins[0])
                            raise Exception(m)
                       if not v <= maxs[0]:
                            m = "Percentile value %s should all be <= the max dataset value %s" % (v, maxs[0])
                            raise Exception(m)

def dot():
    sys.stdout.write('.')
    sys.stdout.flush()

def sleep_with_dot(sec, message=None):
    if message:
        print message
    count = 0
    while count < sec:
        time.sleep(1)
        dot()
        count += 1

def createTestTrain(srcKey, trainDstKey, testDstKey, trainPercent,
    outputClass=None, outputCol=None, changeToBinomial=False):
    # will have to live with random extract. will create variance

    print "train: get random", trainPercent
    print "test: get remaining", 100 - trainPercent
    if changeToBinomial:
        print "change class", outputClass, "to 1, everything else to 0. factor() to turn real to int (for rf)"

    boundary = (trainPercent + 0.0)/100

    execExpr = ""
    execExpr += "cct.hex=runif(%s,-1);" % srcKey
    execExpr += "%s=%s[cct.hex<=%s,];" % (trainDstKey, srcKey, boundary)
    if changeToBinomial:
        execExpr += "%s[,%s]=%s[,%s]==%s;" % (trainDstKey, outputCol+1, trainDstKey, outputCol+1, outputClass)
        execExpr +=  "factor(%s[, %s]);" % (trainDstKey, outputCol+1)

    h2o_exec.exec_expr(None, execExpr, resultKey=trainDstKey, timeoutSecs=30)

    inspect = runInspect(key=trainDstKey)
    infoFromInspect(inspect, "%s after mungeDataset on %s" % (trainDstKey, srcKey) )

    print "test: same, but use the same runif() random result, complement comparison"

    execExpr = ""
    execExpr += "%s=%s[cct.hex>%s,];" % (testDstKey, srcKey, boundary)
    if changeToBinomial:
        execExpr += "%s[,%s]=%s[,%s]==%s;" % (testDstKey, outputCol+1, testDstKey, outputCol+1, outputClass)
        execExpr +=  "factor(%s[, %s])" % (testDstKey, outputCol+1)
    h2o_exec.exec_expr(None, execExpr, resultKey=testDstKey, timeoutSecs=30)

    inspect = runInspect(key=testDstKey)
    infoFromInspect(inspect, "%s after mungeDataset on %s" % (testDstKey, srcKey) )

# figure out what cols to ignore (opposite of cols+response)
def createIgnoredCols(key, cols, response):
    inspect = runInspect(key=key)
    numCols = inspect['numCols']
    ignore = filter(lambda x:(x not in cols and x!=response), range(numCols))

    ignored_cols = ','.join(map(str,ignore))
    return ignored_cols

# example:
# h2o_cmd.runScore(dataKey=scoreDataKey, modelKey=modelKey, vactual=y, vpredict=1, expectedAuc=0.5)
def runScore(node=None, dataKey=None, modelKey=None, predictKey='Predict.hex',
    vactual='C1', vpredict=1, expectedAuc=None, doAUC=True, timeoutSecs=200):
    # Score *******************************
    # this messes up if you use case_mode/case_vale above
    predictKey = 'Predict.hex'
    start = time.time()

    predictResult = runPredict(
        data_key=dataKey,
        model_key=modelKey,
        destination_key=predictKey,
        timeoutSecs=timeoutSecs)

    # inspect = runInspect(key=dataKey)
    # print dataKey, h2o.dump_json(inspect)

    # just get a predict and AUC on the same data. has to be binomial result
    if doAUC:
        resultAUC = h2o.nodes[0].generate_auc(
            thresholds=None,
            actual=dataKey,
            predict='Predict.hex',
            vactual=vactual,
            vpredict=vpredict)

        auc = resultAUC['AUC']

        if expectedAuc:
            h2o_util.assertApproxEqual(auc, expectedAuc, tol=0.15,
                msg="actual auc: %s not close enough to %s" % (auc, expectedAuc))

    # don't do this unless binomial
    predictCMResult = h2o.nodes[0].predict_confusion_matrix(
        actual=dataKey,
        predict=predictKey,
        vactual=vactual,
        vpredict='predict',
        )

    # print "cm", h2o.dump_json(predictCMResult)

    # These will move into the h2o_gbm.py
    # if doAUC=False, means we're not binomial, and the cm is not what we expect
    if doAUC:
        cm = predictCMResult['cm']
        pctWrong = h2o_gbm.pp_cm_summary(cm);
        print h2o_gbm.pp_cm(cm)

    return predictCMResult


text:
var mongoose = require('mongoose');
var express = require('express');

var Schema = mongoose.Schema;
var app = express();
var db = mongoose.connect('mongodb://localhost/scriptobox');

var sio = require('socket.io');

var modelMap = {};
modelMap['pad'] = mongoose.model('Pad', new Schema({
	title: String,
	active: Boolean
}) );

app.use(express.bodyParser());

app.use('/api/data', function(req, res, next) {

	// Get params
	var rawVars = req.path.split('/');
	var vars = [];
	for(var i=0; i<rawVars.length; i++) {
		if(!!rawVars[i]) vars.push(rawVars[i]);
	}

	// Add cross domain header
	res.set('Access-Control-Allow-Origin', '*');
	res.set('Access-Control-Allow-Headers', 'Content-Type');

	// Route the request
	if(req.body.action === 'query') apiQuery(vars[0], req.body.filter, function(data) {
		res.send({res: data});
	});
	else if(req.body.action === 'new') apiAdd(vars[0], req.body.data, function(data) {
		res.send({res: data});
	});

	else res.send({error: 'Invalid action'});

});

var server = app.listen(3000, function() {
	console.log('ScriptoBox Server started');
});

var io = sio.listen(server);
var ioPads = io.of('/pad');
ioPads.on('connection', function(socket) {

	socket.on('update', function(data) {
		ioPads.emit('updateOut', data);
	});

})

function apiQuery(table, filter, callback) {

	// Verify the collection exists
	if(modelMap[table] == null) callback([]);

	else {

		// Query the database
		modelMap[table].find(filter || {}).exec(function(err, data) {
			callback(data);
		});

	}
}

function apiAdd(table, data, callback) {

	// Verify the collection exists
	if(modelMap[table] == null) callback(null);

	else {

		// Create the model
		var inst = new modelMap[table](data);
		inst.save(function(err, inst) {
			if(err) console.log(err);
			else callback(inst);
		});

	}

}


text:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <string>
#include <linux/videodev2.h>

#include "../common/logging.h"
#include "platformstream.h"
#include "platformcontext.h"

// a platform factory function needed by
// libmain.cpp
Context* createPlatformContext()
{
    return new PlatformContext();
}

PlatformContext::PlatformContext() :
    Context()
{
    LOG(LOG_DEBUG, "Context created\n");
    enumerateDevices();
}

PlatformContext::~PlatformContext()
{
}

bool PlatformContext::enumerateDevices()
{
    int fd;
    v4l2_capability  video_cap;

    LOG(LOG_INFO,"Enumerating devices\n");

    const uint32_t maxDevices = 64; // FIXME: is this a sane number for linux?

    uint32_t dcount = 0;
    while(dcount < maxDevices)
    {
        char fname[100];
        snprintf(fname, sizeof(fname), "/dev/video%d", dcount++);

        if ((fd = ::open(fname, O_RDWR /* required */ | O_NONBLOCK)) == -1)
        {
            //LOG(LOG_ERR, "enumerateDevices: Can't open device %s\n", fname);
            continue;
        }

        if (ioctl(fd, VIDIOC_QUERYCAP, &video_cap) == -1)
        {
            ::close(fd);
            LOG(LOG_ERR, "enumerateDevices: Can't get capabilities\n");
            continue;
        }

        if ((video_cap.device_caps & V4L2_CAP_VIDEO_CAPTURE) != 0)
        {
            LOG(LOG_INFO,"Name: '%s'\n", video_cap.card);
            LOG(LOG_INFO,"Path: '%s'\n", fname);
            LOG(LOG_INFO,"Bus : '%s'\n", video_cap.bus_info);
            LOG(LOG_INFO,"capflags = %08X\n", video_cap.capabilities);
            LOG(LOG_INFO,"devflags = %08X\n", video_cap.device_caps);

            if ((video_cap.device_caps & V4L2_CAP_READWRITE) != 0)
            {
                LOG(LOG_INFO,"read/write supported\n");
            }
            else
            {
                LOG(LOG_INFO,"read/write NOT supported\n");
            }

            if ((video_cap.device_caps & V4L2_CAP_STREAMING) != 0)
            {
                LOG(LOG_INFO,"streaming I/O supported\n");
            }
            else
            {
                LOG(LOG_INFO,"streaming I/O NOT supported\n");
            }

            if ((video_cap.device_caps & V4L2_CAP_ASYNCIO) != 0)
            {
                LOG(LOG_INFO,"async I/O supported\n");
            }
            else
            {
                LOG(LOG_INFO,"async I/O NOT supported\n");
            }

            platformDeviceInfo* dinfo = new platformDeviceInfo();
            dinfo->m_name = std::string((const char*)video_cap.card);
            dinfo->m_devicePath = std::string(fname);
            dinfo->m_uniqueID = dinfo->m_name + " ";
            dinfo->m_uniqueID.append((const char*)video_cap.bus_info);

            // enumerate the frame formats
            v4l2_fmtdesc fmtdesc;
            uint32_t index = 0;
            fmtdesc.type  = V4L2_BUF_TYPE_VIDEO_CAPTURE;

            // FIXME: add FPS information
            // https://linuxtv.org/downloads/v4l-dvb-apis/uapi/v4l/vidioc-enum-frameintervals.html

            bool tryMore = true;
            while(tryMore)
            {
                fmtdesc.index = index;

                if (ioctl(fd, VIDIOC_ENUM_FMT, &fmtdesc) == -1)
                {
                    tryMore = false;
                }
                else
                {
                    LOG(LOG_INFO, "Format %d\n", index);
                    LOG(LOG_INFO, "  FOURCC = %s\n", fourCCToString(fmtdesc.pixelformat).c_str());

                    // .. then we enumerate all the frame buffer sizes for that
                    // pixel format type.
                    uint32_t frmindex = 0;
                    CapFormatInfo cinfo;
                    cinfo.fourcc = fmtdesc.pixelformat;
                    while(queryFrameSize(fd, frmindex, fmtdesc.pixelformat, &cinfo.width, &cinfo.height))
                    {
                        frmindex++;
                        cinfo.fps = findMaxFrameRate(fd, fmtdesc.pixelformat, cinfo.width, cinfo.height);
                        dinfo->m_formats.push_back(cinfo);
                        LOG(LOG_VERBOSE, "  %d x %d\n", cinfo.width, cinfo.height);
                    }
                }
                index++;
            }

            m_devices.push_back(dinfo);
        }

        ::close(fd);
    }
    return true;
}

bool PlatformContext::queryFrameSize(int fd, uint32_t index, uint32_t pixelformat, uint32_t *width, uint32_t *height)
{
    v4l2_frmsizeenum frmSize;
    frmSize.index = index;
    frmSize.pixel_format = pixelformat;
    if (ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &frmSize) != -1)
    {
        if (frmSize.type == V4L2_FRMSIZE_TYPE_DISCRETE)
        {
            *width  = frmSize.discrete.width;
            *height = frmSize.discrete.height;
        }
        else
        {
            LOG(LOG_WARNING, "queryFrameSize returned non-discrete frame size!\n");
            *width = 0;
            *height = 0;
        }

        return true;
    }
    return false;
}

uint32_t PlatformContext::findMaxFrameRate(int fd, uint32_t pixelformat,
    uint32_t width, uint32_t height)
{
    uint32_t fps = 0;

    // now search the frame rates
    v4l2_frmivalenum ivals;
    ivals.pixel_format = pixelformat;
    ivals.width = width;
    ivals.height = height;
    ivals.index = 0;
    LOG(LOG_VERBOSE,"Finding max frame rates: \n");
    while (ioctl(fd, VIDIOC_ENUM_FRAMEINTERVALS, &ivals) != -1)
    {
        if (ivals.type == V4L2_FRMIVAL_TYPE_DISCRETE)
        {
            LOG(LOG_VERBOSE,"  FPS %d/%d\n", ivals.discrete.denominator, ivals.discrete.numerator);
            uint32_t v = ivals.discrete.denominator/ivals.discrete.numerator;
            if (fps < v)
            {
                fps = v;
            }
        }
        ivals.index++;
    }

    return fps;
}


text:
require 'test_helper'

class CabinetsControllerTest < ActionController::TestCase
  setup do
    @cabinet = cabinets(:one)
  end

  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:cabinets)
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should create cabinet" do
    assert_difference('Cabinet.count') do
      post :create, cabinet: { abbr: @cabinet.abbr, description: @cabinet.description, room: @cabinet.room }
    end

    assert_redirected_to cabinet_path(assigns(:cabinet))
  end

  test "should show cabinet" do
    get :show, id: @cabinet
    assert_response :success
  end

  test "should get edit" do
    get :edit, id: @cabinet
    assert_response :success
  end

  test "should update cabinet" do
    patch :update, id: @cabinet, cabinet: { abbr: @cabinet.abbr, description: @cabinet.description, room: @cabinet.room }
    assert_redirected_to cabinet_path(assigns(:cabinet))
  end

  test "should destroy cabinet" do
    assert_difference('Cabinet.count', -1) do
      delete :destroy, id: @cabinet
    end

    assert_redirected_to cabinets_path
  end
end


text:
<?php

namespace Kris\LaravelFormBuilder\Console;

class FormGenerator
{

    /**
     * Get fields from options and create add methods from it.
     *
     * @param string|null $fields
     * @return string
     */
    public function getFieldsVariable($fields = null)
    {
        if ($fields) {
            return $this->parseFields($fields);
        }

        return '// Add fields here...';
    }

    /**
     * @param string $name
     * @return object
     */
    public function getClassInfo($name)
    {
        $explodedClassNamespace = explode('\\', $name);
        $className = array_pop($explodedClassNamespace);
        $fullNamespace = join('\\', $explodedClassNamespace);

        return (object)[
            'namespace' => $fullNamespace,
            'className' => $className
        ];
    }

    /**
     * Parse fields from string.
     *
     * @param string $fields
     * @return string
     */
    protected function parseFields($fields)
    {
        $fieldsArray = explode(',', $fields);
        $text = '$this'."\n";

        foreach ($fieldsArray as $field) {
            $text .= $this->prepareAdd($field, end($fieldsArray) == $field);
        }

        return $text.';';
    }

    /**
     * Prepare template for single add field.
     *
     * @param string $field
     * @param bool $isLast
     * @return string
     */
    protected function prepareAdd($field, $isLast = false)
    {
        $field = trim($field);
        list($name, $type) = explode(':', $field);
        $textArr = [
            "            ->add('",
            $name,
            "', '",
            $type,
            "')",
            ($isLast) ? "" : "\n"
        ];

        return join('', $textArr);
    }

}


text:
Looseleaf
======
Looseleaf style for [Mapbox Studio](https://github.com/mapbox/mapbox-studio/).


text:
{% extends "base.html" %}

{% block main %}
<form method="post" action="/login" class="form-stacked">

		Username:

			<input class='span12' id='username' name='username' type='text'>

		Password:

			<input class='span12' id='password' name='password' type='password'>

	<input type="hidden" name="_csrf_token" value="{{ csrf_token() }}">
	<input type='hidden' name='next' value="{{ request.values.next or '' }}">

    <button type="submit" class="btn primary">Login</button>

    <button type="reset" class="btn">Cancel</button>

</form>

If you do not already have a username/password, please sign up.

{% endblock %}


text:
package org.jclouds.oauth.v2.internal;

import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.oauth.v2.OAuthTestUtils.setCredential;
import static org.jclouds.oauth.v2.config.OAuthProperties.AUDIENCE;
import static org.jclouds.oauth.v2.config.OAuthProperties.SCOPES;
import static org.jclouds.oauth.v2.config.OAuthProperties.SIGNATURE_OR_MAC_ALGORITHM;

import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.jclouds.apis.BaseApiLiveTest;
import org.jclouds.oauth.v2.OAuthApi;
import org.testng.annotations.Test;

@Test(groups = "live")
public class BaseOAuthApiLiveTest extends BaseApiLiveTest<OAuthApi> {

   public BaseOAuthApiLiveTest() {
      provider = "oauth";
   }

   @Override
   protected Properties setupProperties() {
      Properties props = super.setupProperties();
      setCredential(props, "oauth.credential");
      checkNotNull(setIfTestSystemPropertyPresent(props, "oauth.endpoint"), "test.oauth.endpoint must be set");
      checkNotNull(setIfTestSystemPropertyPresent(props, AUDIENCE), "test.jclouds.oauth.audience must be set");
      setIfTestSystemPropertyPresent(props, SCOPES);
      setIfTestSystemPropertyPresent(props, SIGNATURE_OR_MAC_ALGORITHM);
      return props;
   }

   protected long nowInSeconds() {
      return TimeUnit.SECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
   }

}


text:
'use strict';

import sortByOrder from 'lodash.sortbyorder';

module.exports = (columns, column, done) => {
    columns.map((col) => {
        col.classes = {};

        return col;
    });

    column.sort = column.sort === 'asc' ? 'desc' : 'asc';
    column.classes = {
        'sort-asc': column.sort === 'asc',
        'sort-desc': column.sort === 'desc'
    };

    done({
        sortingColumn: column,
        columns: columns });
};

module.exports.sort = (data, column) => {
    if (!column) {
        return data;
    }

    var property = column.property;

    return sortByOrder(data, [property], [column.sort]);
};


text:
from __future__ import unicode_literals
import hashlib
import urllib

from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.utils.functional import cached_property

class Trooper(AbstractUser):

    class Meta(AbstractUser.Meta):
        swappable = 'AUTH_USER_MODEL'

    def profile_pic(self):
        email_hash = hashlib.md5(self.email.lower()).hexdigest()
        keys = {'d': settings.DEFAULT_AVATAR}
        keys = urllib.urlencode(keys)
        return "https://www.gravatar.com/avatar/{hash}?{query}".format(hash=email_hash,
                                                                       query=keys)

    @cached_property
    def recently_created_tasks(self):
        return self.task_set.all()

    @cached_property
    def recently_answered_tasks(self):
        from tasker.models import Task
        answer_ids = self.recent_answers.values_list('id', flat=True)
        return Task.objects.filter(id__in=answer_ids).distinct()

    @cached_property
    def recent_answers(self):
        return self.answer_set.all().prefetch_related('question__task')


text:
const ActionTypes = {
	INIT_SPACE: 'INIT_SPACE',
	SET_SPACE_LOADING: 'SET_SPACE_LOADING',
	LOAD_ARTICLES : 'LOAD_ARTICLES',

	INIT_ARTICLE: 'INIT_ARTICLE',
	RESET_ARTICLE: 'RESET_ARTICLE',
	SHOW_BIG_PICTURE: 'SHOW_BIG_PICTURE',

	COOKIE_AUTH: 'COOKIE_AUTH',
};
const ChangeEvent = 'change';

const DEBUG = true;
const WEB_ROOT = DEBUG ? 'http://localhost:3006/' : '';

const ObjectType = {
	TYPE_ARTICLE: 'ARTICLE',
	TYPE_SPACE: 'SPACE',
	TYPE_USER: 'USER',
};

const COOKIE_AUTH = 'vvhcdsfasdf';

module.exports = {
	DEBUG,
	ChangeEvent,
	ActionTypes,
	ObjectType,
	WEB_ROOT,
	COOKIE_AUTH,
};


text:
/**
 * @author Georgegriff@ (George Griffiths)
 * License Apache-2.0
 */

/**
* Finds first matching elements on the page that may be in a shadow root using a complex selector of n-depth
*
* Don't have to specify all shadow roots to button, tree is travered to find the correct element
*
* Example querySelectorAllDeep('downloads-item:nth-child(4) #remove');
*
* Example should work on chrome://downloads outputting the remove button inside of a download card component
*
* Example find first active download link element querySelectorDeep('#downloads-list .is-active a[href^="https://"]');
*
* Another example querySelectorAllDeep('#downloads-list div#title-area + a');
e.g.
*/
export function querySelectorAllDeep(selector, root = document) {
    return _querySelectorDeep(selector, true, root);
}

export function querySelectorDeep(selector, root = document) {
    return _querySelectorDeep(selector, false, root);
}

function _querySelectorDeep(selector, findMany, root) {
    let lightElement = root.querySelector(selector);

    if (document.head.createShadowRoot || document.head.attachShadow) {
        // no need to do any special if selector matches something specific in light-dom
        if (!findMany && lightElement) {
            return lightElement;
        }

        // split on commas because those are a logical divide in the operation
        const selectionsToMake = splitByCharacterUnlessQuoted(selector, ',');

        return selectionsToMake.reduce((acc, minimalSelector) => {
            // if not finding many just reduce the first match
            if (!findMany && acc) {
                return acc;
            }
            // do best to support complex selectors and split the query
            const splitSelector = splitByCharacterUnlessQuoted(minimalSelector
                    //remove white space at start of selector
                    .replace(/^\s+/g, '')
                    .replace(/\s*([>+~]+)\s*/g, '$1'), ' ')
                // filter out entry white selectors
                .filter((entry) => !!entry);
            const possibleElementsIndex = splitSelector.length - 1;
            const possibleElements = collectAllElementsDeep(splitSelector[possibleElementsIndex], root);
            const findElements = findMatchingElement(splitSelector, possibleElementsIndex, root);
            if (findMany) {
                acc = acc.concat(possibleElements.filter(findElements));
                return acc;
            } else {
                acc = possibleElements.find(findElements);
                return acc || null;
            }
        }, findMany ? [] : null);

    } else {
        if (!findMany) {
            return lightElement;
        } else {
            return root.querySelectorAll(selector);
        }
    }

}

function findMatchingElement(splitSelector, possibleElementsIndex, root) {
    return (element) => {
        let position = possibleElementsIndex;
        let parent = element;
        let foundElement = false;
        while (parent) {
            const foundMatch = parent.matches(splitSelector[position]);
            if (foundMatch && position === 0) {
                foundElement = true;
                break;
            }
            if (foundMatch) {
                position--;
            }
            parent = findParentOrHost(parent, root);
        }
        return foundElement;
    };

}

function splitByCharacterUnlessQuoted(selector, character) {
    return selector.match(/\\?.|^$/g).reduce((p, c) => {
        if (c === '"' && !p.sQuote) {
            p.quote ^= 1;
            p.a[p.a.length - 1] += c;
        } else if (c === '\'' && !p.quote) {
            p.sQuote ^= 1;
            p.a[p.a.length - 1] += c;

        } else if (!p.quote && !p.sQuote && c === character) {
            p.a.push('');
        } else {
            p.a[p.a.length - 1] += c;
        }
        return p;
    }, { a: [''] }).a;
}

function findParentOrHost(element, root) {
    const parentNode = element.parentNode;
    return (parentNode && parentNode.host && parentNode.nodeType === 11) ? parentNode.host : parentNode === root ? null : parentNode;
}

/**
 * Finds all elements on the page, inclusive of those within shadow roots.
 * @param {string=} selector Simple selector to filter the elements by. e.g. 'a', 'div.main'
 * @return {!Array<string>} List of anchor hrefs.
 * @author ebidel@ (Eric Bidelman)
 * License Apache-2.0
 */
function collectAllElementsDeep(selector = null, root) {
    const allElements = [];

    const findAllElements = function(nodes) {
        for (let i = 0, el; el = nodes[i]; ++i) {
            allElements.push(el);
            // If the element has a shadow root, dig deeper.
            if (el.shadowRoot) {
                findAllElements(el.shadowRoot.querySelectorAll('*'));
            }
        }
    };
    if(root.shadowRoot) {
        findAllElements(root.shadowRoot.querySelectorAll('*'));
    }
    findAllElements(root.querySelectorAll('*'));

    return selector ? allElements.filter(el => el.matches(selector)) : allElements;
}


text:
package org.eclipse.jface.text.link;

import java.util.Arrays;

import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.contentassist.ICompletionProposal;

/**
 * LinkedPosition with added completion proposals.
 *

 * Clients may instantiate or extend this class.
 *

 *
 * @since 3.0
 */
public class ProposalPosition extends LinkedPosition {

	/**
	 * The proposals
	 */
	private ICompletionProposal[] fProposals;

	/**
	 * Creates a new instance.
	 *
	 * @param document the document
	 * @param offset the offset of the position
	 * @param length the length of the position
	 * @param sequence the iteration sequence rank
	 * @param proposals the proposals to be shown when entering this position
	 */
	public ProposalPosition(IDocument document, int offset, int length, int sequence, ICompletionProposal[] proposals) {
		super(document, offset, length, sequence);
		fProposals= copy(proposals);
	}

	/**
	 * Creates a new instance, with no sequence number.
	 *
	 * @param document the document
	 * @param offset the offset of the position
	 * @param length the length of the position
	 * @param proposals the proposals to be shown when entering this position
	 */
	public ProposalPosition(IDocument document, int offset, int length, ICompletionProposal[] proposals) {
		super(document, offset, length, LinkedPositionGroup.NO_STOP);
		fProposals= copy(proposals);
	}

	/*
	 * @since 3.1
	 */
	private ICompletionProposal[] copy(ICompletionProposal[] proposals) {
		if (proposals != null) {
			ICompletionProposal[] copy= new ICompletionProposal[proposals.length];
			System.arraycopy(proposals, 0, copy, 0, proposals.length);
			return copy;
		}
		return null;
	}

	/*
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	public boolean equals(Object o) {
		if (o instanceof ProposalPosition) {
			if (super.equals(o)) {
				return Arrays.equals(fProposals, ((ProposalPosition)o).fProposals);
			}
		}
		return false;
	}

	/**
	 * Returns the proposals attached to this position. The returned array is owned by
	 * this ProposalPosition and may not be modified by clients.
	 *
	 * @return an array of choices, including the initial one. Callers must not
	 *         modify it.
	 */
	public ICompletionProposal[] getChoices() {
		return fProposals;
	}

	/*
	 * @see org.eclipse.jdt.internal.ui.text.link.LinkedPosition#hashCode()
	 */
	public int hashCode() {
		return super.hashCode() | (fProposals == null ? 0 : fProposals.hashCode());
	}
}


text:
package com.github.ltsopensource.redis;

import com.github.ltsopensource.core.logger.Logger;
import com.github.ltsopensource.core.logger.LoggerFactory;
import redis.clients.jedis.Jedis;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Publisher {

    private static final Logger logger = LoggerFactory.getLogger(Publisher.class);

    private final Jedis publisherJedis;

    private final String channel;

    public Publisher(Jedis publisherJedis, String channel) {
        this.publisherJedis = publisherJedis;
        this.channel = channel;
    }

    public void start() {
        logger.info("Type your message (quit for terminate)");
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

            while (true) {
                String line = reader.readLine();

                if (!"quit".equals(line)) {
                    publisherJedis.publish(channel, line);
                } else {
                    break;
                }
            }

        } catch (IOException e) {
            logger.error("IO failure while reading input, e");
        }
    }
}


text:
<?php

class paymill_log_list extends paymill_log_abstract
{
    private $_searchKey;

    private $_page;

    private $_recordLimit = 8;

    private $_pageCount;

    public function render()
    {
        parent::render();

        $oxConfig = oxRegistry::getConfig();

        $this->_page = $oxConfig->getRequestParameter('seite');
        $this->_searchKey = $oxConfig->getRequestParameter('search_key');
        $this->addTplParam('list', $this->_getData());
        $this->addTplParam('editUrl', $this->_getAdminUrl() . '&cl=paymill_log_entry');
        $this->addTplParam('pageCount', $this->_pageCount);
        return 'paymill_log_list.tpl';
    }

    private function _getData()
    {
        $logList = oxNew('paymill_loglist');

        $where = null;
        if (!empty($this->_searchKey)) {
            $where = 'debug like "%' . $this->_searchKey . '%"';
        }

        if (empty($this->_page)) {
            $this->_page = 1;
        }

        $start = $this->_page * $this->_recordLimit - $this->_recordLimit;

        $this->_pageCount = count($logList->getFilteredList($where)) / $this->_recordLimit;

        $data = $logList->setLimit($start, $this->_recordLimit)->getFilteredList($where)->getArray();

        return $data;
    }

}