text:
import { Quat } from '../math/quat.js';
import { Vec3 } from '../math/vec3.js';

function InterpolatedKey() {
    this._written = false;
    this._name = "";
    this._keyFrames = [];

    // Result of interpolation
    this._quat = new Quat();
    this._pos = new Vec3();
    this._scale = new Vec3();

    // Optional destination for interpolated keyframe
    this._targetNode = null;
}

Object.assign(InterpolatedKey.prototype, {
    getTarget: function () {
        return this._targetNode;
    },

    setTarget: function (node) {
        this._targetNode = node;
    }
});

/**
 * @class
 * @name pc.Skeleton
 * @classdesc Represents a skeleton used to play animations.
 * @param {pc.GraphNode} graph - The root pc.GraphNode of the skeleton.
 * @property {boolean} looping Determines whether skeleton is looping its animation.
 */
function Skeleton(graph) {
    this._animation = null;
    this._time = 0;
    this.looping = true;

    this._interpolatedKeys = [];
    this._interpolatedKeyDict = {};
    this._currKeyIndices = {};

    this.graph = null;

    var self = this;

    function addInterpolatedKeys(node) {
        var interpKey = new InterpolatedKey();
        interpKey._name = node.name;
        self._interpolatedKeys.push(interpKey);
        self._interpolatedKeyDict[node.name] = interpKey;
        self._currKeyIndices[node.name] = 0;

        for (var i = 0; i < node._children.length; i++)
            addInterpolatedKeys(node._children[i]);
    }

    addInterpolatedKeys(graph);
}

/**
 * @function
 * @name pc.Skeleton#addTime
 * @description Progresses The animation assigned to The specified skeleton by The
 * supplied time delta. If the delta takes the animation passed its end point, if
 * the skeleton is set to loop, the animation will continue from the beginning.
 * Otherwise, the animation's current time will remain at its duration (i.e. the
 * end).
 * @param {number} delta - The time in seconds to progress the skeleton's animation.
 */
Skeleton.prototype.addTime = function (delta) {
    if (this._animation !== null) {
        var i;
        var node, nodeName;
        var keys, interpKey;
        var k1, k2, alpha;
        var nodes = this._animation._nodes;
        var duration = this._animation.duration;

        // Check if we can early out
        if ((this._time === duration) && !this.looping) {
            return;
        }

        // Step the current time and work out if we need to jump ahead, clamp or wrap around
        this._time += delta;

        if (this._time > duration) {
            this._time = this.looping ? 0.0 : duration;
            for (i = 0; i < nodes.length; i++) {
                node = nodes[i];
                nodeName = node._name;
                this._currKeyIndices[nodeName] = 0;
            }
        } else if (this._time < 0) {
            this._time = this.looping ? duration : 0.0;
            for (i = 0; i < nodes.length; i++) {
                node = nodes[i];
                nodeName = node._name;
                this._currKeyIndices[nodeName] = node._keys.length - 2;
            }
        }

        // For each animated node...

        // keys index offset
        var offset = (delta >= 0 ? 1 : -1);

        var foundKey;
        for (i = 0; i < nodes.length; i++) {
            node = nodes[i];
            nodeName = node._name;
            keys = node._keys;

            // Determine the interpolated keyframe for this animated node
            interpKey = this._interpolatedKeyDict[nodeName];
            if (interpKey === undefined) {
                // #ifdef DEBUG
                console.warn('Unknown skeleton node name: ' + nodeName);
                // #endif
                continue;
            }
            // If there's only a single key, just copy the key to the interpolated key...
            foundKey = false;
            if (keys.length !== 1) {
                // Otherwise, find the keyframe pair for this node
                for (var currKeyIndex = this._currKeyIndices[nodeName]; currKeyIndex < keys.length - 1 && currKeyIndex >= 0; currKeyIndex += offset) {
                    k1 = keys[currKeyIndex];
                    k2 = keys[currKeyIndex + 1];

                    if ((k1.time <= this._time) && (k2.time >= this._time)) {
                        alpha = (this._time - k1.time) / (k2.time - k1.time);

                        interpKey._pos.lerp(k1.position, k2.position, alpha);
                        interpKey._quat.slerp(k1.rotation, k2.rotation, alpha);
                        interpKey._scale.lerp(k1.scale, k2.scale, alpha);
                        interpKey._written = true;

                        this._currKeyIndices[nodeName] = currKeyIndex;
                        foundKey = true;
                        break;
                    }
                }
            }
            if (keys.length === 1 || (!foundKey && this._time === 0.0 && this.looping)) {
                interpKey._pos.copy(keys[0].position);
                interpKey._quat.copy(keys[0].rotation);
                interpKey._scale.copy(keys[0].scale);
                interpKey._written = true;
            }
        }
    }
};

/**
 * @function
 * @name pc.Skeleton#blend
 * @description Blends two skeletons together.
 * @param {pc.Skeleton} skel1 - Skeleton holding the first pose to be blended.
 * @param {pc.Skeleton} skel2 - Skeleton holding the second pose to be blended.
 * @param {number} alpha - The value controlling the interpolation in relation to the two input
 * skeletons. The value is in the range 0 to 1, 0 generating skel1, 1 generating skel2 and anything
 * in between generating a spherical interpolation between the two.
 */
Skeleton.prototype.blend = function (skel1, skel2, alpha) {
    var numNodes = this._interpolatedKeys.length;
    for (var i = 0; i < numNodes; i++) {
        var key1 = skel1._interpolatedKeys[i];
        var key2 = skel2._interpolatedKeys[i];
        var dstKey = this._interpolatedKeys[i];

        if (key1._written && key2._written) {
            dstKey._quat.slerp(key1._quat, skel2._interpolatedKeys[i]._quat, alpha);
            dstKey._pos.lerp(key1._pos, skel2._interpolatedKeys[i]._pos, alpha);
            dstKey._scale.lerp(key1._scale, key2._scale, alpha);
            dstKey._written = true;
        } else if (key1._written) {
            dstKey._quat.copy(key1._quat);
            dstKey._pos.copy(key1._pos);
            dstKey._scale.copy(key1._scale);
            dstKey._written = true;
        } else if (key2._written) {
            dstKey._quat.copy(key2._quat);
            dstKey._pos.copy(key2._pos);
            dstKey._scale.copy(key2._scale);
            dstKey._written = true;
        }
    }
};

/**
 * @name pc.Skeleton#animation
 * @type {pc.Animation}
 * @description Animation currently assigned to skeleton.
 */
Object.defineProperty(Skeleton.prototype, 'animation', {
    get: function () {
        return this._animation;
    },
    set: function (value) {
        this._animation = value;
        this.currentTime = 0;
    }
});

/**
 * @private
 * @deprecated
 * @function
 * @name pc.Skeleton#getAnimation
 * @description Returns the animation currently assigned to the specified skeleton.
 * @returns {pc.Animation} The animation set on the skeleton.
 */
Skeleton.prototype.getAnimation = function () {
    return this._animation;
};

/**
 * @name pc.Skeleton#currentTime
 * @type {number}
 * @description Current time of currently active animation in seconds.
 * This value is between zero and the duration of the animation.
 */
Object.defineProperty(Skeleton.prototype, 'currentTime', {
    get: function () {
        return this._time;
    },
    set: function (value) {
        this._time = value;
        var numNodes = this._interpolatedKeys.length;
        for (var i = 0; i < numNodes; i++) {
            var node = this._interpolatedKeys[i];
            var nodeName = node._name;
            this._currKeyIndices[nodeName] = 0;
        }

        this.addTime(0);
        this.updateGraph();
    }
});

/**
 * @private
 * @deprecated
 * @function
 * @name pc.Skeleton#getCurrentTime
 * @description Returns the current time of the currently active animation as set on
 * the specified skeleton. This value will be between zero and the duration of the
 * animation.
 * @returns {number} The current time of the animation set on the skeleton.
 */
Skeleton.prototype.getCurrentTime = function () {
    return this._time;
};

/**
 * @private
 * @deprecated
 * @function
 * @name pc.Skeleton#setCurrentTime
 * @description Sets the current time of the currently active animation as set on
 * the specified skeleton. This value must be between zero and the duration of the
 * animation.
 * @param {number} time - The current time of the animation set on the skeleton.
 */
Skeleton.prototype.setCurrentTime = function (time) {
    this.currentTime = time;
};

/**
 * @readonly
 * @name pc.Skeleton#numNodes
 * @type {number}
 * @description Read-only property that returns number of nodes of a skeleton.
 */
Object.defineProperty(Skeleton.prototype, 'numNodes', {
    get: function () {
        return this._interpolatedKeys.length;
    }
});

/**
 * @private
 * @deprecated
 * @function
 * @name pc.Skeleton#getNumNodes
 * @description Returns the number of nodes held by the specified skeleton.
 * @returns {number} The number of nodes held by the specified skeleton.
 */
Skeleton.prototype.getNumNodes = function () {
    return this._interpolatedKeys.length;
};

/**
 * @private
 * @deprecated
 * @function
 * @name pc.Skeleton#setAnimation
 * @description Sets an animation on the specified skeleton.
 * @param {pc.Animation} animation - The animation to set on the skeleton.
 */
Skeleton.prototype.setAnimation = function (animation) {
    this.animation = animation;
};

/**
 * @function
 * @name pc.Skeleton#setGraph
 * @description Links a skeleton to a node hierarchy. The nodes animated skeleton are
 * then subsequently used to drive the local transformation matrices of the node
 * hierarchy.
 * @param {pc.GraphNode} graph - The root node of the graph that the skeleton is to drive.
 */
Skeleton.prototype.setGraph = function (graph) {
    var i;
    this.graph = graph;

    if (graph) {
        for (i = 0; i < this._interpolatedKeys.length; i++) {
            var interpKey = this._interpolatedKeys[i];
            var graphNode = graph.findByName(interpKey._name);
            this._interpolatedKeys[i].setTarget(graphNode);
        }
    } else {
        for (i = 0; i < this._interpolatedKeys.length; i++) {
            this._interpolatedKeys[i].setTarget(null);
        }
    }
};

/**
 * @function
 * @name pc.Skeleton#updateGraph
 * @description Synchronizes the currently linked node hierarchy with the current state of the
 * skeleton. Internally, this function converts the interpolated keyframe at each node in the
 * skeleton into the local transformation matrix at each corresponding node in the linked node
 * hierarchy.
 */
Skeleton.prototype.updateGraph = function () {
    if (this.graph) {
        for (var i = 0; i < this._interpolatedKeys.length; i++) {
            var interpKey = this._interpolatedKeys[i];
            if (interpKey._written) {
                var transform = interpKey.getTarget();

                transform.localPosition.copy(interpKey._pos);
                transform.localRotation.copy(interpKey._quat);
                transform.localScale.copy(interpKey._scale);

                if (!transform._dirtyLocal)
                    transform._dirtifyLocal();

                interpKey._written = false;
            }
        }
    }
};

/**
 * @private
 * @deprecated
 * @function
 * @name pc.Skeleton#setLooping
 * @description Specified whether a skeleton should loop its animation or not. If the animation
 * loops, it will wrap back to the start when adding time to the skeleton beyond the duration
 * of the animation. Otherwise, the animation stops at its end after a single play through.
 * @param {boolean} looping - True to cause the animation to loop back to the start on completion
 * and false otherwise.
 */
Skeleton.prototype.setLooping = function (looping) {
    this.looping = looping;
};

/**
 * @private
 * @deprecated
 * @function
 * @name pc.Skeleton#getLooping
 * @description Queries the specified skeleton to determine whether it is looping its animation.
 * @returns {boolean} True if the skeleton is looping the animation, false otherwise.
 */
Skeleton.prototype.getLooping = function () {
    return this.looping;
};

export { Skeleton };


text:
#ifndef LOVE_PHYSICS_BOX2D_WRAP_FRICTION_JOINT_H
#define LOVE_PHYSICS_BOX2D_WRAP_FRICTION_JOINT_H

// LOVE
#include "common/runtime.h"
#include "wrap_Joint.h"
#include "FrictionJoint.h"

namespace love
{
namespace physics
{
namespace box2d
{

FrictionJoint *luax_checkfrictionjoint(lua_State *L, int idx);
int w_FrictionJoint_setMaxForce(lua_State *L);
int w_FrictionJoint_getMaxForce(lua_State *L);
int w_FrictionJoint_setMaxTorque(lua_State *L);
int w_FrictionJoint_getMaxTorque(lua_State *L);
extern "C" int luaopen_frictionjoint(lua_State *L);

} // box2d
} // physics
} // love

#endif // LOVE_PHYSICS_BOX2D_WRAP_FRICTION_JOINT_H

redpajama_set_name: RedPajamaGithub


text:
#ifndef LLVM_CODEGEN_LIVEINTERVAL_ANALYSIS_H
#define LLVM_CODEGEN_LIVEINTERVAL_ANALYSIS_H

#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/LiveInterval.h"
#include "llvm/CodeGen/SlotIndexes.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Allocator.h"
#include <cmath>
#include <iterator>

namespace llvm {

  class AliasAnalysis;
  class LiveVariables;
  class MachineLoopInfo;
  class TargetRegisterInfo;
  class MachineRegisterInfo;
  class TargetInstrInfo;
  class TargetRegisterClass;
  class VirtRegMap;

  class LiveIntervals : public MachineFunctionPass {
    MachineFunction* mf_;
    MachineRegisterInfo* mri_;
    const TargetMachine* tm_;
    const TargetRegisterInfo* tri_;
    const TargetInstrInfo* tii_;
    AliasAnalysis *aa_;
    LiveVariables* lv_;
    SlotIndexes* indexes_;

    /// Special pool allocator for VNInfo's (LiveInterval val#).
    ///
    VNInfo::Allocator VNInfoAllocator;

    typedef DenseMap<unsigned, LiveInterval*> Reg2IntervalMap;
    Reg2IntervalMap r2iMap_;

    /// allocatableRegs_ - A bit vector of allocatable registers.
    BitVector allocatableRegs_;

    /// reservedRegs_ - A bit vector of reserved registers.
    BitVector reservedRegs_;

    /// RegMaskSlots - Sorted list of instructions with register mask operands.
    /// Always use the 'r' slot, RegMasks are normal clobbers, not early
    /// clobbers.
    SmallVector<SlotIndex, 8> RegMaskSlots;

    /// RegMaskBits - This vector is parallel to RegMaskSlots, it holds a
    /// pointer to the corresponding register mask.  This pointer can be
    /// recomputed as:
    ///
    ///   MI = Indexes->getInstructionFromIndex(RegMaskSlot[N]);
    ///   unsigned OpNum = findRegMaskOperand(MI);
    ///   RegMaskBits[N] = MI->getOperand(OpNum).getRegMask();
    ///
    /// This is kept in a separate vector partly because some standard
    /// libraries don't support lower_bound() with mixed objects, partly to
    /// improve locality when searching in RegMaskSlots.
    /// Also see the comment in LiveInterval::find().
    SmallVector<const uint32_t*, 8> RegMaskBits;

    /// For each basic block number, keep (begin, size) pairs indexing into the
    /// RegMaskSlots and RegMaskBits arrays.
    /// Note that basic block numbers may not be layout contiguous, that's why
    /// we can't just keep track of the first register mask in each basic
    /// block.
    SmallVector<std::pair<unsigned, unsigned>, 8> RegMaskBlocks;

  public:
    static char ID; // Pass identification, replacement for typeid
    LiveIntervals() : MachineFunctionPass(ID) {
      initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
    }

    // Calculate the spill weight to assign to a single instruction.
    static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth);

    typedef Reg2IntervalMap::iterator iterator;
    typedef Reg2IntervalMap::const_iterator const_iterator;
    const_iterator begin() const { return r2iMap_.begin(); }
    const_iterator end() const { return r2iMap_.end(); }
    iterator begin() { return r2iMap_.begin(); }
    iterator end() { return r2iMap_.end(); }
    unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }

    LiveInterval &getInterval(unsigned reg) {
      Reg2IntervalMap::iterator I = r2iMap_.find(reg);
      assert(I != r2iMap_.end() && "Interval does not exist for register");
      return *I->second;
    }

    const LiveInterval &getInterval(unsigned reg) const {
      Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
      assert(I != r2iMap_.end() && "Interval does not exist for register");
      return *I->second;
    }

    bool hasInterval(unsigned reg) const {
      return r2iMap_.count(reg);
    }

    /// isAllocatable - is the physical register reg allocatable in the current
    /// function?
    bool isAllocatable(unsigned reg) const {
      return allocatableRegs_.test(reg);
    }

    /// isReserved - is the physical register reg reserved in the current
    /// function
    bool isReserved(unsigned reg) const {
      return reservedRegs_.test(reg);
    }

    /// getScaledIntervalSize - get the size of an interval in "units,"
    /// where every function is composed of one thousand units.  This
    /// measure scales properly with empty index slots in the function.
    double getScaledIntervalSize(LiveInterval& I) {
      return (1000.0 * I.getSize()) / indexes_->getIndexesLength();
    }

    /// getFuncInstructionCount - Return the number of instructions in the
    /// current function.
    unsigned getFuncInstructionCount() {
      return indexes_->getFunctionSize();
    }

    /// getApproximateInstructionCount - computes an estimate of the number
    /// of instructions in a given LiveInterval.
    unsigned getApproximateInstructionCount(LiveInterval& I) {
      double IntervalPercentage = getScaledIntervalSize(I) / 1000.0;
      return (unsigned)(IntervalPercentage * indexes_->getFunctionSize());
    }

    // Interval creation
    LiveInterval &getOrCreateInterval(unsigned reg) {
      Reg2IntervalMap::iterator I = r2iMap_.find(reg);
      if (I == r2iMap_.end())
        I = r2iMap_.insert(std::make_pair(reg, createInterval(reg))).first;
      return *I->second;
    }

    /// dupInterval - Duplicate a live interval. The caller is responsible for
    /// managing the allocated memory.
    LiveInterval *dupInterval(LiveInterval *li);

    /// addLiveRangeToEndOfBlock - Given a register and an instruction,
    /// adds a live range from that instruction to the end of its MBB.
    LiveRange addLiveRangeToEndOfBlock(unsigned reg,
                                       MachineInstr* startInst);

    /// shrinkToUses - After removing some uses of a register, shrink its live
    /// range to just the remaining uses. This method does not compute reaching
    /// defs for new uses, and it doesn't remove dead defs.
    /// Dead PHIDef values are marked as unused.
    /// New dead machine instructions are added to the dead vector.
    /// Return true if the interval may have been separated into multiple
    /// connected components.
    bool shrinkToUses(LiveInterval *li,
                      SmallVectorImpl<MachineInstr*> *dead = 0);

    // Interval removal

    void removeInterval(unsigned Reg) {
      DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.find(Reg);
      delete I->second;
      r2iMap_.erase(I);
    }

    SlotIndexes *getSlotIndexes() const {
      return indexes_;
    }

    /// isNotInMIMap - returns true if the specified machine instr has been
    /// removed or was never entered in the map.
    bool isNotInMIMap(const MachineInstr* Instr) const {
      return !indexes_->hasIndex(Instr);
    }

    /// Returns the base index of the given instruction.
    SlotIndex getInstructionIndex(const MachineInstr *instr) const {
      return indexes_->getInstructionIndex(instr);
    }

    /// Returns the instruction associated with the given index.
    MachineInstr* getInstructionFromIndex(SlotIndex index) const {
      return indexes_->getInstructionFromIndex(index);
    }

    /// Return the first index in the given basic block.
    SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
      return indexes_->getMBBStartIdx(mbb);
    }

    /// Return the last index in the given basic block.
    SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
      return indexes_->getMBBEndIdx(mbb);
    }

    bool isLiveInToMBB(const LiveInterval &li,
                       const MachineBasicBlock *mbb) const {
      return li.liveAt(getMBBStartIdx(mbb));
    }

    bool isLiveOutOfMBB(const LiveInterval &li,
                        const MachineBasicBlock *mbb) const {
      return li.liveAt(getMBBEndIdx(mbb).getPrevSlot());
    }

    MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
      return indexes_->getMBBFromIndex(index);
    }

    SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
      return indexes_->insertMachineInstrInMaps(MI);
    }

    void RemoveMachineInstrFromMaps(MachineInstr *MI) {
      indexes_->removeMachineInstrFromMaps(MI);
    }

    void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
      indexes_->replaceMachineInstrInMaps(MI, NewMI);
    }

    bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
                        SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
      return indexes_->findLiveInMBBs(Start, End, MBBs);
    }

    VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }

    virtual void getAnalysisUsage(AnalysisUsage &AU) const;
    virtual void releaseMemory();

    /// runOnMachineFunction - pass entry point
    virtual bool runOnMachineFunction(MachineFunction&);

    /// print - Implement the dump method.
    virtual void print(raw_ostream &O, const Module* = 0) const;

    /// isReMaterializable - Returns true if every definition of MI of every
    /// val# of the specified interval is re-materializable. Also returns true
    /// by reference if all of the defs are load instructions.
    bool isReMaterializable(const LiveInterval &li,
                            const SmallVectorImpl<LiveInterval*> *SpillIs,
                            bool &isLoad);

    /// intervalIsInOneMBB - If LI is confined to a single basic block, return
    /// a pointer to that block.  If LI is live in to or out of any block,
    /// return NULL.
    MachineBasicBlock *intervalIsInOneMBB(const LiveInterval &LI) const;

    /// addKillFlags - Add kill flags to any instruction that kills a virtual
    /// register.
    void addKillFlags();

    /// handleMove - call this method to notify LiveIntervals that
    /// instruction 'mi' has been moved within a basic block. This will update
    /// the live intervals for all operands of mi. Moves between basic blocks
    /// are not supported.
    void handleMove(MachineInstr* MI);

    /// moveIntoBundle - Update intervals for operands of MI so that they
    /// begin/end on the SlotIndex for BundleStart.
    ///
    /// Requires MI and BundleStart to have SlotIndexes, and assumes
    /// existing liveness is accurate. BundleStart should be the first
    /// instruction in the Bundle.
    void handleMoveIntoBundle(MachineInstr* MI, MachineInstr* BundleStart);

    // Register mask functions.
    //
    // Machine instructions may use a register mask operand to indicate that a
    // large number of registers are clobbered by the instruction.  This is
    // typically used for calls.
    //
    // For compile time performance reasons, these clobbers are not recorded in
    // the live intervals for individual physical registers.  Instead,
    // LiveIntervalAnalysis maintains a sorted list of instructions with
    // register mask operands.

    /// getRegMaskSlots - Returns a sorted array of slot indices of all
    /// instructions with register mask operands.
    ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; }

    /// getRegMaskSlotsInBlock - Returns a sorted array of slot indices of all
    /// instructions with register mask operands in the basic block numbered
    /// MBBNum.
    ArrayRef<SlotIndex> getRegMaskSlotsInBlock(unsigned MBBNum) const {
      std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
      return getRegMaskSlots().slice(P.first, P.second);
    }

    /// getRegMaskBits() - Returns an array of register mask pointers
    /// corresponding to getRegMaskSlots().
    ArrayRef<const uint32_t*> getRegMaskBits() const { return RegMaskBits; }

    /// getRegMaskBitsInBlock - Returns an array of mask pointers corresponding
    /// to getRegMaskSlotsInBlock(MBBNum).
    ArrayRef<const uint32_t*> getRegMaskBitsInBlock(unsigned MBBNum) const {
      std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
      return getRegMaskBits().slice(P.first, P.second);
    }

    /// checkRegMaskInterference - Test if LI is live across any register mask
    /// instructions, and compute a bit mask of physical registers that are not
    /// clobbered by any of them.
    ///
    /// Returns false if LI doesn't cross any register mask instructions. In
    /// that case, the bit vector is not filled in.
    bool checkRegMaskInterference(LiveInterval &LI,
                                  BitVector &UsableRegs);

  private:
    /// computeIntervals - Compute live intervals.
    void computeIntervals();

    /// handleRegisterDef - update intervals for a register def
    /// (calls handlePhysicalRegisterDef and
    /// handleVirtualRegisterDef)
    void handleRegisterDef(MachineBasicBlock *MBB,
                           MachineBasicBlock::iterator MI,
                           SlotIndex MIIdx,
                           MachineOperand& MO, unsigned MOIdx);

    /// isPartialRedef - Return true if the specified def at the specific index
    /// is partially re-defining the specified live interval. A common case of
    /// this is a definition of the sub-register.
    bool isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
                        LiveInterval &interval);

    /// handleVirtualRegisterDef - update intervals for a virtual
    /// register def
    void handleVirtualRegisterDef(MachineBasicBlock *MBB,
                                  MachineBasicBlock::iterator MI,
                                  SlotIndex MIIdx, MachineOperand& MO,
                                  unsigned MOIdx,
                                  LiveInterval& interval);

    /// handlePhysicalRegisterDef - update intervals for a physical register
    /// def.
    void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
                                   MachineBasicBlock::iterator mi,
                                   SlotIndex MIIdx, MachineOperand& MO,
                                   LiveInterval &interval);

    /// handleLiveInRegister - Create interval for a livein register.
    void handleLiveInRegister(MachineBasicBlock* mbb,
                              SlotIndex MIIdx,
                              LiveInterval &interval);

    /// getReMatImplicitUse - If the remat definition MI has one (for now, we
    /// only allow one) virtual register operand, then its uses are implicitly
    /// using the register. Returns the virtual register.
    unsigned getReMatImplicitUse(const LiveInterval &li,
                                 MachineInstr *MI) const;

    /// isValNoAvailableAt - Return true if the val# of the specified interval
    /// which reaches the given instruction also reaches the specified use
    /// index.
    bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
                            SlotIndex UseIdx) const;

    /// isReMaterializable - Returns true if the definition MI of the specified
    /// val# of the specified interval is re-materializable. Also returns true
    /// by reference if the def is a load.
    bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
                            MachineInstr *MI,
                            const SmallVectorImpl<LiveInterval*> *SpillIs,
                            bool &isLoad);

    static LiveInterval* createInterval(unsigned Reg);

    void printInstrs(raw_ostream &O) const;
    void dumpInstrs() const;

    class HMEditor;
  };
} // End llvm namespace

#endif


text:
class EnvelopeBuilder
  attr_reader :params, :envelope, :envelope_community, :errors

  # Params:
  #   - params: [Hash] containing the envelope attributes
  #   - update_if_exists: [Bool] tells if we should update or create a new obj
  def initialize(params, envelope: nil, update_if_exists: false,
                 skip_validation: false)
    @params = sanitize(params)
    @envelope = envelope
    @update_if_exists = update_if_exists
    @skip_validation = skip_validation
    @envelope_community = @params[:envelope_community]
  end

  # Validate and build the envelope
  #
  # Return: [List] containing [envelope, errors]
  #
  # Example:
  #   envelope, errors = EnvelopeBuilder.new(params).build
  def build
    validate
    envelope.save if valid?
    [envelope, errors]
  end

  # Run all validations:
  #   - envelope json schema
  #   - ActiveRecord model
  #   - resource json schema (encapsulated on the AR model validations)
  #
  # Return: [Boolean]
  def validate
    validate_envelope
    if valid?
      build_envelope
      validate_model unless skip_validation?
    end
    valid?
  end

  # List of allowed params to be passed on the Envelope construction
  #
  # Return: [List[Symbol]] list of field names
  def self.allowed_params
    @allowed_params ||= begin
      Envelope.column_names.map(&:to_sym) # + [:envelope_community]
    end
  end

  def allowed_params
    self.class.allowed_params
  end

  private

  def validate_envelope
    validator = JSONSchemaValidator.new params, :envelope
    validator.validate
    errors_set validator.error_messages
    valid?
  end

  def validate_model
    envelope.validate
    errors_set envelope.errors.full_messages
    valid?
  end

  def errors_set(errs)
    @errors = errs.nil? || errs.empty? ? nil : errs
  end

  def valid?
    @errors.nil? || @errors.try(:empty?)
  end

  def update_if_exists?
    @update_if_exists
  end

  def skip_validation?
    @skip_validation && @envelope.community.skip_validation_enabled?
  end

  def build_envelope
    @envelope ||= existing_or_new_envelope
    @envelope.assign_community(envelope_community)
    @envelope.assign_attributes(params.slice(*allowed_params))

    @envelope = existing_envelope(@envelope)

    @envelope.skip_validation = true if skip_validation?
    @envelope
  end

  def existing_or_new_envelope
    if update_if_exists?
      Envelope.find_or_initialize_by(envelope_id: params[:envelope_id])
    else
      Envelope.new
    end
  end

  def existing_envelope(envelope)
    id = envelope.process_resource['@id']
    old_envelope = Envelope.community_resource('ce_registry', id)

    if old_envelope
      old_envelope.assign_attributes(params.slice(*allowed_params))
      old_envelope
    else
      envelope
    end
  end

  def sanitize(params)
    params.with_indifferent_access.compact.delete_if { |_k, v| v.try(:blank?) }
  end
end


text:
[![Build Status](https://dev.azure.com/blueveyoud/BibTeXLibrary/_apis/build/status/BERef.BibTeXLibrary?branchName=master)](https://dev.azure.com/blueveyoud/BibTeXLibrary/_build/latest?definitionId=2&branchName=master)
![Nuget](https://img.shields.io/nuget/v/BERef.BibTeXTools.svg)

A utility library for BibTeX written in C#.

## Installation
We recommand install this package via NuGet.
```
Install-Package BERef.BibTeXTools
```
For more information, please ref to [NuGet Gallery | BERef.BibTeXTools](https://www.nuget.org/packages/BERef.BibTeXTools/)

## Usage at a glance

- string -> BibEntry
```csharp
var parser = new BibParser(
                new StringReader(
                  "@article{keyword, title = {\"0\"{123}456{789}}, year = 2012, address=\"PingLeYuan\"}"));
var entry = parser.GetAllResult()[0];
```

- BibEntry
```csharp
// Get Property
entry.Type;       // string: Article
entry.Title;      // string: 0{123}456{789}
entry["Title"];   // string: 0{123}456{789}
```

- BibEntry -> string
```csharp
entry.ToString();
// @Article{keyword,
//   title = {0{123}456{789}},
//   year = {2012},
//   address = {PingLeYuan},
// }
```

- Local File -> BibEntries
```csharp
var parser = new BibParser(new StreamReader("text.bib", Encoding.Default));
var entries = parser.GetAllResult();

foreach(var entry in entries) { ... }
```

## License

The MIT License (MIT)
Copyright (c) 2016 BERef

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
package org.hibernate.test.jpa.proxy;

import javax.persistence.EntityNotFoundException;

import junit.framework.AssertionFailedError;
import org.junit.Test;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.test.jpa.AbstractJPATest;
import org.hibernate.test.jpa.Item;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

/**
 * Test relation between proxies and get()/load() processing
 * and make sure the interactions match the ejb3 expectations
 *
 * @author Steve Ebersole
 */
public class JPAProxyTest extends AbstractJPATest {
	@Test
	public void testEjb3ProxyUsage() {
		Session s = openSession();
		Transaction txn = s.beginTransaction();

		Item item = ( Item ) s.load( Item.class, new Long(-1) );
		assertFalse( Hibernate.isInitialized( item ) );
		try {
			Hibernate.initialize( item );
			fail( "proxy access did not fail on non-existent proxy" );
		}
		catch ( EntityNotFoundException e ) {
			// expected behavior
		}
		catch ( Throwable t ) {
			fail( "unexpected exception type on non-existent proxy access : " + t );
		}

		s.clear();

		Item item2 = ( Item ) s.load( Item.class, new Long(-1) );
		assertFalse( Hibernate.isInitialized( item2 ) );
		assertFalse( item == item2 );
		try {
			item2.getName();
			fail( "proxy access did not fail on non-existent proxy" );
		}
		catch ( EntityNotFoundException e ) {
			// expected behavior
		}
		catch ( Throwable t ) {
			fail( "unexpected exception type on non-existent proxy access : " + t );
		}

		txn.commit();
		s.close();
	}

	/**
	 * The ejb3 find() method maps to the Hibernate get() method
	 */
	@Test
	public void testGetSemantics() {
		Long nonExistentId = new Long( -1 );
		Session s = openSession();
		Transaction txn = s.beginTransaction();
		Item item = ( Item ) s.get( Item.class, nonExistentId );
		assertNull( "get() of non-existent entity did not return null", item );
		txn.commit();
		s.close();

		s = openSession();
		txn = s.beginTransaction();
		// first load() it to generate a proxy...
		item = ( Item ) s.load( Item.class, nonExistentId );
		assertFalse( Hibernate.isInitialized( item ) );
		// then try to get() it to make sure we get an exception
		try {
			s.get( Item.class, nonExistentId );
			fail( "force load did not fail on non-existent entity" );
		}
		catch ( EntityNotFoundException e ) {
			// expected behavior
		}
		catch( AssertionFailedError e ) {
			throw e;
		}
		catch ( Throwable t ) {
			fail( "unexpected exception type on non-existent entity force load : " + t );
		}
		txn.commit();
		s.close();
	}
}


text:
// Implement the following operations of a stack using queues.
//
//
// push(x) -- Push element x onto stack.
//
//
// pop() -- Removes the element on top of the stack.
//
//
// top() -- Get the top element.
//
//
// empty() -- Return whether the stack is empty.
//
//
// Notes:
//
// You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.
// Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
// You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
//
//
//
// Credits:Special thanks to @jianchao.li.fighter for adding this problem and all test cases.

class MyStack {
    queue<int> q;
public:
    /** Initialize your data structure here. */
    MyStack()
    {

    }

    /** Push element x onto stack. */
    void push(int x)
    {
        q.push(x);
        int n = q.size();
        while (--n) {
            q.push(q.front());
            q.pop();
        }
    }

    /** Removes the element on top of the stack and returns that element. */
    int pop()
    {
        int ans = q.front();
        q.pop();
        return ans;
    }

    /** Get the top element. */
    int top() const
    {
        return q.front();
    }

    /** Returns whether the stack is empty. */
    bool empty() const
    {
        return q.empty();
    }
};
/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * bool param_4 = obj.empty();
 */


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;

namespace Microsoft.Diagnostics.Runtime.Interop
{
    [Flags]
    public enum DEBUG_STACK : uint
    {
        ARGUMENTS = 0x1,
        FUNCTION_INFO = 0x2,
        SOURCE_LINE = 0x4,
        FRAME_ADDRESSES = 0x8,
        COLUMN_NAMES = 0x10,
        NONVOLATILE_REGISTERS = 0x20,
        FRAME_NUMBERS = 0x40,
        PARAMETERS = 0x80,
        FRAME_ADDRESSES_RA_ONLY = 0x100,
        FRAME_MEMORY_USAGE = 0x200,
        PARAMETERS_NEWLINE = 0x400,
        DML = 0x800,
        FRAME_OFFSETS = 0x1000
    }
}


text:
@interface CCSBandAreaChart : CCSLineChart {
    CCFloat _areaAlpha;
}

@property(assign, nonatomic) CCFloat areaAlpha;

@end


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>CSS Text Test: overflow-wrap: anywhere and intrinsic sizing</title>
<link rel="author" title="Xidorn Quan" href="https://www.upsuper.org/">
<link rel="author" title="Mozilla" href="https://www.mozilla.org/">
<link rel="help" href="https://drafts.csswg.org/css-text-3/#overflow-wrap-property">
<meta name="flags" content="">
<link rel="match" href="reference/overflow-wrap-min-content-size-002-ref.html">
<meta name="assert" content="overflow-wrap:anywhere doesn't break grapheme cluster and min-content intrinsic size should take that into account.">

Test passes if the glyphs are completely inside the blue box.

நிிிிநிிிி


text:
"""

Created on Wed Mar 13 13:06:14 2013

Author: Josef Perktold
"""

from statsmodels.stats.power import TTestPower, TTestIndPower, tt_solve_power

if __name__ == '__main__':
    effect_size, alpha, power = 0.5, 0.05, 0.8

    ttest_pow = TTestPower()
    print('\nroundtrip - root with respect to all variables')
    print('\n       calculated, desired')

    nobs_p = ttest_pow.solve_power(effect_size=effect_size, nobs=None, alpha=alpha, power=power)
    print('nobs  ', nobs_p)
    print('effect', ttest_pow.solve_power(effect_size=None, nobs=nobs_p, alpha=alpha, power=power), effect_size)

    print('alpha ', ttest_pow.solve_power(effect_size=effect_size, nobs=nobs_p, alpha=None, power=power), alpha)
    print('power  ', ttest_pow.solve_power(effect_size=effect_size, nobs=nobs_p, alpha=alpha, power=None), power)

    print('\nroundtrip - root with respect to all variables')
    print('\n       calculated, desired')

    print('nobs  ', tt_solve_power(effect_size=effect_size, nobs=None, alpha=alpha, power=power), nobs_p)
    print('effect', tt_solve_power(effect_size=None, nobs=nobs_p, alpha=alpha, power=power), effect_size)

    print('alpha ', tt_solve_power(effect_size=effect_size, nobs=nobs_p, alpha=None, power=power), alpha)
    print('power  ', tt_solve_power(effect_size=effect_size, nobs=nobs_p, alpha=alpha, power=None), power)

    print('\none sided')
    nobs_p1 = tt_solve_power(effect_size=effect_size, nobs=None, alpha=alpha, power=power, alternative='larger')
    print('nobs  ', nobs_p1)
    print('effect', tt_solve_power(effect_size=None, nobs=nobs_p1, alpha=alpha, power=power, alternative='larger'), effect_size)
    print('alpha ', tt_solve_power(effect_size=effect_size, nobs=nobs_p1, alpha=None, power=power, alternative='larger'), alpha)
    print('power  ', tt_solve_power(effect_size=effect_size, nobs=nobs_p1, alpha=alpha, power=None, alternative='larger'), power)

    #start_ttp = dict(effect_size=0.01, nobs1=10., alpha=0.15, power=0.6)

    ttind_solve_power = TTestIndPower().solve_power

    print('\nroundtrip - root with respect to all variables')
    print('\n       calculated, desired')

    nobs_p2 = ttind_solve_power(effect_size=effect_size, nobs1=None, alpha=alpha, power=power)
    print('nobs  ', nobs_p2)
    print('effect', ttind_solve_power(effect_size=None, nobs1=nobs_p2, alpha=alpha, power=power), effect_size)
    print('alpha ', ttind_solve_power(effect_size=effect_size, nobs1=nobs_p2, alpha=None, power=power), alpha)
    print('power  ', ttind_solve_power(effect_size=effect_size, nobs1=nobs_p2, alpha=alpha, power=None), power)
    print('ratio  ', ttind_solve_power(effect_size=effect_size, nobs1=nobs_p2, alpha=alpha, power=power, ratio=None), 1)

    print('\ncheck ratio')
    print('smaller power', ttind_solve_power(effect_size=effect_size, nobs1=nobs_p2, alpha=alpha, power=0.7, ratio=None), '< 1')
    print('larger power ', ttind_solve_power(effect_size=effect_size, nobs1=nobs_p2, alpha=alpha, power=0.9, ratio=None), '> 1')


text:
package io.pivotal.spring.cloud.service.eureka;

import java.util.logging.Logger;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

final class SanitizingEurekaInstanceConfigBean extends EurekaInstanceConfigBean implements InitializingBean {

	private static Logger LOGGER = Logger.getLogger(SanitizingEurekaInstanceConfigBean.class.getName());

	public SanitizingEurekaInstanceConfigBean(InetUtils inetUtils) {
		super(inetUtils);
	}

	@Override
	public void setEnvironment(Environment environment) {
		super.setEnvironment(environment);
		// set some defaults from the environment, but allow the defaults to use
		// relaxed binding
		String springAppName = getSpringApplicationName();
		String eurekaInstanceAppname = getEurekaInstanceAppnameProperty();
		if (StringUtils.hasText(eurekaInstanceAppname)) {
			// default to eureka.instance.appname if defined
			setVirtualHostName(eurekaInstanceAppname);
			setSecureVirtualHostName(eurekaInstanceAppname);
		} else if (StringUtils.hasText(springAppName)) {
			// default to a hostname-sanitized spring application name
			String sanitizedAppName = sanitizeHostname(springAppName);
			if (!springAppName.equals(sanitizedAppName)) {
				LOGGER.warning("Spring application name '" + springAppName
						+ "' was sanitized to produce eureka.instance.appname '" + sanitizedAppName + "'");
			}
			setAppname(sanitizedAppName);
			setVirtualHostName(sanitizedAppName);
			setSecureVirtualHostName(sanitizedAppName);
		}
	}

	private String getSpringApplicationName() {

		return Binder.get(getEnvironment()).bind("spring.application.name", String.class).orElse(null);
	}

	private String getEurekaInstanceAppnameProperty() {
		return Binder.get(getEnvironment()).bind("eureka.instance.appname", String.class).orElse(null);
	}

	// RFC 952 defines the valid character set for hostnames.
	private String sanitizeHostname(String hostname) {
		if (hostname == null) {
			return null;
		}
		return hostname.replaceAll("[^0-9a-zA-Z\\-\\.]", "-");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		// don't call super, it's a bug in Camden.SR1-2
		String messageSuffix = "' is set to a different value than eureka.instance.appname '" + getAppname()
				+ "', and is disallowed in Spring Cloud Services. Try only setting eureka.instance.appname."
				+ " Please refer to our documentation and reach out to us if you think you require different values.";
		if (StringUtils.hasText(getVirtualHostName()) && !getVirtualHostName().equalsIgnoreCase(getAppname())) {
			throw new IllegalArgumentException(
					"eureka.instance.virtualHostName '" + getVirtualHostName() + messageSuffix);
		}
		if (StringUtils.hasText(getSecureVirtualHostName()) && !getSecureVirtualHostName().equalsIgnoreCase(getAppname())) {
			throw new IllegalArgumentException(
					"eureka.instance.secureVirtualHostName '" + getSecureVirtualHostName() + messageSuffix);
		}
	}

}


text:
/*
 * Instances Configuration
 */

quarry.config(['$stateProvider', function($stateProvider) {

    // make sure we have a user before allowing access to the rest of the app
    if (!window.user) {
        return
    }

    // Set up them states
    $stateProvider

        //
        // Import States
        //

        .state('instances', {
            url: '/instances',
            templateUrl: '/static/app/instances/partials/base.html',
        })

        //
        // Wizard States
        //

        .state('instances.overview', {
            url: '/overview',
            templateUrl: '/static/app/instances/partials/overview.html',
            controller: 'InstancesOverviewController'
        })
        .state('instances.wizard', {
            url: '/wizard',
            templateUrl: '/static/app/instances/partials/wizard.html',
            controller: 'InstancesWizardController'
        })

}])

/*
 * Jaunt Factory
 */

quarry.factory("RedShirt", ['$http', '$timeout', function($http, $timeout) {

    return {

        instances: function() {
            return $http.get("/api/redshirt/instances")
        },

        spots: function() {
            return $http.get("/api/redshirt/spots")
        },

        clusters: function() {
            return $http.get("/api/redshirt/clusters")
        },

        setClusterWorkers: function(cluster, workers) {
            return $http.post("/api/redshirt/cluster/" + cluster + "/workers/" + workers)
        },

        getStreamers: function() {
            return $http.get("/api/redshirt/streamers")
        },

        shutdownCluster: function(clusterName) {
            return $http.post("/api/redshirt/cluster/"+clusterName+"/shutdown")
        },

        stopCluster: function(clusterName) {
            return $http.post("/api/redshirt/cluster/"+clusterName+"/stop")
        },

        startCluster: function(clusterName) {
            return $http.post("/api/redshirt/cluster/"+clusterName+"/start")
        },

        rebootCluster: function(clusterName) {
            return $http.post("/api/redshirt/cluster/"+clusterName+"/reboot")
        },

        prices: function() {
            return $http.get("/api/redshirt/prices")
        },

        terminateInstance: function(id) {
            return $http.post("/api/redshirt/instance/"+id+"/terminate")
        },

        cancelSpotRequest: function(id) {
            return $http.post("/api/redshirt/spot/"+id+"/cancel")
        },

        launch: function(opts) {
            return $http.post("/api/redshirt/launch", opts)
        },

        launchCluster: function(opts) {
            return $http.post("/api/redshirt/launch/cluster", opts)
        }

    }

}])

/*
 * RedShirt Controllers
 */

quarry.controller('InstancesOverviewController', ["RedShirt", "$scope", "$timeout", function(RedShirt, $scope, $timeout) {

    var clusterTimer;

    $scope.$on('destroy', function() {
        $timeout.cancel(clusterTimer)
    })

    $scope.loadingClusters = true

    var loadClusters = function() {

        RedShirt.clusters()
            .success(function(res) {
                if (Object.keys(res.clusters).length) {
                    $scope.clusters = res.clusters
                }
            })
            .error(function(res) {

            })
            .finally(function() {
                $scope.loadingClusters = false

                // TODO need a global place for setting timer durations
                clusterTimer = $timeout(loadClusters, 5000)
            })

    }
    loadClusters()

    $scope.editingWorkers = {}
    $scope.alterWorkers = function(id, workers) {
        $scope.editingWorkers[id] = {
            "workers": workers,
            "altering": false
        }
    }

    $scope.updateWorkers = function(id) {

        $scope.editingWorkers[id].altering = true

        RedShirt.setClusterWorkers(id, $scope.editingWorkers[id].workers)
            .finally(function() {
                delete $scope.editingWorkers[id]
                $timeout.cancel(clusterTimer)
                loadClusters()
            })

    }

    $scope.cancelUpdateWorkers = function(id) {
        delete $scope.editingWorkers[id]
    }

    $scope.shutdownCluster = function(clusterName) {
        RedShirt.shutdownCluster(clusterName)
        delete $scope.clusters[clusterName]
    }

    $scope.rebootCluster = function(clusterName) {
        RedShirt.rebootCluster(clusterName)
            .finally(function() {
                $timeout.cancel(clusterTimer)
                loadClusters()
            })
    }

    $scope.stopCluster = function(clusterName) {
        RedShirt.stopCluster(clusterName)
            .finally(function() {
                $timeout.cancel(clusterTimer)
                loadClusters()
            })
    }

    $scope.startCluster = function(clusterName) {
        RedShirt.startCluster(clusterName)
            .finally(function() {
                $timeout.cancel(clusterTimer)
                loadClusters()
            })
    }

    $scope.terminateInstance = function(id) {
        RedShirt.terminateInstance(id)
    }

    $scope.cancelSpotRequest = function(id) {
        RedShirt.cancelSpotRequest(id)
    }

}])

quarry.controller('InstancesWizardController', ["RedShirt", "$scope", function(RedShirt, $scope) {

    $scope.workers = 1
    $scope.clusterName = ''
    $scope.spot = false

    $scope.dismissError = function() {
        delete $scope.error
    }

    $scope.launchCluster = function(clusterName, workers, spot) {

        delete $scope.error

        if (isNaN(parseInt(workers))) {
            $scope.error = "You must enter a valid number of workers to launch!"
            return
        }

        $scope.launching = true

        var opts = {
            clusterName: clusterName,
            workers: workers
        }

        if (spot) {
            opts.spot = true
        }

        RedShirt.launchCluster(opts)
            .success(function(res) {
                location.hash = "/instances/overview"
            })
            .error(function(res) {
                $scope.error = res.error
            })
            .finally(function() {
                $scope.launching = false
            })

   }

}])


text:
namespace libcryptmg{
	namespace crypto{
		struct aes;

		class aes_encryptor
		{
			friend struct aes;
			using crypto_store = ::libcryptmg::core::crypto_vector;
			using crypto_iter = crypto_store::iterator;
			using const_crypto_iter = crypto_store::const_iterator;
			const crypto_store block_keys;
			const int number_of_rounds;
			aes_encryptor(crypto_store && key, int num_rounds);
			aes_encryptor(const aes_encryptor&) = delete;
			aes_encryptor& operator=(const aes_encryptor&) = delete;
			aes_encryptor& operator=(aes_encryptor&&) = delete;
		public:
			aes_encryptor(aes_encryptor&&);
			void operator()(const_crypto_iter begin, crypto_iter out);
		};

		class aes_decryptor
		{
			friend struct aes;
			using key_store = ::libcryptmg::core::crypto_vector;
			const key_store block_keys;
			aes_decryptor(key_store && key);
			aes_decryptor(const aes_decryptor&) = delete;
			aes_decryptor& operator=(const aes_decryptor&) = delete;
		public:
			::libcryptmg::core::crypto_vector operator()(const ::libcryptmg::core::crypto_vector &);
		};

		struct aes
		{
			using key_store = ::libcryptmg::core::crypto_vector;
		public:
			static aes_encryptor create_encryptor(const key_store & key);
			static aes_decryptor create_decryptor(const key_store & key);
		};

		using aes_encryptor_with_cbc = ::libcryptmg::crypto::running_modes::cipher_block_chaining < aes > ;
	}
}

#endif //LIBCRYPTMG_AES_HPP


text:
package org.springframework.security.integration;

import jakarta.servlet.http.HttpSession;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import static org.assertj.core.api.Assertions.assertThat;

@ContextConfiguration(locations = { "/http-extra-fsi-app-context.xml" })
@ExtendWith(SpringExtension.class)
public class HttpNamespaceWithMultipleInterceptorsTests {

	@Autowired
	private FilterChainProxy fcp;

	@Test
	public void requestThatIsMatchedByDefaultInterceptorIsAllowed() throws Exception {
		MockHttpServletRequest request = new MockHttpServletRequest();
		request.setMethod("GET");
		request.setServletPath("/somefile.html");
		request.setSession(createAuthenticatedSession("ROLE_0", "ROLE_1", "ROLE_2"));
		MockHttpServletResponse response = new MockHttpServletResponse();
		this.fcp.doFilter(request, response, new MockFilterChain());
		assertThat(response.getStatus()).isEqualTo(200);
	}

	@Test
	public void securedUrlAccessIsRejectedWithoutRequiredRole() throws Exception {
		MockHttpServletRequest request = new MockHttpServletRequest();
		request.setMethod("GET");

		request.setServletPath("/secure/somefile.html");
		request.setSession(createAuthenticatedSession("ROLE_0"));
		MockHttpServletResponse response = new MockHttpServletResponse();
		this.fcp.doFilter(request, response, new MockFilterChain());
		assertThat(response.getStatus()).isEqualTo(403);
	}

	public HttpSession createAuthenticatedSession(String... roles) {
		MockHttpSession session = new MockHttpSession();
		SecurityContextHolder.getContext()
				.setAuthentication(new TestingAuthenticationToken("bob", "bobspassword", roles));
		session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
				SecurityContextHolder.getContext());
		SecurityContextHolder.clearContext();
		return session;
	}

}


text:
#ifndef BOOST_PHOENIX_FUNCTION_HPP
#define BOOST_PHOENIX_FUNCTION_HPP

#include <boost/phoenix/version.hpp>
#include <boost/phoenix/function/function.hpp>
#include <boost/phoenix/function/adapt_callable.hpp>
#include <boost/phoenix/function/adapt_function.hpp>

#endif


text:
const Idea = require ('../lib/idea');
const assert = require('assert');
const $ = require('jquery');

describe('my idea', function() {
  it('should instantiate with a title', function() {
    let idea = new Idea({ title: 'title', body: 'body'});
    assert.equal(idea.title, 'title');
  });

  it('should instantiate with a body', function() {
    let idea = new Idea({ title: 'title', body: 'body'});

    assert.equal(idea.body, 'body');
  });

  it('should have a render method', function() {
    let idea = new Idea({ title: 'title', body: 'body'});
    assert(idea.render);
  });

  it('should render an element with an H2', function() {
    let idea = new Idea({ title: 'title', body: 'body'});
    let renderedIdea = idea.render();

    assert.equal(renderedIdea.find('h2').length, 1);
  });

  it('should render an H2 with the title', function() {
    let idea = new Idea({ title: 'title', body: 'body'});
    let renderedIdea = idea.render();

    assert.equal(renderedIdea.find('h2').html(), 'title');
  });

  describe('renderAndAppendTo method', function() {
    beforeEach(function() {
      this.ideas = $('

').addClass('ideas');
      sinon.spy(Idea.prototype, 'render');
    });

    afterEach(function() {
      this.ideas.empty();
      Idea.prototype.render.restore();
    });

    it('should have a renderAndAppendTo method', function() {
      let idea = new Idea({ title: 'title', body: 'body'});
      assert(idea.renderAndAppendTo);
    });

    it('should delegate to Idea.prototype.render', function() {
      let idea = new Idea({ title: 'title', body: 'body'});
      idea.renderAndAppendTo(this.ideas);

      assert(idea.render.calledOnce);
    });

    it('should renderAndAppendTo to a target', function() {
      let idea = new Idea({ title: 'title', body: 'body'});
      let container = this.ideas;

      idea.renderAndAppendTo(container);

      assert.equal(container.find('.idea').length, 1);
    });
  });

  describe('Idea.all', function() {
    beforeEach(function() {
      this.xhr = sinon.useFakeXMLHttpRequest();
      var requests = this.requests = [];
      this.xhr.oncreate = function(request) {
        requests.push(request);
      }
    });

    afterEach(function() {
      this.xhr.restore();
    });

    it('should fire a requst to /api/v1/ideas', function() {
      Idea.all();
      debugger;
      assert.equal(requests[0].url, '/api/v1/ideas');
      assert.equal(requests[0].method, 'GET');
    });

    // it('should fetch an array of ideas', function(done) {
    //   Idea.all(function(ideas) {
    //     assert(Array.isArray(ideas));
    //     done();
    //   });
    // });
  });
});


text:
package org.apache.cassandra.streaming;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.io.sstable.SSTableReader;
import org.apache.cassandra.utils.FBUtilities;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

public class StreamTransferTaskTest extends SchemaLoader
{
    @Test
    public void testScheduleTimeout() throws Exception
    {
        String ks = "Keyspace1";
        String cf = "Standard1";

        StreamSession session = new StreamSession(FBUtilities.getBroadcastAddress(), 0);
        ColumnFamilyStore cfs = Keyspace.open(ks).getColumnFamilyStore(cf);

        // create two sstables
        for (int i = 0; i < 2; i++)
        {
            insertData(ks, cf, i, 1);
            cfs.forceBlockingFlush();
        }

        // create streaming task that streams those two sstables
        StreamTransferTask task = new StreamTransferTask(session, cfs.metadata.cfId);
        for (SSTableReader sstable : cfs.getSSTables())
        {
            List<Range<Token>> ranges = new ArrayList<>();
            ranges.add(new Range<>(sstable.first.getToken(), sstable.last.getToken()));
            task.addTransferFile(sstable, 1, sstable.getPositionsForRanges(ranges), 0);
        }
        assertEquals(2, task.getTotalNumberOfFiles());

        // if file sending completes before timeout then the task should be canceled.
        ScheduledFuture f = task.scheduleTimeout(0, 1, TimeUnit.SECONDS);
        task.complete(0);
        // timeout task may run after complete but it is noop
        f.get();

        // when timeout runs on second file, task should be completed
        f = task.scheduleTimeout(1, 1, TimeUnit.MILLISECONDS);
        f.get();
        assertEquals(StreamSession.State.WAIT_COMPLETE, session.state());

        // when all streaming are done, time out task should not be scheduled.
        assertNull(task.scheduleTimeout(1, 1, TimeUnit.SECONDS));
    }
}


text:
from __future__ import unicode_literals

import os
import sys
import locale
from itertools import chain
from six import iterkeys, iteritems
from six.moves.configparser import ConfigParser

from bpython.keys import cli_key_dispatch as key_dispatch
from bpython.autocomplete import SIMPLE as default_completion
import bpython.autocomplete

class Struct(object):
    """Simple class for instantiating objects we can add arbitrary attributes
    to and use for various arbitrary things."""

def getpreferredencoding():
    """Get the user's preferred encoding."""
    return locale.getpreferredencoding() or sys.getdefaultencoding()

def can_encode(c):
    try:
        c.encode(getpreferredencoding())
        return True
    except UnicodeEncodeError:
        return False

def supports_box_chars():
    """Check if the encoding supports Unicode box characters."""
    return all(map(can_encode, u'│─└┘┌┐'))

def get_config_home():
    """Returns the base directory for bpython's configuration files."""
    xdg_config_home = os.environ.get('XDG_CONFIG_HOME', '~/.config')
    return os.path.join(xdg_config_home, 'bpython')

def default_config_path():
    """Returns bpython's default configuration file path."""
    return os.path.join(get_config_home(), 'config')

def fill_config_with_default_values(config, default_values):
    for section in iterkeys(default_values):
        if not config.has_section(section):
            config.add_section(section)

        for (opt, val) in iteritems(default_values[section]):
            if not config.has_option(section, opt):
                config.set(section, opt, '%s' % (val, ))

def loadini(struct, configfile):
    """Loads .ini configuration file and stores its values in struct"""

    config_path = os.path.expanduser(configfile)

    config = ConfigParser()
    defaults = {
        'general': {
            'arg_spec': True,
            'auto_display_list': True,
            'autocomplete_mode': default_completion,
            'color_scheme': 'default',
            'complete_magic_methods': True,
            'dedent_after': 1,
            'editor': os.environ.get('VISUAL', os.environ.get('EDITOR', 'vi')),
            'flush_output': True,
            'highlight_show_source': True,
            'hist_duplicates': True,
            'hist_file': '~/.pythonhist',
            'hist_length': 100,
            'paste_time': 0.02,
            'pastebin_confirm': True,
            'pastebin_expiry': '1week',
            'pastebin_helper': '',
            'pastebin_removal_url': 'https://bpaste.net/remove/$removal_id',
            'pastebin_show_url': 'https://bpaste.net/show/$paste_id',
            'pastebin_url': 'https://bpaste.net/json/new',
            'save_append_py': False,
            'single_undo_time': 1.0,
            'syntax': True,
            'tab_length': 4,
            'unicode_box': True
        },
        'keyboard': {
            'backspace': 'C-h',
            'beginning_of_line': 'C-a',
            'clear_line': 'C-u',
            'clear_screen': 'C-l',
            'clear_word': 'C-w',
            'copy_clipboard': 'F10',
            'cut_to_buffer': 'C-k',
            'delete': 'C-d',
            'down_one_line': 'C-n',
            'edit_config': 'F3',
            'edit_current_block': 'C-x',
            'end_of_line': 'C-e',
            'exit': '',
            'external_editor': 'F7',
            'help': 'F1',
            'incremental_search': 'M-s',
            'last_output': 'F9',
            'left': 'C-b',
            'pastebin': 'F8',
            'reimport': 'F6',
            'reverse_incremental_search': 'M-r',
            'right': 'C-f',
            'save': 'C-s',
            'search': 'C-o',
            'show_source': 'F2',
            'suspend': 'C-z',
            'toggle_file_watch': 'F5',
            'transpose_chars': 'C-t',
            'undo': 'C-r',
            'up_one_line': 'C-p',
            'yank_from_buffer': 'C-y'
        },
        'cli': {
            'suggestion_width': 0.8,
            'trim_prompts': False,
        },
        'curtsies': {
            'list_above': False,
            'right_arrow_completion': True,
        }}

    default_keys_to_commands = dict((value, key) for (key, value)
                                    in iteritems(defaults['keyboard']))

    fill_config_with_default_values(config, defaults)
    if not config.read(config_path):
        # No config file. If the user has it in the old place then complain
        if os.path.isfile(os.path.expanduser('~/.bpython.ini')):
            sys.stderr.write("Error: It seems that you have a config file at "
                             "~/.bpython.ini. Please move your config file to "
                             "%s\n" % default_config_path())
            sys.exit(1)

    def get_key_no_doublebind(command):
        default_commands_to_keys = defaults['keyboard']
        requested_key = config.get('keyboard', command)

        try:
            default_command = default_keys_to_commands[requested_key]

            if (default_commands_to_keys[default_command] ==
                    config.get('keyboard', default_command)):
                setattr(struct, '%s_key' % default_command, '')
        except KeyError:
            pass

        return requested_key

    struct.config_path = config_path

    struct.dedent_after = config.getint('general', 'dedent_after')
    struct.tab_length = config.getint('general', 'tab_length')
    struct.auto_display_list = config.getboolean('general',
                                                 'auto_display_list')
    struct.syntax = config.getboolean('general', 'syntax')
    struct.arg_spec = config.getboolean('general', 'arg_spec')
    struct.paste_time = config.getfloat('general', 'paste_time')
    struct.single_undo_time = config.getfloat('general', 'single_undo_time')
    struct.highlight_show_source = config.getboolean('general',
                                                     'highlight_show_source')
    struct.hist_file = config.get('general', 'hist_file')
    struct.editor = config.get('general', 'editor')
    struct.hist_length = config.getint('general', 'hist_length')
    struct.hist_duplicates = config.getboolean('general', 'hist_duplicates')
    struct.flush_output = config.getboolean('general', 'flush_output')

    struct.pastebin_key = get_key_no_doublebind('pastebin')
    struct.copy_clipboard_key = get_key_no_doublebind('copy_clipboard')
    struct.save_key = get_key_no_doublebind('save')
    struct.search_key = get_key_no_doublebind('search')
    struct.show_source_key = get_key_no_doublebind('show_source')
    struct.suspend_key = get_key_no_doublebind('suspend')
    struct.toggle_file_watch_key = get_key_no_doublebind('toggle_file_watch')
    struct.undo_key = get_key_no_doublebind('undo')
    struct.reimport_key = get_key_no_doublebind('reimport')
    struct.reverse_incremental_search_key = get_key_no_doublebind(
        'reverse_incremental_search')
    struct.incremental_search_key = get_key_no_doublebind('incremental_search')
    struct.up_one_line_key = get_key_no_doublebind('up_one_line')
    struct.down_one_line_key = get_key_no_doublebind('down_one_line')
    struct.cut_to_buffer_key = get_key_no_doublebind('cut_to_buffer')
    struct.yank_from_buffer_key = get_key_no_doublebind('yank_from_buffer')
    struct.clear_word_key = get_key_no_doublebind('clear_word')
    struct.backspace_key = get_key_no_doublebind('backspace')
    struct.clear_line_key = get_key_no_doublebind('clear_line')
    struct.clear_screen_key = get_key_no_doublebind('clear_screen')
    struct.delete_key = get_key_no_doublebind('delete')

    struct.left_key = get_key_no_doublebind('left')
    struct.right_key = get_key_no_doublebind('right')
    struct.end_of_line_key = get_key_no_doublebind('end_of_line')
    struct.beginning_of_line_key = get_key_no_doublebind('beginning_of_line')
    struct.transpose_chars_key = get_key_no_doublebind('transpose_chars')
    struct.exit_key = get_key_no_doublebind('exit')
    struct.last_output_key = get_key_no_doublebind('last_output')
    struct.edit_config_key = get_key_no_doublebind('edit_config')
    struct.edit_current_block_key = get_key_no_doublebind('edit_current_block')
    struct.external_editor_key = get_key_no_doublebind('external_editor')
    struct.help_key = get_key_no_doublebind('help')

    struct.pastebin_confirm = config.getboolean('general', 'pastebin_confirm')
    struct.pastebin_url = config.get('general', 'pastebin_url')
    struct.pastebin_show_url = config.get('general', 'pastebin_show_url')
    struct.pastebin_removal_url = config.get('general', 'pastebin_removal_url')
    struct.pastebin_expiry = config.get('general', 'pastebin_expiry')
    struct.pastebin_helper = config.get('general', 'pastebin_helper')

    struct.cli_suggestion_width = config.getfloat('cli',
                                                  'suggestion_width')
    struct.cli_trim_prompts = config.getboolean('cli',
                                                'trim_prompts')

    struct.complete_magic_methods = config.getboolean('general',
                                                      'complete_magic_methods')
    struct.autocomplete_mode = config.get('general', 'autocomplete_mode')
    struct.save_append_py = config.getboolean('general', 'save_append_py')

    struct.curtsies_list_above = config.getboolean('curtsies', 'list_above')
    struct.curtsies_right_arrow_completion = \
        config.getboolean('curtsies', 'right_arrow_completion')

    color_scheme_name = config.get('general', 'color_scheme')

    default_colors = {
        'keyword': 'y',
        'name': 'c',
        'comment': 'b',
        'string': 'm',
        'error': 'r',
        'number': 'G',
        'operator': 'Y',
        'punctuation': 'y',
        'token': 'C',
        'background': 'd',
        'output': 'w',
        'main': 'c',
        'paren': 'R',
        'prompt': 'c',
        'prompt_more': 'g',
        'right_arrow_suggestion': 'K',
    }

    if color_scheme_name == 'default':
        struct.color_scheme = default_colors
    else:
        struct.color_scheme = dict()

        theme_filename = color_scheme_name + '.theme'
        path = os.path.expanduser(os.path.join(get_config_home(),
                                               theme_filename))
        try:
            load_theme(struct, path, struct.color_scheme, default_colors)
        except EnvironmentError:
            sys.stderr.write("Could not load theme '%s'.\n" %
                             (color_scheme_name, ))
            sys.exit(1)

    # expand path of history file
    struct.hist_file = os.path.expanduser(struct.hist_file)

    # verify completion mode
    if struct.autocomplete_mode not in bpython.autocomplete.ALL_MODES:
        struct.autocomplete_mode = default_completion

    # set box drawing characters
    if config.getboolean('general', 'unicode_box') and supports_box_chars():
        struct.left_border = '│'
        struct.right_border = '│'
        struct.top_border = '─'
        struct.bottom_border = '─'
        struct.left_bottom_corner = '└'
        struct.right_bottom_corner = '┘'
        struct.left_top_corner = '┌'
        struct.right_top_corner = '┐'
    else:
        struct.left_border = '|'
        struct.right_border = '|'
        struct.top_border = '-'
        struct.bottom_border = '-'
        struct.left_bottom_corner = '+'
        struct.right_bottom_corner = '+'
        struct.left_top_corner = '+'
        struct.right_top_corner = '+'

def load_theme(struct, path, colors, default_colors):
    theme = ConfigParser()
    with open(path, 'r') as f:
        theme.readfp(f)
    for k, v in chain(theme.items('syntax'), theme.items('interface')):
        if theme.has_option('syntax', k):
            colors[k] = theme.get('syntax', k)
        else:
            colors[k] = theme.get('interface', k)

    # Check against default theme to see if all values are defined
    for k, v in iteritems(default_colors):
        if k not in colors:
            colors[k] = v


text:
package org.schema;

/**
 *
 * Organization: A business corporation.
 *
 * @fullPath Thing > Organization > Corporation
 *
 * @author Texelz (by Onhate)
 *
 */
public class Corporation extends Organization {

	private String tickerSymbol;

	/**
	 * The exchange traded instrument associated with a Corporation object. The
	 * tickerSymbol is expressed as an exchange and an instrument name separated
	 * by a space character. For the exchange component of the tickerSymbol
	 * attribute, we reccommend using the controlled vocaulary of Market
	 * Identifier Codes (MIC) specified in ISO15022.
	 */
	public String getTickerSymbol() {
		return this.tickerSymbol;
	}

	/**
	 * The exchange traded instrument associated with a Corporation object. The
	 * tickerSymbol is expressed as an exchange and an instrument name separated
	 * by a space character. For the exchange component of the tickerSymbol
	 * attribute, we reccommend using the controlled vocaulary of Market
	 * Identifier Codes (MIC) specified in ISO15022.
	 */
	public void setTickerSymbol(String tickerSymbol) {
		this.tickerSymbol = tickerSymbol;
	}
}


text:
package org.elasticsearch.common.compress;

import org.apache.lucene.store.IndexInput;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.settings.Settings;
import org.jboss.netty.buffer.ChannelBuffer;

import java.io.IOException;

/**
 */
public interface Compressor {

    String type();

    void configure(Settings settings);

    boolean isCompressed(BytesReference bytes);

    boolean isCompressed(byte[] data, int offset, int length);

    boolean isCompressed(ChannelBuffer buffer);

    boolean isCompressed(IndexInput in) throws IOException;

    /**
     * Uncompress the provided data, data can be detected as compressed using {@link #isCompressed(byte[], int, int)}.
     */
    byte[] uncompress(byte[] data, int offset, int length) throws IOException;

    /**
     * Compresses the provided data, data can be detected as compressed using {@link #isCompressed(byte[], int, int)}.
     */
    byte[] compress(byte[] data, int offset, int length) throws IOException;

    CompressedStreamInput streamInput(StreamInput in) throws IOException;

    CompressedStreamOutput streamOutput(StreamOutput out) throws IOException;

    /**
     * @deprecated Used for backward comp. since we now use Lucene compressed codec.
     */
    @Deprecated
    CompressedIndexInput indexInput(IndexInput in) throws IOException;
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/privacy/dlp/v2/storage.proto

namespace Google\Cloud\Dlp\V2;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Message defining a list of words or phrases to search for in the data.
 *
 * Generated from protobuf message google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList
 */
class CustomInfoType_Dictionary_WordList extends \Google\Protobuf\Internal\Message
{
    /**
     * Words or phrases defining the dictionary. The dictionary must contain
     * at least one phrase and every phrase must contain at least 2 characters
     * that are letters or digits. [required]
     *
     * Generated from protobuf field repeated string words = 1;
     */
    private $words;

    public function __construct() {
        \GPBMetadata\Google\Privacy\Dlp\V2\Storage::initOnce();
        parent::__construct();
    }

    /**
     * Words or phrases defining the dictionary. The dictionary must contain
     * at least one phrase and every phrase must contain at least 2 characters
     * that are letters or digits. [required]
     *
     * Generated from protobuf field repeated string words = 1;
     * @return \Google\Protobuf\Internal\RepeatedField
     */
    public function getWords()
    {
        return $this->words;
    }

    /**
     * Words or phrases defining the dictionary. The dictionary must contain
     * at least one phrase and every phrase must contain at least 2 characters
     * that are letters or digits. [required]
     *
     * Generated from protobuf field repeated string words = 1;
     * @param string[]|\Google\Protobuf\Internal\RepeatedField $var
     * @return $this
     */
    public function setWords($var)
    {
        $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING);
        $this->words = $arr;

        return $this;
    }

}


text:
package com.cjburkey.shared.installer.system.util;

import javafx.application.Platform;

public class Stop {

	public static final void stop() {
		Log.print("Closing application...");
		Platform.exit();
		return;
	}

	public static final void force(int code) {
		Log.print("Force closing application!");
		Log.print("Close Code: " + code);
		System.exit(code);
		return;
	}

}


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

{% load mezzanine_tags rating_tags future %}

{% block meta_title %}{{ title|default:"Anasayfa" }}{% endblock %}
{% block title %}{{ title }}{% endblock %}

{% block main %}

{% for link in object_list %}

    {% if not profile_user %}{% rating_for link %}{% endif %}
    <div class="link-detail{% if link.rating_sum < 0 %} link-negative{% endif %}">

{{ link.title }}

        {{ link.publish_date|timesince }} önce |
        {{ link.comments_count }} yorum

{% empty %}

{{ no_data }}

{% endfor %}

{% pagination_for object_list "page" "pjax" %}

{% endblock %}


text:
<html>
<head>
<body>
  <div id='container'>
  this is the container and it should be empty when ractive loads
  </div>
  <script src="../bower_components/requirejs/require.js" type="text/javascript"></script>
  <script src="./config.js" type="text/javascript"></script>
  <script src="game.js"></script>
</body>
</head>
</html>


text:
@interface FLEXManager (FWDebug) <FWDebugFpsInfoDelegate>

+ (void)fwDebugLoad;

+ (void)fwDebugLaunch;

+ (BOOL)fwDebugVisible;

- (FWDebugFpsData *)fwDebugFpsData;

+ (void)fwDebugOpenUrl:(NSString *)text;

@end


text:
package org.yidu.novel.batch;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.yidu.novel.service.ArticleService;

public class CleanStatisticsDataJob extends QuartzJobBean {
    /**
     * 输出log
     */
    private Log logger = LogFactory.getLog(this.getClass());

    /**
     * 小说关联操作服务
     */

    private ArticleService articleService;

    /**
     *
     * 设置articleService
     *
     *
     * @param articleService
     *            articleService
     */
    @Autowired
    public void setArticleService(ArticleService articleService) {
        this.articleService = articleService;
    }

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        logger.debug("CleanStatisticsDataJob start.");
        try {
            articleService.cleanStatistics();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        logger.debug("CleanStatisticsDataJob normally end.");
    }
}


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

<TITLE>
QuerySecurityFiltererDispatcher
</TITLE>

<META NAME="keywords" CONTENT="gov.nih.nci.cabig.caaers.accesscontrol.filter.QuerySecurityFiltererDispatcher class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

gov.nih.nci.cabig.caaers.accesscontrol.filter

Class QuerySecurityFiltererDispatcher

java.lang.Object
  gov.nih.nci.cabig.caaers.accesscontrol.filter.QuerySecurityFiltererDispatcher

public class QuerySecurityFiltererDispatcher
extends java.lang.Object

Will take care of applying the correct Security Filtering on the Query.

Field Summary

protected  org.apache.commons.logging.Log
log

Constructor Summary

QuerySecurityFiltererDispatcher()

Method Summary

 void
filter(AbstractQuery query,
       java.lang.String loginId)

          Will take care of applying the correct Query Filter

 java.util.Map<java.lang.Class<? extends AbstractQuery>,QuerySecurityFilterer>
getFiltererMap()

 void
setFiltererMap(java.util.Map<java.lang.Class<? extends AbstractQuery>,QuerySecurityFilterer> filtererMap)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

log

protected final org.apache.commons.logging.Log log

Constructor Detail

QuerySecurityFiltererDispatcher

public QuerySecurityFiltererDispatcher()

Method Detail

filter

public void filter(AbstractQuery query,
                   java.lang.String loginId)

Will take care of applying the correct Query Filter

Parameters:
query -

getFiltererMap

public java.util.Map<java.lang.Class<? extends AbstractQuery>,QuerySecurityFilterer> getFiltererMap()

setFiltererMap

public void setFiltererMap(java.util.Map<java.lang.Class<? extends AbstractQuery>,QuerySecurityFilterer> filtererMap)

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
package com.jetolgon.dicewarebr.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import com.jetolgon.dicewarebr.R;
import com.jetolgon.dicewarebr.activities.MainActivity;
import com.jetolgon.dicewarebr.models.Diceware;

/**
 * Created by jelther.goncalves on 27/03/2017.
 */

public class SplashActivity extends AppCompatActivity implements Runnable {

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

        Diceware mDiceWare = Diceware.getInstance(this);

        Handler handler = new Handler();
        handler.postDelayed(this, 1000);
    }

    @Override
    public void run() {
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }
}


text:
namespace
{
    int notifyFd = -1;
    int inputFd = -1;
    bool plugged[sf::Joystick::Count];

    void updatePluggedList()
    {
        for (unsigned int i = 0; i < sf::Joystick::Count; ++i)
        {
            char name[32];
            std::snprintf(name, sizeof(name), "/dev/input/js%u", i);

            int file = ::open(name, O_RDONLY);
            if (file >= 0)
            {
                plugged[i] = true;
                ::close(file);
            }
            else
            {
                plugged[i] = false;
            }
        }
    }

    bool canRead(int descriptor)
    {
        if (descriptor >= 0)
        {
            fd_set set;
            FD_ZERO(&set);
            FD_SET(descriptor, &set);
            timeval timeout = {0, 0};
            return select(descriptor + 1, &set, NULL, NULL, &timeout) > 0 &&
                   FD_ISSET(notifyFd, &set);
        }
        else
        {
            return false;
        }
    }
}

namespace sf
{
namespace priv
{
////////////////////////////////////////////////////////////
void JoystickImpl::initialize()
{
    // Reset the array of plugged joysticks
    std::fill(plugged, plugged + Joystick::Count, false);

    // Create the inotify instance
    notifyFd = inotify_init();
    if (notifyFd < 0)
    {
        err() << "Failed to initialize inotify, joystick connections and disconnections won't be notified" << std::endl;
        return;
    }

    // Watch nodes created and deleted in the /dev/input directory
    inputFd = inotify_add_watch(notifyFd, "/dev/input", IN_CREATE | IN_DELETE);
    if (inputFd < 0)
    {
        err() << "Failed to initialize inotify, joystick connections and disconnections won't be notified" << std::endl;
        return;
    }

    // Do an initial scan
    updatePluggedList();
}

////////////////////////////////////////////////////////////
void JoystickImpl::cleanup()
{
    // Stop watching the /dev/input directory
    if (inputFd >= 0)
        inotify_rm_watch(notifyFd, inputFd);

    // Close the inotify file descriptor
    if (notifyFd >= 0)
        ::close(notifyFd);
}

////////////////////////////////////////////////////////////
bool JoystickImpl::isConnected(unsigned int index)
{
    // First check if new joysticks were added/removed since last update
    if (canRead(notifyFd))
    {
        // Don't bother decomposing and interpreting the filename, just do a full scan
        updatePluggedList();

        // Flush all the pending events
        while (canRead(notifyFd))
        {
            char buffer[128];
            (void)read(notifyFd, buffer, sizeof(buffer));
        }
    }

    // Then check if the joystick is connected
    return plugged[index];
}

////////////////////////////////////////////////////////////
bool JoystickImpl::open(unsigned int index)
{
    if (plugged[index])
    {
        char name[32];
        std::snprintf(name, sizeof(name), "/dev/input/js%u", index);

        // Open the joystick's file descriptor (read-only and non-blocking)
        m_file = ::open(name, O_RDONLY | O_NONBLOCK);
        if (m_file >= 0)
        {
            // Retrieve the axes mapping
            ioctl(m_file, JSIOCGAXMAP, m_mapping);

            // Get info
            m_identification.name = getJoystickName(index);
            m_identification.vendorId = getUdevAttributeUint(index, "idVendor");
            m_identification.productId = getUdevAttributeUint(index, "idProduct");

            // Reset the joystick state
            m_state = JoystickState();

            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}

////////////////////////////////////////////////////////////
void JoystickImpl::close()
{
    ::close(m_file);
}

////////////////////////////////////////////////////////////
JoystickCaps JoystickImpl::getCapabilities() const
{
    JoystickCaps caps;

    // Get the number of buttons
    char buttonCount;
    ioctl(m_file, JSIOCGBUTTONS, &buttonCount);
    caps.buttonCount = buttonCount;
    if (caps.buttonCount > Joystick::ButtonCount)
        caps.buttonCount = Joystick::ButtonCount;

    // Get the supported axes
    char axesCount;
    ioctl(m_file, JSIOCGAXES, &axesCount);
    for (int i = 0; i < axesCount; ++i)
    {
        switch (m_mapping[i])
        {
            case ABS_X :        caps.axes[Joystick::X]    = true; break;
            case ABS_Y :        caps.axes[Joystick::Y]    = true; break;
            case ABS_Z :
            case ABS_THROTTLE : caps.axes[Joystick::Z]    = true; break;
            case ABS_RZ:
            case ABS_RUDDER:    caps.axes[Joystick::R]    = true; break;
            case ABS_RX :       caps.axes[Joystick::U]    = true; break;
            case ABS_RY :       caps.axes[Joystick::V]    = true; break;
            case ABS_HAT0X :    caps.axes[Joystick::PovX] = true; break;
            case ABS_HAT0Y :    caps.axes[Joystick::PovY] = true; break;
            default : break;
        }
    }

    return caps;
}

////////////////////////////////////////////////////////////
Joystick::Identification JoystickImpl::getIdentification() const
{
    return m_identification;
}

////////////////////////////////////////////////////////////
JoystickState JoystickImpl::JoystickImpl::update()
{
    // pop events from the joystick file
    js_event joyState;
    while (read(m_file, &joyState, sizeof(joyState)) > 0)
    {
        switch (joyState.type & ~JS_EVENT_INIT)
        {
            // An axis was moved
            case JS_EVENT_AXIS :
            {
                float value = joyState.value * 100.f / 32767.f;
                switch (m_mapping[joyState.number])
                {
                    case ABS_X :        m_state.axes[Joystick::X]    = value; break;
                    case ABS_Y :        m_state.axes[Joystick::Y]    = value; break;
                    case ABS_Z :
                    case ABS_THROTTLE : m_state.axes[Joystick::Z]    = value; break;
                    case ABS_RZ:
                    case ABS_RUDDER:    m_state.axes[Joystick::R]    = value; break;
                    case ABS_RX :       m_state.axes[Joystick::U]    = value; break;
                    case ABS_RY :       m_state.axes[Joystick::V]    = value; break;
                    case ABS_HAT0X :    m_state.axes[Joystick::PovX] = value; break;
                    case ABS_HAT0Y :    m_state.axes[Joystick::PovY] = value; break;
                    default : break;
                }
                break;
            }

            // A button was pressed
            case JS_EVENT_BUTTON :
            {
                if (joyState.number < Joystick::ButtonCount)
                    m_state.buttons[joyState.number] = (joyState.value != 0);
                break;
            }
        }
    }

    // Check the connection state of the joystick (read() fails with an error != EGAIN if it's no longer connected)
    m_state.connected = (errno == EAGAIN);

    return m_state;
}

////////////////////////////////////////////////////////////
std::string JoystickImpl::getJoystickName(unsigned int index)
{
    // Get the name
    char joyname[128];
    if (ioctl(m_file, JSIOCGNAME(sizeof(joyname)), joyname) >= 0)
    {
        return std::string(joyname);
    }

    err() << "Unable to get name for joystick at index " << index << std::endl;
    return std::string("Unknown Joystick");
}

////////////////////////////////////////////////////////////
unsigned int JoystickImpl::getUdevAttributeUint(unsigned int index, std::string attributeName)
{
    unsigned int attr = 0;
    udev* udevContext = udev_new();
    if (udevContext)
    {
        char sysname[32];
        std::snprintf(sysname, sizeof(sysname), "js%u", index);
        udev_device* dev = udev_device_new_from_subsystem_sysname(udevContext, "input", sysname);

        dev = udev_device_get_parent_with_subsystem_devtype(dev, "usb", "usb_device");
        if (dev)
        {
            std::stringstream ss;
            ss << std::hex << udev_device_get_sysattr_value(dev, attributeName.c_str());

            ss >> attr;
        }
        else
        {
            err() << "Unable to get attribute '" << attributeName << "'. Could not find parent USB device for joystick at index " << index << std::endl;
        }

        udev_device_unref(dev);
        udev_unref(udevContext);
    }
    else
    {
        err() << "Unable to get attribute '" << attributeName << "'. Cannot create udev for reading info for joystick at index " << index << std::endl;
    }

    return attr;
}

} // namespace priv

} // namespace sf


text:
package org.bitcoins.db.models

import org.bitcoins.core.crypto.{ExtKeyVersion, ExtPrivateKey}
import org.bitcoins.testkit.db.{TestAppConfig, TestAppConfigFixture}

import java.sql.SQLException

class MasterXPubDAOTest extends TestAppConfigFixture {
  behavior of "MasterXPubDAO"

  it must "create and find a master xpub" in { testAppConfig: TestAppConfig =>
    val xpriv = ExtPrivateKey.freshRootKey(ExtKeyVersion.SegWitTestNet3Priv)
    val xpub = xpriv.extPublicKey
    val masterXpub =
      MasterXPubDAO()(executionContext, appConfig = testAppConfig)

    val createdF = masterXpub.create(xpub)

    val readF = createdF.flatMap { _ =>
      masterXpub.read(xpriv.publicKey)
    }

    for {
      readOpt <- readF
    } yield {
      readOpt match {
        case None    => fail()
        case Some(r) => assert(r.toExtPublicKey == xpub)
      }
    }
  }

  it must "create only one master xpub" in { testAppConfig: TestAppConfig =>
    val masterXpubDAO =
      MasterXPubDAO()(executionContext, appConfig = testAppConfig)

    val xpriv = ExtPrivateKey.freshRootKey(ExtKeyVersion.SegWitTestNet3Priv)
    val xpub = xpriv.extPublicKey

    val xpriv2 = ExtPrivateKey.freshRootKey(ExtKeyVersion.SegWitTestNet3Priv)
    val xpub2 = xpriv2.extPublicKey

    for {
      created <- masterXpubDAO.create(xpub)
      _ = assert(created.toExtPublicKey == xpub)
      // don't insert a duplicate key
      _ <- recoverToSucceededIf[SQLException](masterXpubDAO.create(xpub))
      // don't insert more than one key
      _ <- recoverToSucceededIf[SQLException](masterXpubDAO.create(xpub2))
    } yield succeed

  }

  it must "validate the masterxpub and succeed in the database" in {
    testAppConfig: TestAppConfig =>
      val xpriv = ExtPrivateKey.freshRootKey(ExtKeyVersion.SegWitTestNet3Priv)
      val xpub = xpriv.extPublicKey
      val masterXpub =
        MasterXPubDAO()(executionContext, appConfig = testAppConfig)

      val createdF = masterXpub.create(xpub)

      for {
        _ <- createdF
        _ <- masterXpub.validate(xpub)
      } yield succeed
  }

  it must "throw an exception is the stored master xpub is different than the given" in {
    testAppConfig: TestAppConfig =>
      val xpriv = ExtPrivateKey.freshRootKey(ExtKeyVersion.SegWitTestNet3Priv)
      val xpub = xpriv.extPublicKey
      val masterXpub =
        MasterXPubDAO()(executionContext, appConfig = testAppConfig)

      val createdF = masterXpub.create(xpub)

      val differentXpub = ExtPrivateKey
        .freshRootKey(ExtKeyVersion.SegWitTestNet3Priv)
        .extPublicKey

      val validatedF = {
        for {
          _ <- createdF
          _ <- masterXpub.validate(differentXpub)
        } yield ()
      }

      recoverToSucceededIf[RuntimeException] {
        validatedF
      }
  }
}


text:
layout: page
title: Seattle Police Officer 8300 Kassi A. Sobania
permalink: /information/agencies/city_of_seattle/seattle_police_department/copbook/8300/
---

**Age as of Feb. 24, 2016:** 24


text:
package ssttpcalculator

import java.time.LocalDate
import java.time.temporal.ChronoUnit
import java.time.temporal.ChronoUnit._

import javax.inject.Singleton

@Singleton
class DurationService {
  def getDaysBetween(startDate: LocalDate, endDate: LocalDate, inclusive: Boolean = true): Long = calculatePeriod(startDate, endDate, DAYS, inclusive)

  /**
   * Calculates the number of days between two dates which uses the inclusive flag to determine if it is single
   * inclusive (includes the end date) or not inclusive (excludes both start and end date).
   */
  private def calculatePeriod(startDate: LocalDate, endDate: LocalDate, frequency: ChronoUnit, inclusive: Boolean): Long = {
    frequency.between(startDate, endDate) + (if (inclusive) 0 else -1) match {
      case c if c > 0 => c
      case _          => 0
    }
  }

  def getRepaymentDates(startDate: LocalDate, endDate: LocalDate): Seq[LocalDate] = {
    if (startDate.isAfter(endDate)) throw new IllegalArgumentException("Start date must be BEFORE end date")

    Iterator.iterate(startDate)(_ plusMonths 1).takeWhile(_.compareTo(endDate) <= 0).toSeq
  }
}


text:
@interface NSAttributeDescription (NSPDynamoStore)

-(BOOL)nsp_isStringType;
-(BOOL)nsp_isNumberType;

@end