text
stringlengths 2
99.9k
| meta
dict |
---|---|
{
"id": 4926,
"name": "Pirate Guard",
"incomplete": true,
"members": true,
"release_date": "2002-02-27",
"combat_level": 19,
"size": 1,
"hitpoints": 25,
"max_hit": 3,
"attack_type": [
"slash"
],
"attack_speed": 4,
"aggressive": false,
"poisonous": false,
"immune_poison": false,
"immune_venom": false,
"attributes": [],
"category": [],
"slayer_monster": false,
"slayer_level": null,
"slayer_xp": null,
"slayer_masters": [],
"duplicate": false,
"examine": "A morally ambiguous guard.",
"icon": null,
"wiki_name": "Pirate Guard",
"wiki_url": "https://oldschool.runescape.wiki/w/Pirate_Guard",
"attack_level": 18,
"strength_level": 16,
"defence_level": 10,
"magic_level": 1,
"ranged_level": 1,
"attack_stab": 0,
"attack_slash": 0,
"attack_crush": 0,
"attack_magic": 0,
"attack_ranged": 0,
"defence_stab": 30,
"defence_slash": 39,
"defence_crush": 30,
"defence_magic": 0,
"defence_ranged": 0,
"attack_accuracy": 20,
"melee_strength": 16,
"ranged_strength": 0,
"magic_damage": 0,
"drops": [
{
"id": 526,
"name": "Bones",
"members": true,
"quantity": "1",
"noted": false,
"rarity": 1.0,
"drop_requirements": null
}
]
} | {
"pile_set_name": "Github"
} |
"use strict";
exports.__esModule = true;
exports.default = function () {
return {
manipulateOptions: function manipulateOptions(opts, parserOpts) {
parserOpts.plugins.push("jsx");
}
};
};
module.exports = exports["default"]; | {
"pile_set_name": "Github"
} |
///////////////////////////////////////////////////////////////////////////////
//
// @@@ START COPYRIGHT @@@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
// @@@ END COPYRIGHT @@@
//
///////////////////////////////////////////////////////////////////////////////
#include "nstype.h"
#include "replicate.cxx"
| {
"pile_set_name": "Github"
} |
//===-- PPCCTRLoops.cpp - Identify and generate CTR loops -----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This pass identifies loops where we can generate the PPC branch instructions
// that decrement and test the count register (CTR) (bdnz and friends).
//
// The pattern that defines the induction variable can changed depending on
// prior optimizations. For example, the IndVarSimplify phase run by 'opt'
// normalizes induction variables, and the Loop Strength Reduction pass
// run by 'llc' may also make changes to the induction variable.
//
// Criteria for CTR loops:
// - Countable loops (w/ ind. var for a trip count)
// - Try inner-most loops first
// - No nested CTR loops.
// - No function calls in loops.
//
//===----------------------------------------------------------------------===//
#include "PPC.h"
#include "PPCSubtarget.h"
#include "PPCTargetMachine.h"
#include "PPCTargetTransformInfo.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/CFG.h"
#include "llvm/Analysis/CodeMetrics.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/LoopIterator.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/CodeGen/TargetSchedule.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/InitializePasses.h"
#include "llvm/PassSupport.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/LoopUtils.h"
#ifndef NDEBUG
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#endif
using namespace llvm;
#define DEBUG_TYPE "ctrloops"
#ifndef NDEBUG
static cl::opt<int> CTRLoopLimit("ppc-max-ctrloop", cl::Hidden, cl::init(-1));
#endif
namespace {
#ifndef NDEBUG
struct PPCCTRLoopsVerify : public MachineFunctionPass {
public:
static char ID;
PPCCTRLoopsVerify() : MachineFunctionPass(ID) {
initializePPCCTRLoopsVerifyPass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<MachineDominatorTree>();
MachineFunctionPass::getAnalysisUsage(AU);
}
bool runOnMachineFunction(MachineFunction &MF) override;
private:
MachineDominatorTree *MDT;
};
char PPCCTRLoopsVerify::ID = 0;
#endif // NDEBUG
} // end anonymous namespace
#ifndef NDEBUG
INITIALIZE_PASS_BEGIN(PPCCTRLoopsVerify, "ppc-ctr-loops-verify",
"PowerPC CTR Loops Verify", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
INITIALIZE_PASS_END(PPCCTRLoopsVerify, "ppc-ctr-loops-verify",
"PowerPC CTR Loops Verify", false, false)
FunctionPass *llvm::createPPCCTRLoopsVerify() {
return new PPCCTRLoopsVerify();
}
#endif // NDEBUG
#ifndef NDEBUG
static bool clobbersCTR(const MachineInstr &MI) {
for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI.getOperand(i);
if (MO.isReg()) {
if (MO.isDef() && (MO.getReg() == PPC::CTR || MO.getReg() == PPC::CTR8))
return true;
} else if (MO.isRegMask()) {
if (MO.clobbersPhysReg(PPC::CTR) || MO.clobbersPhysReg(PPC::CTR8))
return true;
}
}
return false;
}
static bool verifyCTRBranch(MachineBasicBlock *MBB,
MachineBasicBlock::iterator I) {
MachineBasicBlock::iterator BI = I;
SmallSet<MachineBasicBlock *, 16> Visited;
SmallVector<MachineBasicBlock *, 8> Preds;
bool CheckPreds;
if (I == MBB->begin()) {
Visited.insert(MBB);
goto queue_preds;
} else
--I;
check_block:
Visited.insert(MBB);
if (I == MBB->end())
goto queue_preds;
CheckPreds = true;
for (MachineBasicBlock::iterator IE = MBB->begin();; --I) {
unsigned Opc = I->getOpcode();
if (Opc == PPC::MTCTRloop || Opc == PPC::MTCTR8loop) {
CheckPreds = false;
break;
}
if (I != BI && clobbersCTR(*I)) {
LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " (" << MBB->getFullName()
<< ") instruction " << *I
<< " clobbers CTR, invalidating "
<< printMBBReference(*BI->getParent()) << " ("
<< BI->getParent()->getFullName() << ") instruction "
<< *BI << "\n");
return false;
}
if (I == IE)
break;
}
if (!CheckPreds && Preds.empty())
return true;
if (CheckPreds) {
queue_preds:
if (MachineFunction::iterator(MBB) == MBB->getParent()->begin()) {
LLVM_DEBUG(dbgs() << "Unable to find a MTCTR instruction for "
<< printMBBReference(*BI->getParent()) << " ("
<< BI->getParent()->getFullName() << ") instruction "
<< *BI << "\n");
return false;
}
for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
PIE = MBB->pred_end(); PI != PIE; ++PI)
Preds.push_back(*PI);
}
do {
MBB = Preds.pop_back_val();
if (!Visited.count(MBB)) {
I = MBB->getLastNonDebugInstr();
goto check_block;
}
} while (!Preds.empty());
return true;
}
bool PPCCTRLoopsVerify::runOnMachineFunction(MachineFunction &MF) {
MDT = &getAnalysis<MachineDominatorTree>();
// Verify that all bdnz/bdz instructions are dominated by a loop mtctr before
// any other instructions that might clobber the ctr register.
for (MachineFunction::iterator I = MF.begin(), IE = MF.end();
I != IE; ++I) {
MachineBasicBlock *MBB = &*I;
if (!MDT->isReachableFromEntry(MBB))
continue;
for (MachineBasicBlock::iterator MII = MBB->getFirstTerminator(),
MIIE = MBB->end(); MII != MIIE; ++MII) {
unsigned Opc = MII->getOpcode();
if (Opc == PPC::BDNZ8 || Opc == PPC::BDNZ ||
Opc == PPC::BDZ8 || Opc == PPC::BDZ)
if (!verifyCTRBranch(MBB, MII))
llvm_unreachable("Invalid PPC CTR loop!");
}
}
return false;
}
#endif // NDEBUG
| {
"pile_set_name": "Github"
} |
// integer.h - written and placed in the public domain by Wei Dai
//! \file integer.h
//! \brief Multiple precision integer with arithmetic operations
//! \details The Integer class can represent positive and negative integers
//! with absolute value less than (256**sizeof(word))<sup>(256**sizeof(int))</sup>.
//! \details Internally, the library uses a sign magnitude representation, and the class
//! has two data members. The first is a IntegerSecBlock (a SecBlock<word>) and it is
//! used to hold the representation. The second is a Sign (an enumeration), and it is
//! used to track the sign of the Integer.
//! \since Crypto++ 1.0
#ifndef CRYPTOPP_INTEGER_H
#define CRYPTOPP_INTEGER_H
#include "cryptlib.h"
#include "secblock.h"
#include "stdcpp.h"
#include <iosfwd>
NAMESPACE_BEGIN(CryptoPP)
//! \struct InitializeInteger
//! \brief Performs static initialization of the Integer class
struct InitializeInteger
{
InitializeInteger();
};
// Always align, http://github.com/weidai11/cryptopp/issues/256
typedef SecBlock<word, AllocatorWithCleanup<word, true> > IntegerSecBlock;
//! \brief Multiple precision integer with arithmetic operations
//! \details The Integer class can represent positive and negative integers
//! with absolute value less than (256**sizeof(word))<sup>(256**sizeof(int))</sup>.
//! \details Internally, the library uses a sign magnitude representation, and the class
//! has two data members. The first is a IntegerSecBlock (a SecBlock<word>) and it is
//! used to hold the representation. The second is a Sign (an enumeration), and it is
//! used to track the sign of the Integer.
//! \since Crypto++ 1.0
//! \nosubgrouping
class CRYPTOPP_DLL Integer : private InitializeInteger, public ASN1Object
{
public:
//! \name ENUMS, EXCEPTIONS, and TYPEDEFS
//@{
//! \brief Exception thrown when division by 0 is encountered
class DivideByZero : public Exception
{
public:
DivideByZero() : Exception(OTHER_ERROR, "Integer: division by zero") {}
};
//! \brief Exception thrown when a random number cannot be found that
//! satisfies the condition
class RandomNumberNotFound : public Exception
{
public:
RandomNumberNotFound() : Exception(OTHER_ERROR, "Integer: no integer satisfies the given parameters") {}
};
//! \enum Sign
//! \brief Used internally to represent the integer
//! \details Sign is used internally to represent the integer. It is also used in a few API functions.
//! \sa SetPositive(), SetNegative(), Signedness
enum Sign {
//! \brief the value is positive or 0
POSITIVE=0,
//! \brief the value is negative
NEGATIVE=1};
//! \enum Signedness
//! \brief Used when importing and exporting integers
//! \details Signedness is usually used in API functions.
//! \sa Sign
enum Signedness {
//! \brief an unsigned value
UNSIGNED,
//! \brief a signed value
SIGNED};
//! \enum RandomNumberType
//! \brief Properties of a random integer
enum RandomNumberType {
//! \brief a number with no special properties
ANY,
//! \brief a number which is probabilistically prime
PRIME};
//@}
//! \name CREATORS
//@{
//! \brief Creates the zero integer
Integer();
//! copy constructor
Integer(const Integer& t);
//! \brief Convert from signed long
Integer(signed long value);
//! \brief Convert from lword
//! \param sign enumeration indicating Sign
//! \param value the long word
Integer(Sign sign, lword value);
//! \brief Convert from two words
//! \param sign enumeration indicating Sign
//! \param highWord the high word
//! \param lowWord the low word
Integer(Sign sign, word highWord, word lowWord);
//! \brief Convert from a C-string
//! \param str C-string value
//! \param order the ByteOrder of the string to be processed
//! \details \p str can be in base 2, 8, 10, or 16. Base is determined by a case
//! insensitive suffix of 'h', 'o', or 'b'. No suffix means base 10.
//! \details Byte order was added at Crypto++ 5.7 to allow use of little-endian
//! integers with curve25519, Poly1305 and Microsoft CAPI.
explicit Integer(const char *str, ByteOrder order = BIG_ENDIAN_ORDER);
//! \brief Convert from a wide C-string
//! \param str wide C-string value
//! \param order the ByteOrder of the string to be processed
//! \details \p str can be in base 2, 8, 10, or 16. Base is determined by a case
//! insensitive suffix of 'h', 'o', or 'b'. No suffix means base 10.
//! \details Byte order was added at Crypto++ 5.7 to allow use of little-endian
//! integers with curve25519, Poly1305 and Microsoft CAPI.
explicit Integer(const wchar_t *str, ByteOrder order = BIG_ENDIAN_ORDER);
//! \brief Convert from a big-endian byte array
//! \param encodedInteger big-endian byte array
//! \param byteCount length of the byte array
//! \param sign enumeration indicating Signedness
//! \param order the ByteOrder of the array to be processed
//! \details Byte order was added at Crypto++ 5.7 to allow use of little-endian
//! integers with curve25519, Poly1305 and Microsoft CAPI.
Integer(const byte *encodedInteger, size_t byteCount, Signedness sign=UNSIGNED, ByteOrder order = BIG_ENDIAN_ORDER);
//! \brief Convert from a big-endian array
//! \param bt BufferedTransformation object with big-endian byte array
//! \param byteCount length of the byte array
//! \param sign enumeration indicating Signedness
//! \param order the ByteOrder of the data to be processed
//! \details Byte order was added at Crypto++ 5.7 to allow use of little-endian
//! integers with curve25519, Poly1305 and Microsoft CAPI.
Integer(BufferedTransformation &bt, size_t byteCount, Signedness sign=UNSIGNED, ByteOrder order = BIG_ENDIAN_ORDER);
//! \brief Convert from a BER encoded byte array
//! \param bt BufferedTransformation object with BER encoded byte array
explicit Integer(BufferedTransformation &bt);
//! \brief Create a random integer
//! \param rng RandomNumberGenerator used to generate material
//! \param bitCount the number of bits in the resulting integer
//! \details The random integer created is uniformly distributed over <tt>[0, 2<sup>bitCount</sup>]</tt>.
Integer(RandomNumberGenerator &rng, size_t bitCount);
//! \brief Integer representing 0
//! \returns an Integer representing 0
//! \details Zero() avoids calling constructors for frequently used integers
static const Integer & CRYPTOPP_API Zero();
//! \brief Integer representing 1
//! \returns an Integer representing 1
//! \details One() avoids calling constructors for frequently used integers
static const Integer & CRYPTOPP_API One();
//! \brief Integer representing 2
//! \returns an Integer representing 2
//! \details Two() avoids calling constructors for frequently used integers
static const Integer & CRYPTOPP_API Two();
//! \brief Create a random integer of special form
//! \param rng RandomNumberGenerator used to generate material
//! \param min the minimum value
//! \param max the maximum value
//! \param rnType RandomNumberType to specify the type
//! \param equiv the equivalence class based on the parameter \p mod
//! \param mod the modulus used to reduce the equivalence class
//! \throw RandomNumberNotFound if the set is empty.
//! \details Ideally, the random integer created should be uniformly distributed
//! over <tt>{x | min \<= x \<= max</tt> and \p x is of rnType and <tt>x \% mod == equiv}</tt>.
//! However the actual distribution may not be uniform because sequential
//! search is used to find an appropriate number from a random starting
//! point.
//! \details May return (with very small probability) a pseudoprime when a prime
//! is requested and <tt>max \> lastSmallPrime*lastSmallPrime</tt>. \p lastSmallPrime
//! is declared in nbtheory.h.
Integer(RandomNumberGenerator &rng, const Integer &min, const Integer &max, RandomNumberType rnType=ANY, const Integer &equiv=Zero(), const Integer &mod=One());
//! \brief Exponentiates to a power of 2
//! \returns the Integer 2<sup>e</sup>
//! \sa a_times_b_mod_c() and a_exp_b_mod_c()
static Integer CRYPTOPP_API Power2(size_t e);
//@}
//! \name ENCODE/DECODE
//@{
//! \brief Minimum number of bytes to encode this integer
//! \param sign enumeration indicating Signedness
//! \note The MinEncodedSize() of 0 is 1.
size_t MinEncodedSize(Signedness sign=UNSIGNED) const;
//! \brief Encode in big-endian format
//! \param output big-endian byte array
//! \param outputLen length of the byte array
//! \param sign enumeration indicating Signedness
//! \details Unsigned means encode absolute value, signed means encode two's complement if negative.
//! \details outputLen can be used to ensure an Integer is encoded to an exact size (rather than a
//! minimum size). An exact size is useful, for example, when encoding to a field element size.
void Encode(byte *output, size_t outputLen, Signedness sign=UNSIGNED) const;
//! \brief Encode in big-endian format
//! \param bt BufferedTransformation object
//! \param outputLen length of the encoding
//! \param sign enumeration indicating Signedness
//! \details Unsigned means encode absolute value, signed means encode two's complement if negative.
//! \details outputLen can be used to ensure an Integer is encoded to an exact size (rather than a
//! minimum size). An exact size is useful, for example, when encoding to a field element size.
void Encode(BufferedTransformation &bt, size_t outputLen, Signedness sign=UNSIGNED) const;
//! \brief Encode in DER format
//! \param bt BufferedTransformation object
//! \details Encodes the Integer using Distinguished Encoding Rules
//! The result is placed into a BufferedTransformation object
void DEREncode(BufferedTransformation &bt) const;
//! \brief Encode absolute value as big-endian octet string
//! \param bt BufferedTransformation object
//! \param length the number of mytes to decode
void DEREncodeAsOctetString(BufferedTransformation &bt, size_t length) const;
//! \brief Encode absolute value in OpenPGP format
//! \param output big-endian byte array
//! \param bufferSize length of the byte array
//! \returns length of the output
//! \details OpenPGPEncode places result into a BufferedTransformation object and returns the
//! number of bytes used for the encoding
size_t OpenPGPEncode(byte *output, size_t bufferSize) const;
//! \brief Encode absolute value in OpenPGP format
//! \param bt BufferedTransformation object
//! \returns length of the output
//! \details OpenPGPEncode places result into a BufferedTransformation object and returns the
//! number of bytes used for the encoding
size_t OpenPGPEncode(BufferedTransformation &bt) const;
//! \brief Decode from big-endian byte array
//! \param input big-endian byte array
//! \param inputLen length of the byte array
//! \param sign enumeration indicating Signedness
void Decode(const byte *input, size_t inputLen, Signedness sign=UNSIGNED);
//! \brief Decode nonnegative value from big-endian byte array
//! \param bt BufferedTransformation object
//! \param inputLen length of the byte array
//! \param sign enumeration indicating Signedness
//! \note <tt>bt.MaxRetrievable() \>= inputLen</tt>.
void Decode(BufferedTransformation &bt, size_t inputLen, Signedness sign=UNSIGNED);
//! \brief Decode from BER format
//! \param input big-endian byte array
//! \param inputLen length of the byte array
void BERDecode(const byte *input, size_t inputLen);
//! \brief Decode from BER format
//! \param bt BufferedTransformation object
void BERDecode(BufferedTransformation &bt);
//! \brief Decode nonnegative value from big-endian octet string
//! \param bt BufferedTransformation object
//! \param length length of the byte array
void BERDecodeAsOctetString(BufferedTransformation &bt, size_t length);
//! \brief Exception thrown when an error is encountered decoding an OpenPGP integer
class OpenPGPDecodeErr : public Exception
{
public:
OpenPGPDecodeErr() : Exception(INVALID_DATA_FORMAT, "OpenPGP decode error") {}
};
//! \brief Decode from OpenPGP format
//! \param input big-endian byte array
//! \param inputLen length of the byte array
void OpenPGPDecode(const byte *input, size_t inputLen);
//! \brief Decode from OpenPGP format
//! \param bt BufferedTransformation object
void OpenPGPDecode(BufferedTransformation &bt);
//@}
//! \name ACCESSORS
//@{
//! \brief Determines if the Integer is convertable to Long
//! \returns true if *this can be represented as a signed long
//! \sa ConvertToLong()
bool IsConvertableToLong() const;
//! \brief Convert the Integer to Long
//! \return equivalent signed long if possible, otherwise undefined
//! \sa IsConvertableToLong()
signed long ConvertToLong() const;
//! \brief Determines the number of bits required to represent the Integer
//! \returns number of significant bits = floor(log2(abs(*this))) + 1
unsigned int BitCount() const;
//! \brief Determines the number of bytes required to represent the Integer
//! \returns number of significant bytes = ceiling(BitCount()/8)
unsigned int ByteCount() const;
//! \brief Determines the number of words required to represent the Integer
//! \returns number of significant words = ceiling(ByteCount()/sizeof(word))
unsigned int WordCount() const;
//! \brief Provides the i-th bit of the Integer
//! \returns the i-th bit, i=0 being the least significant bit
bool GetBit(size_t i) const;
//! \brief Provides the i-th byte of the Integer
//! \returns the i-th byte
byte GetByte(size_t i) const;
//! \brief Provides the low order bits of the Integer
//! \returns n lowest bits of *this >> i
lword GetBits(size_t i, size_t n) const;
//! \brief Determines if the Integer is 0
//! \returns true if the Integer is 0, false otherwise
bool IsZero() const {return !*this;}
//! \brief Determines if the Integer is non-0
//! \returns true if the Integer is non-0, false otherwise
bool NotZero() const {return !IsZero();}
//! \brief Determines if the Integer is negative
//! \returns true if the Integer is negative, false otherwise
bool IsNegative() const {return sign == NEGATIVE;}
//! \brief Determines if the Integer is non-negative
//! \returns true if the Integer is non-negative, false otherwise
bool NotNegative() const {return !IsNegative();}
//! \brief Determines if the Integer is positive
//! \returns true if the Integer is positive, false otherwise
bool IsPositive() const {return NotNegative() && NotZero();}
//! \brief Determines if the Integer is non-positive
//! \returns true if the Integer is non-positive, false otherwise
bool NotPositive() const {return !IsPositive();}
//! \brief Determines if the Integer is even parity
//! \returns true if the Integer is even, false otherwise
bool IsEven() const {return GetBit(0) == 0;}
//! \brief Determines if the Integer is odd parity
//! \returns true if the Integer is odd, false otherwise
bool IsOdd() const {return GetBit(0) == 1;}
//@}
//! \name MANIPULATORS
//@{
//! \brief Assignment
Integer& operator=(const Integer& t);
//! \brief Addition Assignment
Integer& operator+=(const Integer& t);
//! \brief Subtraction Assignment
Integer& operator-=(const Integer& t);
//! \brief Multiplication Assignment
//! \sa a_times_b_mod_c() and a_exp_b_mod_c()
Integer& operator*=(const Integer& t) {return *this = Times(t);}
//! \brief Division Assignment
Integer& operator/=(const Integer& t) {return *this = DividedBy(t);}
//! \brief Remainder Assignment
//! \sa a_times_b_mod_c() and a_exp_b_mod_c()
Integer& operator%=(const Integer& t) {return *this = Modulo(t);}
//! \brief Division Assignment
Integer& operator/=(word t) {return *this = DividedBy(t);}
//! \brief Remainder Assignment
//! \sa a_times_b_mod_c() and a_exp_b_mod_c()
Integer& operator%=(word t) {return *this = Integer(POSITIVE, 0, Modulo(t));}
//! \brief Left-shift Assignment
Integer& operator<<=(size_t n);
//! \brief Right-shift Assignment
Integer& operator>>=(size_t n);
//! \brief Bitwise AND Assignment
//! \param t the other Integer
//! \returns the result of *this & t
//! \details operator&=() performs a bitwise AND on *this. Missing bits are truncated
//! at the most significant bit positions, so the result is as small as the
//! smaller of the operands.
//! \details Internally, Crypto++ uses a sign-magnitude representation. The library
//! does not attempt to interpret bits, and the result is always POSITIVE. If needed,
//! the integer should be converted to a 2's compliment representation before performing
//! the operation.
//! \since Crypto++ 5.7
Integer& operator&=(const Integer& t);
//! \brief Bitwise OR Assignment
//! \param t the second Integer
//! \returns the result of *this | t
//! \details operator|=() performs a bitwise OR on *this. Missing bits are shifted in
//! at the most significant bit positions, so the result is as large as the
//! larger of the operands.
//! \details Internally, Crypto++ uses a sign-magnitude representation. The library
//! does not attempt to interpret bits, and the result is always POSITIVE. If needed,
//! the integer should be converted to a 2's compliment representation before performing
//! the operation.
//! \since Crypto++ 5.7
Integer& operator|=(const Integer& t);
//! \brief Bitwise XOR Assignment
//! \param t the other Integer
//! \returns the result of *this ^ t
//! \details operator^=() performs a bitwise XOR on *this. Missing bits are shifted
//! in at the most significant bit positions, so the result is as large as the
//! larger of the operands.
//! \details Internally, Crypto++ uses a sign-magnitude representation. The library
//! does not attempt to interpret bits, and the result is always POSITIVE. If needed,
//! the integer should be converted to a 2's compliment representation before performing
//! the operation.
//! \since Crypto++ 5.7
Integer& operator^=(const Integer& t);
//! \brief Set this Integer to random integer
//! \param rng RandomNumberGenerator used to generate material
//! \param bitCount the number of bits in the resulting integer
//! \details The random integer created is uniformly distributed over <tt>[0, 2<sup>bitCount</sup>]</tt>.
void Randomize(RandomNumberGenerator &rng, size_t bitCount);
//! \brief Set this Integer to random integer
//! \param rng RandomNumberGenerator used to generate material
//! \param min the minimum value
//! \param max the maximum value
//! \details The random integer created is uniformly distributed over <tt>[min, max]</tt>.
void Randomize(RandomNumberGenerator &rng, const Integer &min, const Integer &max);
//! \brief Set this Integer to random integer of special form
//! \param rng RandomNumberGenerator used to generate material
//! \param min the minimum value
//! \param max the maximum value
//! \param rnType RandomNumberType to specify the type
//! \param equiv the equivalence class based on the parameter \p mod
//! \param mod the modulus used to reduce the equivalence class
//! \throw RandomNumberNotFound if the set is empty.
//! \details Ideally, the random integer created should be uniformly distributed
//! over <tt>{x | min \<= x \<= max</tt> and \p x is of rnType and <tt>x \% mod == equiv}</tt>.
//! However the actual distribution may not be uniform because sequential
//! search is used to find an appropriate number from a random starting
//! point.
//! \details May return (with very small probability) a pseudoprime when a prime
//! is requested and <tt>max \> lastSmallPrime*lastSmallPrime</tt>. \p lastSmallPrime
//! is declared in nbtheory.h.
bool Randomize(RandomNumberGenerator &rng, const Integer &min, const Integer &max, RandomNumberType rnType, const Integer &equiv=Zero(), const Integer &mod=One());
bool GenerateRandomNoThrow(RandomNumberGenerator &rng, const NameValuePairs ¶ms = g_nullNameValuePairs);
void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs ¶ms = g_nullNameValuePairs)
{
if (!GenerateRandomNoThrow(rng, params))
throw RandomNumberNotFound();
}
//! \brief Set the n-th bit to value
//! \details 0-based numbering.
void SetBit(size_t n, bool value=1);
//! \brief Set the n-th byte to value
//! \details 0-based numbering.
void SetByte(size_t n, byte value);
//! \brief Reverse the Sign of the Integer
void Negate();
//! \brief Sets the Integer to positive
void SetPositive() {sign = POSITIVE;}
//! \brief Sets the Integer to negative
void SetNegative() {if (!!(*this)) sign = NEGATIVE;}
//! \brief Swaps this Integer with another Integer
void swap(Integer &a);
//@}
//! \name UNARY OPERATORS
//@{
//! \brief Negation
bool operator!() const;
//! \brief Addition
Integer operator+() const {return *this;}
//! \brief Subtraction
Integer operator-() const;
//! \brief Pre-increment
Integer& operator++();
//! \brief Pre-decrement
Integer& operator--();
//! \brief Post-increment
Integer operator++(int) {Integer temp = *this; ++*this; return temp;}
//! \brief Post-decrement
Integer operator--(int) {Integer temp = *this; --*this; return temp;}
//@}
//! \name BINARY OPERATORS
//@{
//! \brief Perform signed comparison
//! \param a the Integer to comapre
//! \retval -1 if <tt>*this < a</tt>
//! \retval 0 if <tt>*this = a</tt>
//! \retval 1 if <tt>*this > a</tt>
int Compare(const Integer& a) const;
//! \brief Addition
Integer Plus(const Integer &b) const;
//! \brief Subtraction
Integer Minus(const Integer &b) const;
//! \brief Multiplication
//! \sa a_times_b_mod_c() and a_exp_b_mod_c()
Integer Times(const Integer &b) const;
//! \brief Division
Integer DividedBy(const Integer &b) const;
//! \brief Remainder
//! \sa a_times_b_mod_c() and a_exp_b_mod_c()
Integer Modulo(const Integer &b) const;
//! \brief Division
Integer DividedBy(word b) const;
//! \brief Remainder
//! \sa a_times_b_mod_c() and a_exp_b_mod_c()
word Modulo(word b) const;
//! \brief Bitwise AND
//! \param t the other Integer
//! \returns the result of <tt>*this & t</tt>
//! \details And() performs a bitwise AND on the operands. Missing bits are truncated
//! at the most significant bit positions, so the result is as small as the
//! smaller of the operands.
//! \details Internally, Crypto++ uses a sign-magnitude representation. The library
//! does not attempt to interpret bits, and the result is always POSITIVE. If needed,
//! the integer should be converted to a 2's compliment representation before performing
//! the operation.
//! \since Crypto++ 5.7
Integer And(const Integer&) const;
//! \brief Bitwise OR
//! \param t the other Integer
//! \returns the result of <tt>*this | t</tt>
//! \details Or() performs a bitwise OR on the operands. Missing bits are shifted in
//! at the most significant bit positions, so the result is as large as the
//! larger of the operands.
//! \details Internally, Crypto++ uses a sign-magnitude representation. The library
//! does not attempt to interpret bits, and the result is always POSITIVE. If needed,
//! the integer should be converted to a 2's compliment representation before performing
//! the operation.
//! \since Crypto++ 5.7
Integer Or(const Integer&) const;
//! \brief Bitwise XOR
//! \param t the other Integer
//! \returns the result of <tt>*this ^ t</tt>
//! \details Xor() performs a bitwise XOR on the operands. Missing bits are shifted in
//! at the most significant bit positions, so the result is as large as the
//! larger of the operands.
//! \details Internally, Crypto++ uses a sign-magnitude representation. The library
//! does not attempt to interpret bits, and the result is always POSITIVE. If needed,
//! the integer should be converted to a 2's compliment representation before performing
//! the operation.
//! \since Crypto++ 5.7
Integer Xor(const Integer&) const;
//! \brief Right-shift
Integer operator>>(size_t n) const {return Integer(*this)>>=n;}
//! \brief Left-shift
Integer operator<<(size_t n) const {return Integer(*this)<<=n;}
//@}
//! \name OTHER ARITHMETIC FUNCTIONS
//@{
//! \brief Retrieve the absolute value of this integer
Integer AbsoluteValue() const;
//! \brief Add this integer to itself
Integer Doubled() const {return Plus(*this);}
//! \brief Multiply this integer by itself
//! \sa a_times_b_mod_c() and a_exp_b_mod_c()
Integer Squared() const {return Times(*this);}
//! \brief Extract square root
//! \details if negative return 0, else return floor of square root
Integer SquareRoot() const;
//! \brief Determine whether this integer is a perfect square
bool IsSquare() const;
//! is 1 or -1
bool IsUnit() const;
//! return inverse if 1 or -1, otherwise return 0
Integer MultiplicativeInverse() const;
//! \brief calculate r and q such that (a == d*q + r) && (0 <= r < abs(d))
static void CRYPTOPP_API Divide(Integer &r, Integer &q, const Integer &a, const Integer &d);
//! \brief use a faster division algorithm when divisor is short
static void CRYPTOPP_API Divide(word &r, Integer &q, const Integer &a, word d);
//! \brief returns same result as Divide(r, q, a, Power2(n)), but faster
static void CRYPTOPP_API DivideByPowerOf2(Integer &r, Integer &q, const Integer &a, unsigned int n);
//! greatest common divisor
static Integer CRYPTOPP_API Gcd(const Integer &a, const Integer &n);
//! \brief calculate multiplicative inverse of *this mod n
Integer InverseMod(const Integer &n) const;
//!
//! \sa a_times_b_mod_c() and a_exp_b_mod_c()
word InverseMod(word n) const;
//@}
//! \name INPUT/OUTPUT
//@{
//! \brief Extraction operator
//! \param in a reference to a std::istream
//! \param a a reference to an Integer
//! \returns a reference to a std::istream reference
friend CRYPTOPP_DLL std::istream& CRYPTOPP_API operator>>(std::istream& in, Integer &a);
//!
//! \brief Insertion operator
//! \param out a reference to a std::ostream
//! \param a a constant reference to an Integer
//! \returns a reference to a std::ostream reference
//! \details The output integer responds to std::hex, std::oct, std::hex, std::upper and
//! std::lower. The output includes the suffix \a \b h (for hex), \a \b . (\a \b dot, for dec)
//! and \a \b o (for octal). There is currently no way to suppress the suffix.
//! \details If you want to print an Integer without the suffix or using an arbitrary base, then
//! use IntToString<Integer>().
//! \sa IntToString<Integer>
friend CRYPTOPP_DLL std::ostream& CRYPTOPP_API operator<<(std::ostream& out, const Integer &a);
//@}
#ifndef CRYPTOPP_DOXYGEN_PROCESSING
//! modular multiplication
CRYPTOPP_DLL friend Integer CRYPTOPP_API a_times_b_mod_c(const Integer &x, const Integer& y, const Integer& m);
//! modular exponentiation
CRYPTOPP_DLL friend Integer CRYPTOPP_API a_exp_b_mod_c(const Integer &x, const Integer& e, const Integer& m);
#endif
private:
Integer(word value, size_t length);
int PositiveCompare(const Integer &t) const;
IntegerSecBlock reg;
Sign sign;
#ifndef CRYPTOPP_DOXYGEN_PROCESSING
friend class ModularArithmetic;
friend class MontgomeryRepresentation;
friend class HalfMontgomeryRepresentation;
friend void PositiveAdd(Integer &sum, const Integer &a, const Integer &b);
friend void PositiveSubtract(Integer &diff, const Integer &a, const Integer &b);
friend void PositiveMultiply(Integer &product, const Integer &a, const Integer &b);
friend void PositiveDivide(Integer &remainder, Integer "ient, const Integer ÷nd, const Integer &divisor);
#endif
};
//! \brief Comparison
inline bool operator==(const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)==0;}
//! \brief Comparison
inline bool operator!=(const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)!=0;}
//! \brief Comparison
inline bool operator> (const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)> 0;}
//! \brief Comparison
inline bool operator>=(const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)>=0;}
//! \brief Comparison
inline bool operator< (const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)< 0;}
//! \brief Comparison
inline bool operator<=(const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)<=0;}
//! \brief Addition
inline CryptoPP::Integer operator+(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Plus(b);}
//! \brief Subtraction
inline CryptoPP::Integer operator-(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Minus(b);}
//! \brief Multiplication
//! \sa a_times_b_mod_c() and a_exp_b_mod_c()
inline CryptoPP::Integer operator*(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Times(b);}
//! \brief Division
inline CryptoPP::Integer operator/(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.DividedBy(b);}
//! \brief Remainder
//! \sa a_times_b_mod_c() and a_exp_b_mod_c()
inline CryptoPP::Integer operator%(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Modulo(b);}
//! \brief Division
inline CryptoPP::Integer operator/(const CryptoPP::Integer &a, CryptoPP::word b) {return a.DividedBy(b);}
//! \brief Remainder
//! \sa a_times_b_mod_c() and a_exp_b_mod_c()
inline CryptoPP::word operator%(const CryptoPP::Integer &a, CryptoPP::word b) {return a.Modulo(b);}
//! \brief Bitwise AND
//! \param a the first Integer
//! \param b the second Integer
//! \returns the result of a & b
//! \details operator&() performs a bitwise AND on the operands. Missing bits are truncated
//! at the most significant bit positions, so the result is as small as the
//! smaller of the operands.
//! \details Internally, Crypto++ uses a sign-magnitude representation. The library
//! does not attempt to interpret bits, and the result is always POSITIVE. If needed,
//! the integer should be converted to a 2's compliment representation before performing
//! the operation.
//! \since Crypto++ 5.7
inline CryptoPP::Integer operator&(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.And(b);}
//! \brief Bitwise OR
//! \param a the first Integer
//! \param b the second Integer
//! \returns the result of a | b
//! \details operator|() performs a bitwise OR on the operands. Missing bits are shifted in
//! at the most significant bit positions, so the result is as large as the
//! larger of the operands.
//! \details Internally, Crypto++ uses a sign-magnitude representation. The library
//! does not attempt to interpret bits, and the result is always POSITIVE. If needed,
//! the integer should be converted to a 2's compliment representation before performing
//! the operation.
//! \since Crypto++ 5.7
inline CryptoPP::Integer operator|(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Or(b);}
//! \brief Bitwise XOR
//! \param a the first Integer
//! \param b the second Integer
//! \returns the result of a ^ b
//! \details operator^() performs a bitwise XOR on the operands. Missing bits are shifted
//! in at the most significant bit positions, so the result is as large as the
//! larger of the operands.
//! \details Internally, Crypto++ uses a sign-magnitude representation. The library
//! does not attempt to interpret bits, and the result is always POSITIVE. If needed,
//! the integer should be converted to a 2's compliment representation before performing
//! the operation.
//! \since Crypto++ 5.7
inline CryptoPP::Integer operator^(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Xor(b);}
NAMESPACE_END
#ifndef __BORLANDC__
NAMESPACE_BEGIN(std)
inline void swap(CryptoPP::Integer &a, CryptoPP::Integer &b)
{
a.swap(b);
}
NAMESPACE_END
#endif
#endif
| {
"pile_set_name": "Github"
} |
{
"@metadata": {
"authors": [
"Ebrahimi-amir",
"Amir a57"
]
},
"browse": "ویکی یه باخیش",
"smw_browselink": "اوزللیکلری گؤزدن کئچیر",
"smw-livepreview-loading": "یوکلنیر..."
}
| {
"pile_set_name": "Github"
} |
// Created by cgo -godefs - DO NOT EDIT
// cgo -godefs defs_freebsd.go
package socket
const (
sysAF_UNSPEC = 0x0
sysAF_INET = 0x2
sysAF_INET6 = 0x1c
sysSOCK_RAW = 0x3
)
type iovec struct {
Base *byte
Len uint64
}
type msghdr struct {
Name *byte
Namelen uint32
Pad_cgo_0 [4]byte
Iov *iovec
Iovlen int32
Pad_cgo_1 [4]byte
Control *byte
Controllen uint32
Flags int32
}
type cmsghdr struct {
Len uint32
Level int32
Type int32
}
type sockaddrInet struct {
Len uint8
Family uint8
Port uint16
Addr [4]byte /* in_addr */
Zero [8]int8
}
type sockaddrInet6 struct {
Len uint8
Family uint8
Port uint16
Flowinfo uint32
Addr [16]byte /* in6_addr */
Scope_id uint32
}
const (
sizeofIovec = 0x10
sizeofMsghdr = 0x30
sizeofCmsghdr = 0xc
sizeofSockaddrInet = 0x10
sizeofSockaddrInet6 = 0x1c
)
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Zest</title>
</head>
<body bgcolor="#ffffff">
<h1>Zest</h1>
<p>
Zest is an experimental specialized scripting language (also known as a domain-specific language)
developed by the Mozilla security team and is intended to be used in web oriented security tools.
<p>
It is included by default with ZAP.<br>
<h2>Creating Zest scripts</h2>
There are a variety of ways to create Zest scripts:
<h3>Record a new Zest script Button</h3>
<ul>
<li>Press the 'Record a new Zest script' button on the main toolbar</li>
<li>Type in a suitable name for your script in the 'Add a Zest Script' dialog</li>
<li>Select the prefix you want to record requests for, or leave blank to record all requests</li>
<li>Press the 'Save' button</li>
<li>The 'Record a new Zest script' button will stay pressed, change to 'Recording a new Zest script' and show a red icon.</li>
</ul>
The new Zest script will be shown in the Scripts tab with a red 'recording' icon.<br>
Any requests that you make underneath the specified prefix will be added to the script.<br>
Press the 'Recording a new Zest script' again to stop recording the requests.<br>
Note that you can only record 'Stand Alone' Zest scripts in this way. If you want to create other types of Zest script you must use another mechanism.
<br><br>
You can also right click any Stand Alone Zest script and use the 'Start recording' and 'Stop recording' buttons.
<h3>New Script Button</h3>
<ul>
<li>Navigate to the Scripts tree tab</li>
<li>Press the 'New Script...' button</li>
<li>Type in a suitable name for your script in the 'New Script' dialog</li>
<li>Select the script type (see the Scripts add-on help page for more details)</li>
<li>Select the Zest script engine</li>
<li>Select one of the templates (if relevant)</li>
<li>Press the 'Save' button</li>
</ul>
Any type of Zest script can be created this way.
<h3>Right clicking a Zest template</h3>
<ul>
<li>Navigate to the Scripts tree tab</li>
<li>Expand the 'Templates' node and find a template you want to use</li>
<li>Right click on the template and select 'New Script...'</li>
<li>Press the 'Save' button</li>
</ul>
Any type of Zest script can be created this way.
<h3>Right clicking requests</h3>
<ul>
<li>Navigate to any tab that shows requests, such as the History tab</li>
<li>Select one or more requests</li>
<li>Right click on them</li>
<li>Select the 'Add to Zest Script' menu which allows you to select an existing Stand Alone script or create a new one</li>
</ul>
Note that you can only add request to 'Stand Alone' Zest scripts.
<h3>Plug-n-Hack</h3>
If you are using a recent version of Firefox then you can create Zest scripts from within your browser.<br>
<ul>
<li>Press the 'Plug-n-Hack' button on the ZAP 'Quick Start' tab</li>
<li>Install the Plug-n-Hack Firefox Add-on and accept all of the dialogs</li>
<li>Press 'Shift F2' in Firefox to access the Developer Toolbar</li>
<li>Type 'zap record on global' to start recording a new Zest script</li>
<li>Any requests you make through ZAP will be added to the script</li>
<li>Type 'zap record off global' to stop recording the script</li>
</ul>
Note that you can only record 'Stand Alone' Zest scripts in this way. If you want to create other types of Zest script you must use another mechanism.
<h2>Editing Zest scripts</h2>
Zest scripts are edited graphically in the Scripts tree tab.<br>
Each statement is a node in the tree - double click nodes to edit the statement properties.<br>
You can add, move and remove statements via right clicking the Zest nodes.<br>
You can also add requests to 'Stand alone' Zest scripts by right clicking the requests in any of the other tabs.<br>
There are also some right click options available when you select text in the Request or Response tabs.<br>
<br>
Zest includes a set of 'built in' variables as well as allowing you to declare your own.<br>
A right click menu is provided (where relevant) in the edit dialogs to allow you to paste in any of the available variable names.<br>
<h2>External links</h2>
<table>
<tr>
<td> </td>
<td><a href="https://developer.mozilla.org/en-US/docs/zest">https://developer.mozilla.org/en-US/docs/zest</a></td>
<td>Zest overview</td></tr>
<tr>
<td> </td>
<td><a href="https://github.com/mozilla/zest">https://github.com/mozilla/zest</a></td>
<td>The Zest github repository, including details of the language</td>
</tr>
</table>
</body>
</html>
| {
"pile_set_name": "Github"
} |
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
| {
"pile_set_name": "Github"
} |
use nom::{le_u8, le_u16, IResult};
use ::api::{Characteristic, UUID, CharPropFlags, ValueNotification};
use bluez::constants::*;
use bluez::protocol::*;
use bytes::{BytesMut, BufMut};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_characteristics() {
let buf = [9, 7, 2, 0, 2, 3, 0, 0, 42, 4, 0, 2, 5, 0, 1, 42, 6, 0, 10, 7, 0, 2, 42];
assert_eq!(characteristics(&buf), Ok((
&[][..],
Ok(vec![
Characteristic {
start_handle: 2,
value_handle: 3,
end_handle: 0xFFFF,
uuid: UUID::B16(0x2A00),
properties: CharPropFlags::READ
},
Characteristic {
start_handle: 4,
value_handle: 5,
end_handle: 0xFFFF,
uuid: UUID::B16(0x2A01),
properties: CharPropFlags::READ
},
Characteristic {
start_handle: 6,
value_handle: 7,
end_handle: 0xFFFF,
uuid: UUID::B16(0x2A02),
properties: CharPropFlags::READ | CharPropFlags::WRITE
},
]
))))
}
#[test]
fn test_value_notification() {
let buf = [27, 46, 0, 165, 17, 5, 0, 0, 130, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
assert_eq!(value_notification(&buf), Ok((
&[][..],
ValueNotification {
handle: 46,
value: vec![165, 17, 5, 0, 0, 130, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
})
));
}
#[test]
fn test_error() {
let buf = [1, 8, 32, 0, 10];
assert_eq!(characteristics(&buf), Ok((
&[][..],
Err(ErrorResponse {
request_opcode: 0x08,
handle: 0x20,
error_code: 0x0a,
})
)))
}
#[test]
fn test_read_req() {
let expected: Vec<u8> = vec![0x0A, 0x25, 0x00];
assert_eq!(expected, read_req(0x0025));
}
}
#[derive(Debug, PartialEq)]
pub struct NotifyResponse {
pub typ: u8,
pub handle: u16,
pub value: u16,
}
named!(pub notify_response<&[u8], NotifyResponse>,
do_parse!(
_op: tag!(&[ATT_OP_READ_BY_TYPE_RESP]) >>
typ: le_u8 >>
handle: le_u16 >>
value: le_u16 >>
(
NotifyResponse { typ, handle, value }
)
));
#[derive(Debug, PartialEq)]
pub struct ExchangeMTURequest {
pub client_rx_mtu: u16,
}
named!(pub mtu_request<&[u8], ExchangeMTURequest>,
do_parse!(
_op: tag!(&[ATT_OP_EXCHANGE_MTU_REQ]) >>
client_rx_mtu: le_u16 >>
(
ExchangeMTURequest { client_rx_mtu }
)
));
#[derive(Debug, PartialEq)]
pub struct ErrorResponse {
request_opcode: u8,
handle: u16,
error_code: u8,
}
named!(pub error_response<&[u8], ErrorResponse>,
do_parse!(
request_opcode: le_u8 >>
handle: le_u16 >>
error_code: le_u8 >>
(
ErrorResponse { request_opcode, handle, error_code }
)
));
named!(pub value_notification<&[u8], ValueNotification>,
do_parse!(
_op: tag!(&[ATT_OP_VALUE_NOTIFICATION]) >>
handle: le_u16 >>
value: many1!(complete!(le_u8)) >>
(
ValueNotification { handle, value }
)
));
fn characteristic(i: &[u8], b16_uuid: bool) -> IResult<&[u8], Characteristic> {
let (i, start_handle) = try_parse!(i, le_u16);
let (i, properties) = try_parse!(i, le_u8);
let (i, value_handle) = try_parse!(i, le_u16);
let (i, uuid) = if b16_uuid {
try_parse!(i, map!(le_u16, |b| UUID::B16(b)))
} else {
try_parse!(i, map!(parse_uuid_128, |b| UUID::B128(b)))
};
Ok((i, Characteristic {
start_handle,
value_handle,
end_handle: 0xFFFF,
uuid,
properties: CharPropFlags::from_bits_truncate(properties),
}))
}
pub fn characteristics(i: &[u8]) -> IResult<&[u8], Result<Vec<Characteristic>, ErrorResponse>> {
let (i, opcode) = try_parse!(i, le_u8);
let (i, result) = match opcode {
ATT_OP_ERROR_RESP => {
try_parse!(i, map!(error_response, |r| Err(r)))
}
ATT_OP_READ_BY_TYPE_RESP => {
let (i, rec_len) = try_parse!(i, le_u8);
let num = i.len() / rec_len as usize;
let b16_uuid = rec_len == 7;
try_parse!(i, map!(count!(apply!(characteristic, b16_uuid), num), |r| Ok(r)))
}
x => {
warn!("unhandled characteristics op type {} for {:?}", x, i);
(&[][..], Ok(vec![]))
}
};
Ok((i, result))
}
pub fn read_by_type_req(start_handle: u16, end_handle: u16, uuid: UUID) -> Vec<u8> {
let mut buf = BytesMut::with_capacity(3 + uuid.size());
buf.put_u8(ATT_OP_READ_BY_TYPE_REQ);
buf.put_u16_le(start_handle);
buf.put_u16_le(end_handle);
match uuid {
UUID::B16(u) => buf.put_u16_le(u),
UUID::B128(u) => buf.put_slice(&u),
}
buf.to_vec()
}
pub fn read_req(handle: u16) -> Vec<u8> {
let mut buf = BytesMut::with_capacity(3);
buf.put_u8(ATT_OP_READ_REQ);
buf.put_u16_le(handle);
buf.to_vec()
}
| {
"pile_set_name": "Github"
} |
$(document).ready(function() {
var today = new Date();
/* getMonth() returns 0-11 */
var month = today.getMonth() + 1;
var date = today.getDate();
var year = today.getFullYear();
if (month == 12 &&
date in {'23': true, '24': true, '25': true, '26': true} ) {
/* Happy Xmas :) */
$("li#title").html("Happy Holidays");
if (date == 24 || date == 25) {
$().jSnow({
vSize:'100',
fadeAway:true
});
}
}
if (month == 12 &&
date in {'30': true, '31': true} ) {
/* Bye :) */
$("li#title").html("Bye " + year);
}
if (month == 1 &&
date in {'1': true, '2': true, '3': true} ) {
/* Hello :) */
$("li#title").html("Hello " + year);
}
});
| {
"pile_set_name": "Github"
} |
// (C) Copyright Edward Diener 2011,2012,2013
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
#if !defined(BOOST_TTI_HAS_STATIC_MEMBER_DATA_HPP)
#define BOOST_TTI_HAS_STATIC_MEMBER_DATA_HPP
#include <boost/config.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/tti/gen/has_static_member_data_gen.hpp>
#include <boost/tti/detail/dstatic_mem_data.hpp>
/*
The succeeding comments in this file are in doxygen format.
*/
/** \file
*/
/// Expands to a metafunction which tests whether a static member data with a particular name and type exists.
/**
trait = the name of the metafunction within the tti namespace.
name = the name of the inner member.
generates a metafunction called "trait" where 'trait' is the macro parameter.
The metafunction types and return:
BOOST_TTI_TP_T = the enclosing type.
BOOST_TTI_TP_TYPE = the static member data type,
in the form of a data type,
in which to look for our 'name'.
returns = 'value' is true if the 'name' exists,
with the BOOST_TTI_TP_TYPE type,
within the enclosing BOOST_TTI_TP_T type,
otherwise 'value' is false.
*/
#define BOOST_TTI_TRAIT_HAS_STATIC_MEMBER_DATA(trait,name) \
BOOST_TTI_DETAIL_TRAIT_HAS_STATIC_MEMBER_DATA(trait,name) \
template<class BOOST_TTI_TP_T,class BOOST_TTI_TP_TYPE> \
struct trait \
{ \
typedef typename \
BOOST_PP_CAT(trait,_detail_hsd)<BOOST_TTI_TP_T,BOOST_TTI_TP_TYPE>::type type; \
BOOST_STATIC_CONSTANT(bool,value=type::value); \
}; \
/**/
/// Expands to a metafunction which tests whether a static member data with a particular name and type exists.
/**
name = the name of the inner member.
generates a metafunction called "has_static_member_data_name" where 'name' is the macro parameter.
The metafunction types and return:
BOOST_TTI_TP_T = the enclosing type.
BOOST_TTI_TP_TYPE = the static member data type,
in the form of a data type,
in which to look for our 'name'.
returns = 'value' is true if the 'name' exists,
with the appropriate BOOST_TTI_TP_TYPE type,
within the enclosing BOOST_TTI_TP_T type,
otherwise 'value' is false.
*/
#define BOOST_TTI_HAS_STATIC_MEMBER_DATA(name) \
BOOST_TTI_TRAIT_HAS_STATIC_MEMBER_DATA \
( \
BOOST_TTI_HAS_STATIC_MEMBER_DATA_GEN(name), \
name \
) \
/**/
#endif // BOOST_TTI_HAS_STATIC_MEMBER_DATA_HPP
| {
"pile_set_name": "Github"
} |
swagger: '2.0'
info:
title: SEMAPHORE
description: Semaphore API
version: "2.2.0"
host: localhost:3000
consumes:
- application/json
produces:
- application/json
- text/plain; charset=utf-8
tags:
- name: authentication
description: Authentication, Logout & API Tokens
- name: project
description: Everything related to a project
- name: user
description: User-related API
schemes:
- http
- https
basePath: /api
definitions:
Pong:
type: string
x-example: pong
Login:
type: object
properties:
auth:
type: string
description: Username/Email address
x-example: [email protected]
password:
type: string
format: password
description: Password
UserRequest:
type: object
properties:
name:
type: string
x-example: Integration Test User
username:
type: string
x-example: test-user
email:
type: string
x-example: [email protected]
alert:
type: boolean
admin:
type: boolean
User:
type: object
properties:
id:
type: integer
minimum: 1
name:
type: string
username:
type: string
email:
type: string
created:
type: string
pattern: ^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-[0-9]{2}T\d{2}:\d{2}:\d{2}Z$
alert:
type: boolean
admin:
type: boolean
APIToken:
type: object
properties:
id:
type: string
created:
type: string
pattern: ^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-[0-9]{2}T\d{2}:\d{2}:\d{2}Z$
expired:
type: boolean
user_id:
type: integer
minimum: 1
ProjectRequest:
type: object
properties:
name:
type: string
alert:
type: boolean
Project:
type: object
properties:
id:
type: integer
minimum: 1
name:
type: string
created:
type: string
pattern: ^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-[0-9]{2}T\d{2}:\d{2}:\d{2}Z$
alert:
type: boolean
AccessKeyRequest:
type: object
properties:
name:
type: string
type:
type: string
enum: [ssh, aws, gcloud, do]
project_id:
type: integer
minimum: 1
x-example: 2
key:
type: string
secret:
type: string
AccessKey:
type: object
properties:
id:
type: integer
name:
type: string
type:
type: string
enum: [ssh, aws, gcloud, do]
project_id:
type: integer
key:
type: string
secret:
type: string
EnvironmentRequest:
type: object
properties:
name:
type: string
project_id:
type: integer
minimum: 1
password:
type: string
json:
type: string
Environment:
type: object
properties:
id:
type: integer
minimum: 1
name:
type: string
project_id:
type: integer
minimum: 1
password:
type: string
json:
type: string
InventoryRequest:
type: object
properties:
name:
type: string
project_id:
type: integer
minimum: 1
inventory:
type: string
key_id:
type: integer
minimum: 1
ssh_key_id:
type: integer
minimum: 1
type:
type: string
enum: [static, file]
Inventory:
type: object
properties:
id:
type: integer
name:
type: string
project_id:
type: integer
inventory:
type: string
key_id:
type: integer
ssh_key_id:
type: integer
type:
type: string
enum: [static, file]
RepositoryRequest:
type: object
properties:
name:
type: string
project_id:
type: integer
git_url:
type: string
ssh_key_id:
type: integer
Repository:
type: object
properties:
id:
type: integer
name:
type: string
project_id:
type: integer
git_url:
type: string
ssh_key_id:
type: integer
Task:
type: object
properties:
id:
type: integer
example: 23
template_id:
type: integer
status:
type: string
debug:
type: boolean
playbook:
type: string
environment:
type: string
TaskOutput:
type: object
properties:
task_id:
type: integer
example: 23
task:
type: string
time:
type: string
format: date-time
output:
type: string
TemplateRequest:
type: object
properties:
ssh_key_id:
type: integer
minimum: 1
project_id:
type: integer
minimum: 1
inventory_id:
type: integer
minimum: 1
repository_id:
type: integer
minimum: 1
environment_id:
type: integer
minimum: 1
alias:
type: string
playbook:
type: string
arguments:
type: string
override_args:
type: boolean
Template:
type: object
properties:
id:
type: integer
minimum: 1
ssh_key_id:
type: integer
minimum: 1
project_id:
type: integer
minimum: 1
inventory_id:
type: integer
minimum: 1
repository_id:
type: integer
environment_id:
type: integer
minimum: 1
alias:
type: string
playbook:
type: string
arguments:
type: string
override_args:
type: boolean
Event:
type: object
properties:
project_id:
type: integer
object_id:
type:
- integer
- 'null'
object_type:
type:
- string
- 'null'
description:
type: string
InfoType:
type: object
properties:
version:
type: string
updateBody:
type: string
update:
type: object
properties:
tag_name:
type: string
securityDefinitions:
cookie:
type: apiKey
name: Cookie
in: header
bearer:
type: apiKey
name: Authorization
in: header
security:
- bearer: []
- cookie: []
parameters:
project_id:
name: project_id
description: Project ID
in: path
type: integer
required: true
x-example: 1
user_id:
name: user_id
description: User ID
in: path
type: integer
required: true
x-example: 2
key_id:
name: key_id
description: key ID
in: path
type: integer
required: true
x-example: 3
repository_id:
name: repository_id
description: repository ID
in: path
type: integer
required: true
x-example: 4
inventory_id:
name: inventory_id
description: inventory ID
in: path
type: integer
required: true
x-example: 5
environment_id:
name: environment_id
description: environment ID
in: path
type: integer
required: true
x-example: 6
template_id:
name: template_id
description: template ID
in: path
type: integer
required: true
x-example: 7
task_id:
name: task_id
description: task ID
in: path
type: integer
required: true
x-example: 8
paths:
/ping:
get:
summary: PING test
produces:
- text/plain
security: [] # No security
responses:
200:
description: Successful "PONG" reply
schema:
$ref: "#/definitions/Pong"
headers:
content-type:
type: string
x-example: text/plain; charset=utf-8
/ws:
get:
summary: Websocket handler
schemes:
- ws
- wss
responses:
200:
description: OK
401:
description: not authenticated
/info:
get:
summary: Fetches information about semaphore
description: you must be authenticated to use this
responses:
200:
description: ok
schema:
$ref: "#/definitions/InfoType"
/upgrade:
get:
summary: Check if new updates available and fetch /info
responses:
204:
description: no update
200:
description: ok
schema:
$ref: "#/definitions/InfoType"
post:
summary: Upgrade the server
responses:
200:
description: Server binary was replaced by new version, server has shut down.
# Authentication
/auth/login:
post:
tags:
- authentication
summary: Performs Login
description: |
Upon success you will be logged in
security: [] # No security
parameters:
- name: Login Body
in: body
required: true
schema:
$ref: '#/definitions/Login'
responses:
204:
description: You are logged in
400:
description: something in body is missing / is invalid
/auth/logout:
post:
tags:
- authentication
summary: Destroys current session
responses:
204:
description: Your session was successfully nuked
# User Tokens
/user:
get:
tags:
- user
summary: Fetch logged in user
responses:
200:
description: User
schema:
$ref: "#/definitions/User"
/user/tokens:
get:
tags:
- authentication
- user
summary: Fetch API tokens for user
responses:
200:
description: API Tokens
schema:
type: array
items:
$ref: "#/definitions/APIToken"
post:
tags:
- authentication
- user
summary: Create an API token
responses:
201:
description: API Token
schema:
$ref: "#/definitions/APIToken"
/user/tokens/{api_token_id}:
parameters:
- name: api_token_id
in: path
type: string
required: true
x-example: "kwofd61g93-yuqvex8efmhjkgnbxlo8mp1tin6spyhu="
delete:
tags:
- authentication
- user
summary: Expires API token
responses:
204:
description: Expired API Token
# User Profiles
/users:
get:
tags:
- user
summary: Fetches all users
responses:
200:
description: Users
schema:
type: array
items:
$ref: "#/definitions/User"
post:
tags:
- user
summary: Creates a user
consumes:
- application/json
parameters:
- name: User
in: body
required: true
schema:
$ref: "#/definitions/UserRequest"
responses:
400:
description: User creation failed
201:
description: User created
schema:
$ref: "#/definitions/User"
/users/{user_id}:
parameters:
- $ref: "#/parameters/user_id"
get:
tags:
- user
summary: Fetches a user profile
responses:
200:
description: User profile
schema:
$ref: "#/definitions/User"
put:
tags:
- user
summary: Updates user details
consumes:
- application/json
parameters:
- name: User
in: body
required: true
schema:
$ref: "#/definitions/UserRequest"
responses:
204:
description: User Updated
delete:
tags:
- user
summary: Deletes user
responses:
204:
description: User deleted
/users/{user_id}/password:
parameters:
- $ref: "#/parameters/user_id"
post:
tags:
- user
summary: Updates user password
consumes:
- application/json
parameters:
- name: Password
in: body
required: true
schema:
type: object
properties:
password:
type: string
format: password
responses:
204:
description: Password updated
# Projects
/projects:
get:
tags:
- projects
summary: Get projects
responses:
200:
description: List of projects
schema:
type: array
items:
$ref: "#/definitions/Project"
post:
tags:
- projects
summary: Create a new project
consumes:
- application/json
parameters:
- name: Project
in: body
required: true
schema:
$ref: '#/definitions/ProjectRequest'
responses:
201:
description: Created project
/events:
get:
summary: Get Events related to Semaphore and projects you are part of
responses:
200:
description: Array of events in chronological order
schema:
type: array
items:
$ref: '#/definitions/Event'
/events/last:
get:
summary: Get last 200 Events related to Semaphore and projects you are part of
responses:
200:
description: Array of events in chronological order
schema:
type: array
items:
$ref: '#/definitions/Event'
/project/{project_id}:
parameters:
- $ref: "#/parameters/project_id"
get:
tags:
- project
summary: Fetch project
responses:
200:
description: Project
schema:
$ref: "#/definitions/Project"
put:
tags:
- project
summary: Update project
parameters:
- name: Project
in: body
required: true
schema:
type: object
properties:
name:
type: string
responses:
204:
description: Project saved
delete:
tags:
- project
summary: Delete project
responses:
204:
description: Project deleted
/project/{project_id}/events:
parameters:
- $ref: '#/parameters/project_id'
get:
tags:
- project
summary: Get Events related to this project
responses:
200:
description: Array of events in chronological order
schema:
type: array
items:
$ref: '#/definitions/Event'
# User management
/project/{project_id}/users:
parameters:
- $ref: "#/parameters/project_id"
get:
tags:
- project
summary: Get users linked to project
parameters:
- name: sort
in: query
required: true
type: string
enum: [name, username, email, admin]
description: sorting name
x-example: email
- name: order
in: query
required: true
type: string
enum: [asc, desc]
description: ordering manner
x-example: desc
responses:
200:
description: Users
schema:
type: array
items:
$ref: "#/definitions/User"
post:
tags:
- project
summary: Link user to project
parameters:
- name: User
in: body
required: true
schema:
type: object
properties:
user_id:
type: integer
minimum: 2
admin:
type: boolean
responses:
204:
description: User added
/project/{project_id}/users/{user_id}:
parameters:
- $ref: "#/parameters/project_id"
- $ref: "#/parameters/user_id"
delete:
tags:
- project
summary: Removes user from project
responses:
204:
description: User removed
/project/{project_id}/users/{user_id}/admin:
parameters:
- $ref: "#/parameters/project_id"
- $ref: "#/parameters/user_id"
post:
tags:
- project
summary: Makes user admin
responses:
204:
description: User made administrator
delete:
tags:
- project
summary: Revoke admin privileges
responses:
204:
description: User admin privileges revoked
# project access keys
/project/{project_id}/keys:
parameters:
- $ref: "#/parameters/project_id"
get:
tags:
- project
summary: Get access keys linked to project
parameters:
# TODO - the space in this parameter name results in a dredd warning
- name: Key type
in: query
required: false
type: string
enum: [ssh, aws, gcloud, do]
description: Filter by key type
x-example: ssh
- name: sort
in: query
required: true
type: string
enum: [name, type]
description: sorting name
x-example: type
- name: order
in: query
required: true
type: string
enum: [asc, desc]
description: ordering manner
x-example: asc
responses:
200:
description: Access Keys
schema:
type: array
items:
$ref: "#/definitions/AccessKey"
post:
tags:
- project
summary: Add access key
parameters:
- name: Access Key
in: body
required: true
schema:
$ref: "#/definitions/AccessKeyRequest"
responses:
204:
description: Access Key created
400:
description: Bad type
/project/{project_id}/keys/{key_id}:
parameters:
- $ref: "#/parameters/project_id"
- $ref: "#/parameters/key_id"
put:
tags:
- project
summary: Updates access key
parameters:
- name: Access Key
in: body
required: true
schema:
$ref: "#/definitions/AccessKeyRequest"
responses:
204:
description: Key updated
400:
description: Bad type
delete:
tags:
- project
summary: Removes access key
responses:
204:
description: access key removed
# project repositories
/project/{project_id}/repositories:
parameters:
- $ref: "#/parameters/project_id"
get:
tags:
- project
summary: Get repositories
parameters:
- name: sort
in: query
required: true
type: string
enum: [name, git_url, ssh_key]
description: sorting name
- name: order
in: query
required: true
type: string
format: asc/desc
enum: [asc, desc]
description: ordering manner
responses:
200:
description: repositories
schema:
type: array
items:
$ref: "#/definitions/Repository"
post:
tags:
- project
summary: Add repository
parameters:
- name: Repository
in: body
required: true
schema:
$ref: "#/definitions/RepositoryRequest"
responses:
204:
description: Repository created
/project/{project_id}/repositories/{repository_id}:
parameters:
- $ref: "#/parameters/project_id"
- $ref: "#/parameters/repository_id"
delete:
tags:
- project
summary: Removes repository
responses:
204:
description: repository removed
# project inventory
/project/{project_id}/inventory:
parameters:
- $ref: "#/parameters/project_id"
get:
tags:
- project
summary: Get inventory
parameters:
- name: sort
in: query
required: true
type: string
description: sorting name
enum: [name, type]
- name: order
in: query
required: true
type: string
description: ordering manner
enum: [asc, desc]
responses:
200:
description: inventory
schema:
type: array
items:
$ref: "#/definitions/Inventory"
post:
tags:
- project
summary: create inventory
parameters:
- name: Inventory
in: body
required: true
schema:
$ref: "#/definitions/InventoryRequest"
responses:
201:
description: inventory created
schema:
$ref: "#/definitions/Inventory"
/project/{project_id}/inventory/{inventory_id}:
parameters:
- $ref: "#/parameters/project_id"
- $ref: "#/parameters/inventory_id"
put:
tags:
- project
summary: Updates inventory
parameters:
- name: Inventory
in: body
required: true
schema:
$ref: "#/definitions/InventoryRequest"
responses:
204:
description: Inventory updated
delete:
tags:
- project
summary: Removes inventory
responses:
204:
description: inventory removed
# project environment
/project/{project_id}/environment:
parameters:
- $ref: "#/parameters/project_id"
get:
tags:
- project
summary: Get environment
parameters:
- name: sort
in: query
required: true
type: string
format: name
description: sorting name
x-example: 'db-deploy'
- name: order
in: query
required: true
type: string
format: asc/desc
description: ordering manner
x-example: desc
responses:
200:
description: environment
schema:
type: array
items:
$ref: "#/definitions/Environment"
post:
tags:
- project
summary: Add environment
parameters:
- name: environment
in: body
required: true
schema:
$ref: "#/definitions/EnvironmentRequest"
responses:
204:
description: Environment created
/project/{project_id}/environment/{environment_id}:
parameters:
- $ref: "#/parameters/project_id"
- $ref: "#/parameters/environment_id"
put:
tags:
- project
summary: Update environment
parameters:
- name: environment
in: body
required: true
schema:
$ref: "#/definitions/EnvironmentRequest"
responses:
204:
description: Environment Updated
delete:
tags:
- project
summary: Removes environment
responses:
204:
description: environment removed
# project templates
/project/{project_id}/templates:
parameters:
- $ref: "#/parameters/project_id"
get:
tags:
- project
summary: Get template
parameters:
- name: sort
in: query
required: true
type: string
description: sorting name
enum: [alias, playbook, ssh_key, inventory, environment, repository]
- name: order
in: query
required: true
type: string
description: ordering manner
enum: [asc, desc]
responses:
200:
description: template
schema:
type: array
items:
$ref: "#/definitions/Template"
post:
tags:
- project
summary: create template
parameters:
- name: template
in: body
required: true
schema:
$ref: "#/definitions/TemplateRequest"
responses:
201:
description: template created
schema:
$ref: "#/definitions/Template"
/project/{project_id}/templates/{template_id}:
parameters:
- $ref: "#/parameters/project_id"
- $ref: "#/parameters/template_id"
put:
tags:
- project
summary: Updates template
parameters:
- name: template
in: body
required: true
schema:
$ref: "#/definitions/TemplateRequest"
responses:
204:
description: template updated
delete:
tags:
- project
summary: Removes template
responses:
204:
description: template removed
# tasks
/project/{project_id}/tasks:
parameters:
- $ref: "#/parameters/project_id"
get:
tags:
- project
summary: Get Tasks related to current project
responses:
200:
description: Array of tasks in chronological order
schema:
type: array
items:
$ref: '#/definitions/Task'
post:
tags:
- project
summary: Starts a job
parameters:
- name: task
in: body
required: true
schema:
type: object
properties:
template_id:
type: integer
debug:
type: boolean
dry_run:
type: boolean
playbook:
type: string
environment:
type: string
responses:
201:
description: Task queued
schema:
$ref: "#/definitions/Task"
/project/{project_id}/tasks/last:
parameters:
- $ref: "#/parameters/project_id"
get:
tags:
- project
summary: Get last 200 Tasks related to current project
responses:
200:
description: Array of tasks in chronological order
schema:
type: array
items:
$ref: '#/definitions/Task'
/project/{project_id}/tasks/{task_id}:
parameters:
- $ref: "#/parameters/project_id"
- $ref: "#/parameters/task_id"
get:
tags:
- project
summary: Get a single task
responses:
200:
description: Task
schema:
$ref: "#/definitions/Task"
delete:
tags:
- project
summary: Deletes task (including output)
responses:
204:
description: task deleted
/project/{project_id}/tasks/{task_id}/output:
parameters:
- $ref: '#/parameters/project_id'
- $ref: '#/parameters/task_id'
get:
tags:
- project
summary: Get task output
responses:
200:
description: output
schema:
type: array
items:
$ref: "#/definitions/TaskOutput"
| {
"pile_set_name": "Github"
} |
{
"kind": "discovery#restDescription",
"etag": "\"YWOzh2SDasdU84ArJnpYek-OMdg/NOsFjtPY9zRzc3K9F8mQGuDeSj0\"",
"discoveryVersion": "v1",
"id": "cloudmonitoring:v2beta2",
"name": "cloudmonitoring",
"canonicalName": "Cloud Monitoring",
"version": "v2beta2",
"revision": "20170501",
"title": "Cloud Monitoring API",
"description": "Accesses Google Cloud Monitoring data.",
"ownerDomain": "google.com",
"ownerName": "Google",
"icons": {
"x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png",
"x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png"
},
"documentationLink": "https://cloud.google.com/monitoring/v2beta2/",
"protocol": "rest",
"baseUrl": "https://www.googleapis.com/cloudmonitoring/v2beta2/projects/",
"basePath": "/cloudmonitoring/v2beta2/projects/",
"rootUrl": "https://www.googleapis.com/",
"servicePath": "cloudmonitoring/v2beta2/projects/",
"batchPath": "batch",
"parameters": {
"alt": {
"type": "string",
"description": "Data format for the response.",
"default": "json",
"enum": [
"json"
],
"enumDescriptions": [
"Responses with Content-Type of application/json"
],
"location": "query"
},
"fields": {
"type": "string",
"description": "Selector specifying which fields to include in a partial response.",
"location": "query"
},
"key": {
"type": "string",
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.",
"location": "query"
},
"oauth_token": {
"type": "string",
"description": "OAuth 2.0 token for the current user.",
"location": "query"
},
"prettyPrint": {
"type": "boolean",
"description": "Returns response with indentations and line breaks.",
"default": "true",
"location": "query"
},
"quotaUser": {
"type": "string",
"description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.",
"location": "query"
},
"userIp": {
"type": "string",
"description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.",
"location": "query"
}
},
"auth": {
"oauth2": {
"scopes": {
"https://www.googleapis.com/auth/cloud-platform": {
"description": "View and manage your data across Google Cloud Platform services"
},
"https://www.googleapis.com/auth/monitoring": {
"description": "View and write monitoring data for all of your Google and third-party Cloud and API projects"
}
}
}
},
"schemas": {
"DeleteMetricDescriptorResponse": {
"id": "DeleteMetricDescriptorResponse",
"type": "object",
"description": "The response of cloudmonitoring.metricDescriptors.delete.",
"properties": {
"kind": {
"type": "string",
"description": "Identifies what kind of resource this is. Value: the fixed string \"cloudmonitoring#deleteMetricDescriptorResponse\".",
"default": "cloudmonitoring#deleteMetricDescriptorResponse"
}
}
},
"ListMetricDescriptorsRequest": {
"id": "ListMetricDescriptorsRequest",
"type": "object",
"description": "The request of cloudmonitoring.metricDescriptors.list.",
"properties": {
"kind": {
"type": "string",
"description": "Identifies what kind of resource this is. Value: the fixed string \"cloudmonitoring#listMetricDescriptorsRequest\".",
"default": "cloudmonitoring#listMetricDescriptorsRequest"
}
}
},
"ListMetricDescriptorsResponse": {
"id": "ListMetricDescriptorsResponse",
"type": "object",
"description": "The response of cloudmonitoring.metricDescriptors.list.",
"properties": {
"kind": {
"type": "string",
"description": "Identifies what kind of resource this is. Value: the fixed string \"cloudmonitoring#listMetricDescriptorsResponse\".",
"default": "cloudmonitoring#listMetricDescriptorsResponse"
},
"metrics": {
"type": "array",
"description": "The returned metric descriptors.",
"items": {
"$ref": "MetricDescriptor"
}
},
"nextPageToken": {
"type": "string",
"description": "Pagination token. If present, indicates that additional results are available for retrieval. To access the results past the pagination limit, pass this value to the pageToken query parameter."
}
}
},
"ListTimeseriesDescriptorsRequest": {
"id": "ListTimeseriesDescriptorsRequest",
"type": "object",
"description": "The request of cloudmonitoring.timeseriesDescriptors.list",
"properties": {
"kind": {
"type": "string",
"description": "Identifies what kind of resource this is. Value: the fixed string \"cloudmonitoring#listTimeseriesDescriptorsRequest\".",
"default": "cloudmonitoring#listTimeseriesDescriptorsRequest"
}
}
},
"ListTimeseriesDescriptorsResponse": {
"id": "ListTimeseriesDescriptorsResponse",
"type": "object",
"description": "The response of cloudmonitoring.timeseriesDescriptors.list",
"properties": {
"kind": {
"type": "string",
"description": "Identifies what kind of resource this is. Value: the fixed string \"cloudmonitoring#listTimeseriesDescriptorsResponse\".",
"default": "cloudmonitoring#listTimeseriesDescriptorsResponse"
},
"nextPageToken": {
"type": "string",
"description": "Pagination token. If present, indicates that additional results are available for retrieval. To access the results past the pagination limit, set this value to the pageToken query parameter."
},
"oldest": {
"type": "string",
"description": "The oldest timestamp of the interval of this query, as an RFC 3339 string.",
"format": "date-time"
},
"timeseries": {
"type": "array",
"description": "The returned time series descriptors.",
"items": {
"$ref": "TimeseriesDescriptor"
}
},
"youngest": {
"type": "string",
"description": "The youngest timestamp of the interval of this query, as an RFC 3339 string.",
"format": "date-time"
}
}
},
"ListTimeseriesRequest": {
"id": "ListTimeseriesRequest",
"type": "object",
"description": "The request of cloudmonitoring.timeseries.list",
"properties": {
"kind": {
"type": "string",
"description": "Identifies what kind of resource this is. Value: the fixed string \"cloudmonitoring#listTimeseriesRequest\".",
"default": "cloudmonitoring#listTimeseriesRequest"
}
}
},
"ListTimeseriesResponse": {
"id": "ListTimeseriesResponse",
"type": "object",
"description": "The response of cloudmonitoring.timeseries.list",
"properties": {
"kind": {
"type": "string",
"description": "Identifies what kind of resource this is. Value: the fixed string \"cloudmonitoring#listTimeseriesResponse\".",
"default": "cloudmonitoring#listTimeseriesResponse"
},
"nextPageToken": {
"type": "string",
"description": "Pagination token. If present, indicates that additional results are available for retrieval. To access the results past the pagination limit, set the pageToken query parameter to this value. All of the points of a time series will be returned before returning any point of the subsequent time series."
},
"oldest": {
"type": "string",
"description": "The oldest timestamp of the interval of this query as an RFC 3339 string.",
"format": "date-time"
},
"timeseries": {
"type": "array",
"description": "The returned time series.",
"items": {
"$ref": "Timeseries"
}
},
"youngest": {
"type": "string",
"description": "The youngest timestamp of the interval of this query as an RFC 3339 string.",
"format": "date-time"
}
}
},
"MetricDescriptor": {
"id": "MetricDescriptor",
"type": "object",
"description": "A metricDescriptor defines the name, label keys, and data type of a particular metric.",
"properties": {
"description": {
"type": "string",
"description": "Description of this metric."
},
"labels": {
"type": "array",
"description": "Labels defined for this metric.",
"items": {
"$ref": "MetricDescriptorLabelDescriptor"
}
},
"name": {
"type": "string",
"description": "The name of this metric."
},
"project": {
"type": "string",
"description": "The project ID to which the metric belongs."
},
"typeDescriptor": {
"$ref": "MetricDescriptorTypeDescriptor",
"description": "Type description for this metric."
}
}
},
"MetricDescriptorLabelDescriptor": {
"id": "MetricDescriptorLabelDescriptor",
"type": "object",
"description": "A label in a metric is a description of this metric, including the key of this description (what the description is), and the value for this description.",
"properties": {
"description": {
"type": "string",
"description": "Label description."
},
"key": {
"type": "string",
"description": "Label key."
}
}
},
"MetricDescriptorTypeDescriptor": {
"id": "MetricDescriptorTypeDescriptor",
"type": "object",
"description": "A type in a metric contains information about how the metric is collected and what its data points look like.",
"properties": {
"metricType": {
"type": "string",
"description": "The method of collecting data for the metric. See Metric types."
},
"valueType": {
"type": "string",
"description": "The data type of of individual points in the metric's time series. See Metric value types."
}
}
},
"Point": {
"id": "Point",
"type": "object",
"description": "Point is a single point in a time series. It consists of a start time, an end time, and a value.",
"properties": {
"boolValue": {
"type": "boolean",
"description": "The value of this data point. Either \"true\" or \"false\"."
},
"distributionValue": {
"$ref": "PointDistribution",
"description": "The value of this data point as a distribution. A distribution value can contain a list of buckets and/or an underflowBucket and an overflowBucket. The values of these points can be used to create a histogram."
},
"doubleValue": {
"type": "number",
"description": "The value of this data point as a double-precision floating-point number.",
"format": "double"
},
"end": {
"type": "string",
"description": "The interval [start, end] is the time period to which the point's value applies. For gauge metrics, whose values are instantaneous measurements, this interval should be empty (start should equal end). For cumulative metrics (of which deltas and rates are special cases), the interval should be non-empty. Both start and end are RFC 3339 strings.",
"format": "date-time"
},
"int64Value": {
"type": "string",
"description": "The value of this data point as a 64-bit integer.",
"format": "int64"
},
"start": {
"type": "string",
"description": "The interval [start, end] is the time period to which the point's value applies. For gauge metrics, whose values are instantaneous measurements, this interval should be empty (start should equal end). For cumulative metrics (of which deltas and rates are special cases), the interval should be non-empty. Both start and end are RFC 3339 strings.",
"format": "date-time"
},
"stringValue": {
"type": "string",
"description": "The value of this data point in string format."
}
}
},
"PointDistribution": {
"id": "PointDistribution",
"type": "object",
"description": "Distribution data point value type. When writing distribution points, try to be consistent with the boundaries of your buckets. If you must modify the bucket boundaries, then do so by merging, partitioning, or appending rather than skewing them.",
"properties": {
"buckets": {
"type": "array",
"description": "The finite buckets.",
"items": {
"$ref": "PointDistributionBucket"
}
},
"overflowBucket": {
"$ref": "PointDistributionOverflowBucket",
"description": "The overflow bucket."
},
"underflowBucket": {
"$ref": "PointDistributionUnderflowBucket",
"description": "The underflow bucket."
}
}
},
"PointDistributionBucket": {
"id": "PointDistributionBucket",
"type": "object",
"description": "The histogram's bucket. Buckets that form the histogram of a distribution value. If the upper bound of a bucket, say U1, does not equal the lower bound of the next bucket, say L2, this means that there is no event in [U1, L2).",
"properties": {
"count": {
"type": "string",
"description": "The number of events whose values are in the interval defined by this bucket.",
"format": "int64"
},
"lowerBound": {
"type": "number",
"description": "The lower bound of the value interval of this bucket (inclusive).",
"format": "double"
},
"upperBound": {
"type": "number",
"description": "The upper bound of the value interval of this bucket (exclusive).",
"format": "double"
}
}
},
"PointDistributionOverflowBucket": {
"id": "PointDistributionOverflowBucket",
"type": "object",
"description": "The overflow bucket is a special bucket that does not have the upperBound field; it includes all of the events that are no less than its lower bound.",
"properties": {
"count": {
"type": "string",
"description": "The number of events whose values are in the interval defined by this bucket.",
"format": "int64"
},
"lowerBound": {
"type": "number",
"description": "The lower bound of the value interval of this bucket (inclusive).",
"format": "double"
}
}
},
"PointDistributionUnderflowBucket": {
"id": "PointDistributionUnderflowBucket",
"type": "object",
"description": "The underflow bucket is a special bucket that does not have the lowerBound field; it includes all of the events that are less than its upper bound.",
"properties": {
"count": {
"type": "string",
"description": "The number of events whose values are in the interval defined by this bucket.",
"format": "int64"
},
"upperBound": {
"type": "number",
"description": "The upper bound of the value interval of this bucket (exclusive).",
"format": "double"
}
}
},
"Timeseries": {
"id": "Timeseries",
"type": "object",
"description": "The monitoring data is organized as metrics and stored as data points that are recorded over time. Each data point represents information like the CPU utilization of your virtual machine. A historical record of these data points is called a time series.",
"properties": {
"points": {
"type": "array",
"description": "The data points of this time series. The points are listed in order of their end timestamp, from younger to older.",
"items": {
"$ref": "Point"
}
},
"timeseriesDesc": {
"$ref": "TimeseriesDescriptor",
"description": "The descriptor of this time series."
}
}
},
"TimeseriesDescriptor": {
"id": "TimeseriesDescriptor",
"type": "object",
"description": "TimeseriesDescriptor identifies a single time series.",
"properties": {
"labels": {
"type": "object",
"description": "The label's name.",
"additionalProperties": {
"type": "string",
"description": "The label's name."
}
},
"metric": {
"type": "string",
"description": "The name of the metric."
},
"project": {
"type": "string",
"description": "The Developers Console project number to which this time series belongs."
}
}
},
"TimeseriesDescriptorLabel": {
"id": "TimeseriesDescriptorLabel",
"type": "object",
"properties": {
"key": {
"type": "string",
"description": "The label's name."
},
"value": {
"type": "string",
"description": "The label's value."
}
}
},
"TimeseriesPoint": {
"id": "TimeseriesPoint",
"type": "object",
"description": "When writing time series, TimeseriesPoint should be used instead of Timeseries, to enforce single point for each time series in the timeseries.write request.",
"properties": {
"point": {
"$ref": "Point",
"description": "The data point in this time series snapshot."
},
"timeseriesDesc": {
"$ref": "TimeseriesDescriptor",
"description": "The descriptor of this time series."
}
}
},
"WriteTimeseriesRequest": {
"id": "WriteTimeseriesRequest",
"type": "object",
"description": "The request of cloudmonitoring.timeseries.write",
"properties": {
"commonLabels": {
"type": "object",
"description": "The label's name.",
"additionalProperties": {
"type": "string",
"description": "The label's name."
}
},
"timeseries": {
"type": "array",
"description": "Provide time series specific labels and the data points for each time series. The labels in timeseries and the common_labels should form a complete list of labels that required by the metric.",
"items": {
"$ref": "TimeseriesPoint"
}
}
}
},
"WriteTimeseriesResponse": {
"id": "WriteTimeseriesResponse",
"type": "object",
"description": "The response of cloudmonitoring.timeseries.write",
"properties": {
"kind": {
"type": "string",
"description": "Identifies what kind of resource this is. Value: the fixed string \"cloudmonitoring#writeTimeseriesResponse\".",
"default": "cloudmonitoring#writeTimeseriesResponse"
}
}
}
},
"resources": {
"metricDescriptors": {
"methods": {
"create": {
"id": "cloudmonitoring.metricDescriptors.create",
"path": "{project}/metricDescriptors",
"httpMethod": "POST",
"description": "Create a new metric.",
"parameters": {
"project": {
"type": "string",
"description": "The project id. The value can be the numeric project ID or string-based project name.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"project"
],
"request": {
"$ref": "MetricDescriptor"
},
"response": {
"$ref": "MetricDescriptor"
},
"scopes": [
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/monitoring"
]
},
"delete": {
"id": "cloudmonitoring.metricDescriptors.delete",
"path": "{project}/metricDescriptors/{metric}",
"httpMethod": "DELETE",
"description": "Delete an existing metric.",
"parameters": {
"metric": {
"type": "string",
"description": "Name of the metric.",
"required": true,
"location": "path"
},
"project": {
"type": "string",
"description": "The project ID to which the metric belongs.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"project",
"metric"
],
"response": {
"$ref": "DeleteMetricDescriptorResponse"
},
"scopes": [
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/monitoring"
]
},
"list": {
"id": "cloudmonitoring.metricDescriptors.list",
"path": "{project}/metricDescriptors",
"httpMethod": "GET",
"description": "List metric descriptors that match the query. If the query is not set, then all of the metric descriptors will be returned. Large responses will be paginated, use the nextPageToken returned in the response to request subsequent pages of results by setting the pageToken query parameter to the value of the nextPageToken.",
"parameters": {
"count": {
"type": "integer",
"description": "Maximum number of metric descriptors per page. Used for pagination. If not specified, count = 100.",
"default": "100",
"format": "int32",
"minimum": "1",
"maximum": "1000",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "The pagination token, which is used to page through large result sets. Set this value to the value of the nextPageToken to retrieve the next page of results.",
"location": "query"
},
"project": {
"type": "string",
"description": "The project id. The value can be the numeric project ID or string-based project name.",
"required": true,
"location": "path"
},
"query": {
"type": "string",
"description": "The query used to search against existing metrics. Separate keywords with a space; the service joins all keywords with AND, meaning that all keywords must match for a metric to be returned. If this field is omitted, all metrics are returned. If an empty string is passed with this field, no metrics are returned.",
"location": "query"
}
},
"parameterOrder": [
"project"
],
"request": {
"$ref": "ListMetricDescriptorsRequest"
},
"response": {
"$ref": "ListMetricDescriptorsResponse"
},
"scopes": [
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/monitoring"
]
}
}
},
"timeseries": {
"methods": {
"list": {
"id": "cloudmonitoring.timeseries.list",
"path": "{project}/timeseries/{metric}",
"httpMethod": "GET",
"description": "List the data points of the time series that match the metric and labels values and that have data points in the interval. Large responses are paginated; use the nextPageToken returned in the response to request subsequent pages of results by setting the pageToken query parameter to the value of the nextPageToken.",
"parameters": {
"aggregator": {
"type": "string",
"description": "The aggregation function that will reduce the data points in each window to a single point. This parameter is only valid for non-cumulative metrics with a value type of INT64 or DOUBLE.",
"enum": [
"max",
"mean",
"min",
"sum"
],
"enumDescriptions": [
"",
"",
"",
""
],
"location": "query"
},
"count": {
"type": "integer",
"description": "Maximum number of data points per page, which is used for pagination of results.",
"default": "6000",
"format": "int32",
"minimum": "1",
"maximum": "12000",
"location": "query"
},
"labels": {
"type": "string",
"description": "A collection of labels for the matching time series, which are represented as: \n- key==value: key equals the value \n- key=~value: key regex matches the value \n- key!=value: key does not equal the value \n- key!~value: key regex does not match the value For example, to list all of the time series descriptors for the region us-central1, you could specify:\nlabel=cloud.googleapis.com%2Flocation=~us-central1.*",
"pattern": "(.+?)(==|=~|!=|!~)(.+)",
"repeated": true,
"location": "query"
},
"metric": {
"type": "string",
"description": "Metric names are protocol-free URLs as listed in the Supported Metrics page. For example, compute.googleapis.com/instance/disk/read_ops_count.",
"required": true,
"location": "path"
},
"oldest": {
"type": "string",
"description": "Start of the time interval (exclusive), which is expressed as an RFC 3339 timestamp. If neither oldest nor timespan is specified, the default time interval will be (youngest - 4 hours, youngest]",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "The pagination token, which is used to page through large result sets. Set this value to the value of the nextPageToken to retrieve the next page of results.",
"location": "query"
},
"project": {
"type": "string",
"description": "The project ID to which this time series belongs. The value can be the numeric project ID or string-based project name.",
"required": true,
"location": "path"
},
"timespan": {
"type": "string",
"description": "Length of the time interval to query, which is an alternative way to declare the interval: (youngest - timespan, youngest]. The timespan and oldest parameters should not be used together. Units: \n- s: second \n- m: minute \n- h: hour \n- d: day \n- w: week Examples: 2s, 3m, 4w. Only one unit is allowed, for example: 2w3d is not allowed; you should use 17d instead.\n\nIf neither oldest nor timespan is specified, the default time interval will be (youngest - 4 hours, youngest].",
"pattern": "[0-9]+[smhdw]?",
"location": "query"
},
"window": {
"type": "string",
"description": "The sampling window. At most one data point will be returned for each window in the requested time interval. This parameter is only valid for non-cumulative metric types. Units: \n- m: minute \n- h: hour \n- d: day \n- w: week Examples: 3m, 4w. Only one unit is allowed, for example: 2w3d is not allowed; you should use 17d instead.",
"pattern": "[0-9]+[mhdw]?",
"location": "query"
},
"youngest": {
"type": "string",
"description": "End of the time interval (inclusive), which is expressed as an RFC 3339 timestamp.",
"required": true,
"location": "query"
}
},
"parameterOrder": [
"project",
"metric",
"youngest"
],
"request": {
"$ref": "ListTimeseriesRequest"
},
"response": {
"$ref": "ListTimeseriesResponse"
},
"scopes": [
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/monitoring"
]
},
"write": {
"id": "cloudmonitoring.timeseries.write",
"path": "{project}/timeseries:write",
"httpMethod": "POST",
"description": "Put data points to one or more time series for one or more metrics. If a time series does not exist, a new time series will be created. It is not allowed to write a time series point that is older than the existing youngest point of that time series. Points that are older than the existing youngest point of that time series will be discarded silently. Therefore, users should make sure that points of a time series are written sequentially in the order of their end time.",
"parameters": {
"project": {
"type": "string",
"description": "The project ID. The value can be the numeric project ID or string-based project name.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"project"
],
"request": {
"$ref": "WriteTimeseriesRequest"
},
"response": {
"$ref": "WriteTimeseriesResponse"
},
"scopes": [
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/monitoring"
]
}
}
},
"timeseriesDescriptors": {
"methods": {
"list": {
"id": "cloudmonitoring.timeseriesDescriptors.list",
"path": "{project}/timeseriesDescriptors/{metric}",
"httpMethod": "GET",
"description": "List the descriptors of the time series that match the metric and labels values and that have data points in the interval. Large responses are paginated; use the nextPageToken returned in the response to request subsequent pages of results by setting the pageToken query parameter to the value of the nextPageToken.",
"parameters": {
"aggregator": {
"type": "string",
"description": "The aggregation function that will reduce the data points in each window to a single point. This parameter is only valid for non-cumulative metrics with a value type of INT64 or DOUBLE.",
"enum": [
"max",
"mean",
"min",
"sum"
],
"enumDescriptions": [
"",
"",
"",
""
],
"location": "query"
},
"count": {
"type": "integer",
"description": "Maximum number of time series descriptors per page. Used for pagination. If not specified, count = 100.",
"default": "100",
"format": "int32",
"minimum": "1",
"maximum": "1000",
"location": "query"
},
"labels": {
"type": "string",
"description": "A collection of labels for the matching time series, which are represented as: \n- key==value: key equals the value \n- key=~value: key regex matches the value \n- key!=value: key does not equal the value \n- key!~value: key regex does not match the value For example, to list all of the time series descriptors for the region us-central1, you could specify:\nlabel=cloud.googleapis.com%2Flocation=~us-central1.*",
"pattern": "(.+?)(==|=~|!=|!~)(.+)",
"repeated": true,
"location": "query"
},
"metric": {
"type": "string",
"description": "Metric names are protocol-free URLs as listed in the Supported Metrics page. For example, compute.googleapis.com/instance/disk/read_ops_count.",
"required": true,
"location": "path"
},
"oldest": {
"type": "string",
"description": "Start of the time interval (exclusive), which is expressed as an RFC 3339 timestamp. If neither oldest nor timespan is specified, the default time interval will be (youngest - 4 hours, youngest]",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "The pagination token, which is used to page through large result sets. Set this value to the value of the nextPageToken to retrieve the next page of results.",
"location": "query"
},
"project": {
"type": "string",
"description": "The project ID to which this time series belongs. The value can be the numeric project ID or string-based project name.",
"required": true,
"location": "path"
},
"timespan": {
"type": "string",
"description": "Length of the time interval to query, which is an alternative way to declare the interval: (youngest - timespan, youngest]. The timespan and oldest parameters should not be used together. Units: \n- s: second \n- m: minute \n- h: hour \n- d: day \n- w: week Examples: 2s, 3m, 4w. Only one unit is allowed, for example: 2w3d is not allowed; you should use 17d instead.\n\nIf neither oldest nor timespan is specified, the default time interval will be (youngest - 4 hours, youngest].",
"pattern": "[0-9]+[smhdw]?",
"location": "query"
},
"window": {
"type": "string",
"description": "The sampling window. At most one data point will be returned for each window in the requested time interval. This parameter is only valid for non-cumulative metric types. Units: \n- m: minute \n- h: hour \n- d: day \n- w: week Examples: 3m, 4w. Only one unit is allowed, for example: 2w3d is not allowed; you should use 17d instead.",
"pattern": "[0-9]+[mhdw]?",
"location": "query"
},
"youngest": {
"type": "string",
"description": "End of the time interval (inclusive), which is expressed as an RFC 3339 timestamp.",
"required": true,
"location": "query"
}
},
"parameterOrder": [
"project",
"metric",
"youngest"
],
"request": {
"$ref": "ListTimeseriesDescriptorsRequest"
},
"response": {
"$ref": "ListTimeseriesDescriptorsResponse"
},
"scopes": [
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/monitoring"
]
}
}
}
}
}
| {
"pile_set_name": "Github"
} |
<?php
$lang["category_name_required"] = "";
$lang["expenses_categories_add_item"] = "";
$lang["expenses_categories_cannot_be_deleted"] = "";
$lang["expenses_categories_category_id"] = "";
$lang["expenses_categories_confirm_delete"] = "";
$lang["expenses_categories_confirm_restore"] = "";
$lang["expenses_categories_description"] = "";
$lang["expenses_categories_error_adding_updating"] = "";
$lang["expenses_categories_info"] = "";
$lang["expenses_categories_name"] = "";
$lang["expenses_categories_new"] = "";
$lang["expenses_categories_no_expenses_categories_to_display"] = "";
$lang["expenses_categories_none_selected"] = "";
$lang["expenses_categories_one_or_multiple"] = "";
$lang["expenses_categories_quantity"] = "";
$lang["expenses_categories_successful_adding"] = "";
$lang["expenses_categories_successful_deleted"] = "";
$lang["expenses_categories_successful_updating"] = "";
$lang["expenses_categories_update"] = "";
| {
"pile_set_name": "Github"
} |
/****************************************************************************
* Copyright (c) 2007 Free Software Foundation, Inc. *
* *
* 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, distribute with modifications, 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 ABOVE 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. *
* *
* Except as contained in this notice, the name(s) of the above copyright *
* holders shall not be used in advertising or otherwise to promote the *
* sale, use or other dealings in this Software without prior written *
* authorization. *
****************************************************************************/
/*
** lib_key_name.c
**
** The routine key_name().
**
*/
#include <curses.priv.h>
MODULE_ID("$Id: lib_key_name.c,v 1.3 2008/10/11 20:15:14 tom Exp $")
NCURSES_EXPORT(NCURSES_CONST char *)
key_name(wchar_t c)
{
cchar_t my_cchar;
wchar_t *my_wchars;
size_t len;
/* FIXME: move to _nc_globals */
static char result[MB_LEN_MAX + 1];
memset(&my_cchar, 0, sizeof(my_cchar));
my_cchar.chars[0] = c;
my_cchar.chars[1] = L'\0';
my_wchars = wunctrl(&my_cchar);
len = wcstombs(result, my_wchars, sizeof(result) - 1);
if (isEILSEQ(len) || (len == 0)) {
return 0;
}
result[len] = '\0';
return result;
}
| {
"pile_set_name": "Github"
} |
// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#ifndef LAYER_DEQUANTIZE_H
#define LAYER_DEQUANTIZE_H
#include "layer.h"
namespace ncnn {
class Dequantize : public Layer
{
public:
Dequantize();
virtual int load_param(const ParamDict& pd);
virtual int load_model(const ModelBin& mb);
virtual int forward_inplace(Mat& bottom_top_blob, const Option& opt) const;
public:
float scale;
int bias_term;
int bias_data_size;
Mat bias_data;
};
} // namespace ncnn
#endif // LAYER_DEQUANTIZE_H
| {
"pile_set_name": "Github"
} |
#================================================================#
# Copyright (c) 2010-2011 Zipline Games, Inc.
# All Rights Reserved.
# http://getmoai.com
#================================================================#
include $(CLEAR_VARS)
LOCAL_MODULE := crypto-b
LOCAL_ARM_MODE := $(MY_ARM_MODE)
LOCAL_CFLAGS := $(MY_CFLAGS)
LOCAL_C_INCLUDES := $(MY_HEADER_SEARCH_PATHS)
include ../../lists/crypto-b.mk
include $(BUILD_STATIC_LIBRARY) | {
"pile_set_name": "Github"
} |
// @flow
import React, { Component } from "react";
import { Provider } from "react-redux";
import thunk from "redux-thunk";
import { createStore, applyMiddleware, compose } from "redux";
import { getAccounts, getCountervalues, getSettings, getBle } from "../db";
import CounterValues from "../countervalues";
import reducers from "../reducers";
import { importSettings } from "../actions/settings";
import { importStore as importAccounts } from "../actions/accounts";
import { importBle } from "../actions/ble";
import { INITIAL_STATE, supportedCountervalues } from "../reducers/settings";
const createLedgerStore = () =>
createStore(
reducers,
undefined,
// $FlowFixMe
compose(
applyMiddleware(thunk),
typeof __REDUX_DEVTOOLS_EXTENSION__ === "function"
? __REDUX_DEVTOOLS_EXTENSION__()
: f => f,
),
);
export default class LedgerStoreProvider extends Component<
{
onInitFinished: () => void,
children: (ready: boolean, store: *) => *,
},
{
store: *,
ready: boolean,
},
> {
state = {
store: createLedgerStore(),
ready: false,
};
componentDidMount() {
return this.init();
}
componentDidCatch(e: *) {
console.error(e);
throw e;
}
async init() {
const { store } = this.state;
const bleData = await getBle();
store.dispatch(importBle(bleData));
const settingsData = await getSettings();
if (
settingsData &&
settingsData.counterValue &&
!supportedCountervalues.find(
({ ticker }) => ticker === settingsData.counterValue,
)
) {
settingsData.counterValue = INITIAL_STATE.counterValue;
}
store.dispatch(importSettings(settingsData));
const accountsData = await getAccounts();
store.dispatch(importAccounts(accountsData));
const countervaluesData = await getCountervalues();
store.dispatch(CounterValues.importAction(countervaluesData));
this.setState({ ready: true }, () => {
this.props.onInitFinished();
});
}
render() {
const { children } = this.props;
const { store, ready } = this.state;
return <Provider store={store}>{children(ready, store)}</Provider>;
}
}
| {
"pile_set_name": "Github"
} |
from unittest.mock import patch
from .....graphql.csv.enums import ProductFieldEnum
from .....product.models import Attribute, Product, ProductImage, VariantImage
from .....warehouse.models import Warehouse
from ....utils.products_data import (
ProductExportFields,
add_attribute_info_to_data,
add_collection_info_to_data,
add_image_uris_to_data,
add_warehouse_info_to_data,
get_products_relations_data,
get_variants_relations_data,
prepare_products_relations_data,
prepare_variants_relations_data,
)
@patch("saleor.csv.utils.products_data.prepare_products_relations_data")
def test_get_products_relations_data(prepare_products_data_mocked, product_list):
# given
qs = Product.objects.all()
export_fields = {
"collections__slug" "images__image",
"name",
"description",
}
attribute_ids = []
# when
get_products_relations_data(qs, export_fields, attribute_ids)
# then
prepare_products_data_mocked.called_once_with(
qs, {"collections__slug", "images__image"}, attribute_ids
)
@patch("saleor.csv.utils.products_data.prepare_products_relations_data")
def test_get_products_relations_data_no_relations_fields(
prepare_products_data_mocked, product_list
):
# given
qs = Product.objects.all()
export_fields = {"name", "description"}
attribute_ids = []
# when
get_products_relations_data(qs, export_fields, attribute_ids)
# then
prepare_products_data_mocked.assert_not_called()
@patch("saleor.csv.utils.products_data.prepare_products_relations_data")
def test_get_products_relations_data_attribute_ids(
prepare_products_data_mocked, product_list
):
# given
qs = Product.objects.all()
export_fields = {"name", "description"}
attribute_ids = list(Attribute.objects.values_list("pk", flat=True))
# when
get_products_relations_data(qs, export_fields, attribute_ids)
# then
prepare_products_data_mocked.called_once_with(qs, {}, attribute_ids)
def test_prepare_products_relations_data(product_with_image, collection_list):
# given
pk = product_with_image.pk
collection_list[0].products.add(product_with_image)
collection_list[1].products.add(product_with_image)
qs = Product.objects.all()
fields = set(
ProductExportFields.HEADERS_TO_FIELDS_MAPPING["product_many_to_many"].values()
)
attribute_ids = [
str(attr.assignment.attribute.pk)
for attr in product_with_image.attributes.all()
]
# when
result = prepare_products_relations_data(qs, fields, attribute_ids)
# then
collections = ", ".join(
sorted([collection.slug for collection in collection_list[:2]])
)
images = ", ".join(
[
"http://mirumee.com/media/" + image.image.name
for image in product_with_image.images.all()
]
)
expected_result = {pk: {"collections__slug": collections, "images__image": images}}
assigned_attribute = product_with_image.attributes.first()
if assigned_attribute:
header = f"{assigned_attribute.attribute.slug} (product attribute)"
expected_result[pk][header] = assigned_attribute.values.first().slug
assert result == expected_result
def test_prepare_products_relations_data_only_fields(
product_with_image, collection_list
):
# given
pk = product_with_image.pk
collection_list[0].products.add(product_with_image)
collection_list[1].products.add(product_with_image)
qs = Product.objects.all()
fields = {"collections__slug"}
attribute_ids = []
# when
result = prepare_products_relations_data(qs, fields, attribute_ids)
# then
collections = ", ".join(
sorted([collection.slug for collection in collection_list[:2]])
)
expected_result = {pk: {"collections__slug": collections}}
assert result == expected_result
def test_prepare_products_relations_data_only_attributes_ids(
product_with_image, collection_list
):
# given
pk = product_with_image.pk
collection_list[0].products.add(product_with_image)
collection_list[1].products.add(product_with_image)
qs = Product.objects.all()
fields = {"name"}
attribute_ids = [
str(attr.assignment.attribute.pk)
for attr in product_with_image.attributes.all()
]
# when
result = prepare_products_relations_data(qs, fields, attribute_ids)
# then
expected_result = {pk: {}}
assigned_attribute = product_with_image.attributes.first()
if assigned_attribute:
header = f"{assigned_attribute.attribute.slug} (product attribute)"
expected_result[pk][header] = assigned_attribute.values.first().slug
assert result == expected_result
@patch("saleor.csv.utils.products_data.prepare_variants_relations_data")
def test_get_variants_relations_data(prepare_variants_data_mocked, product_list):
# given
qs = Product.objects.all()
export_fields = {
"collections__slug",
"variants__sku",
"variants__images__image",
}
attribute_ids = []
warehouse_ids = []
# when
get_variants_relations_data(qs, export_fields, attribute_ids, warehouse_ids)
# then
prepare_variants_data_mocked.called_once_with(
qs, {ProductFieldEnum.VARIANT_IMAGES.value}, attribute_ids, warehouse_ids
)
@patch("saleor.csv.utils.products_data.prepare_variants_relations_data")
def test_get_variants_relations_data_no_relations_fields(
prepare_variants_data_mocked, product_list
):
# given
qs = Product.objects.all()
export_fields = {"name", "variants__sku"}
attribute_ids = []
warehouse_ids = []
# when
get_variants_relations_data(qs, export_fields, attribute_ids, warehouse_ids)
# then
prepare_variants_data_mocked.assert_not_called()
@patch("saleor.csv.utils.products_data.prepare_variants_relations_data")
def test_get_variants_relations_data_attribute_ids(
prepare_variants_data_mocked, product_list
):
# given
qs = Product.objects.all()
export_fields = {"name", "variants__sku"}
attribute_ids = list(Attribute.objects.values_list("pk", flat=True))
warehouse_ids = []
# when
get_variants_relations_data(qs, export_fields, attribute_ids, warehouse_ids)
# then
prepare_variants_data_mocked.called_once_with(qs, {}, attribute_ids, warehouse_ids)
@patch("saleor.csv.utils.products_data.prepare_variants_relations_data")
def test_get_variants_relations_data_warehouse_ids(
prepare_variants_data_mocked, product_list, warehouses
):
# given
qs = Product.objects.all()
export_fields = {"name", "variants__sku"}
attribute_ids = []
warehouse_ids = list(Warehouse.objects.values_list("pk", flat=True))
# when
get_variants_relations_data(qs, export_fields, attribute_ids, warehouse_ids)
# then
prepare_variants_data_mocked.called_once_with(qs, {}, attribute_ids, warehouse_ids)
@patch("saleor.csv.utils.products_data.prepare_variants_relations_data")
def test_get_variants_relations_data_attributes_and_warehouses_ids(
prepare_variants_data_mocked, product_list, warehouses
):
# given
qs = Product.objects.all()
export_fields = {"name", "description"}
attribute_ids = list(Attribute.objects.values_list("pk", flat=True))
warehouse_ids = list(Warehouse.objects.values_list("pk", flat=True))
# when
get_variants_relations_data(qs, export_fields, attribute_ids, warehouse_ids)
# then
prepare_variants_data_mocked.called_once_with(qs, {}, attribute_ids, warehouse_ids)
def test_prepare_variants_relations_data(
product_with_variant_with_two_attributes, image, media_root
):
# given
qs = Product.objects.all()
variant = product_with_variant_with_two_attributes.variants.first()
product_image = ProductImage.objects.create(
product=product_with_variant_with_two_attributes, image=image
)
VariantImage.objects.create(variant=variant, image=product_image)
fields = {"variants__images__image"}
attribute_ids = [str(attr.pk) for attr in Attribute.objects.all()]
warehouse_ids = [str(w.pk) for w in Warehouse.objects.all()]
# when
result = prepare_variants_relations_data(qs, fields, attribute_ids, warehouse_ids)
# then
pk = variant.pk
images = ", ".join(
[
"http://mirumee.com/media/" + image.image.name
for image in variant.images.all()
]
)
expected_result = {pk: {"variants__images__image": images}}
for assigned_attribute in variant.attributes.all():
header = f"{assigned_attribute.attribute.slug} (variant attribute)"
if str(assigned_attribute.attribute.pk) in attribute_ids:
expected_result[pk][header] = assigned_attribute.values.first().slug
for stock in variant.stocks.all():
if str(stock.warehouse.pk) in warehouse_ids:
slug = stock.warehouse.slug
warehouse_headers = [
f"{slug} (warehouse quantity)",
]
expected_result[pk][warehouse_headers[0]] = stock.quantity
assert result == expected_result
def test_prepare_variants_relations_data_only_fields(
product_with_variant_with_two_attributes, image, media_root
):
# given
qs = Product.objects.all()
variant = product_with_variant_with_two_attributes.variants.first()
product_image = ProductImage.objects.create(
product=product_with_variant_with_two_attributes, image=image
)
VariantImage.objects.create(variant=variant, image=product_image)
fields = {"variants__images__image"}
attribute_ids = []
warehouse_ids = []
# when
result = prepare_variants_relations_data(qs, fields, attribute_ids, warehouse_ids)
# then
pk = variant.pk
images = ", ".join(
[
"http://mirumee.com/media/" + image.image.name
for image in variant.images.all()
]
)
expected_result = {pk: {"variants__images__image": images}}
assert result == expected_result
def test_prepare_variants_relations_data_attributes_ids(
product_with_variant_with_two_attributes, image, media_root
):
# given
qs = Product.objects.all()
variant = product_with_variant_with_two_attributes.variants.first()
product_image = ProductImage.objects.create(
product=product_with_variant_with_two_attributes, image=image
)
VariantImage.objects.create(variant=variant, image=product_image)
fields = set()
attribute_ids = [str(attr.pk) for attr in Attribute.objects.all()]
warehouse_ids = []
# when
result = prepare_variants_relations_data(qs, fields, attribute_ids, warehouse_ids)
# then
pk = variant.pk
expected_result = {pk: {}}
for assigned_attribute in variant.attributes.all():
header = f"{assigned_attribute.attribute.slug} (variant attribute)"
if str(assigned_attribute.attribute.pk) in attribute_ids:
expected_result[pk][header] = assigned_attribute.values.first().slug
assert result == expected_result
def test_prepare_variants_relations_data_warehouse_ids(
product_with_single_variant, image, media_root
):
# given
qs = Product.objects.all()
variant = product_with_single_variant.variants.first()
fields = set()
attribute_ids = []
warehouse_ids = [str(w.pk) for w in Warehouse.objects.all()]
# when
result = prepare_variants_relations_data(qs, fields, attribute_ids, warehouse_ids)
# then
pk = variant.pk
expected_result = {pk: {}}
for stock in variant.stocks.all():
if str(stock.warehouse.pk) in warehouse_ids:
slug = stock.warehouse.slug
warehouse_headers = [
f"{slug} (warehouse quantity)",
]
expected_result[pk][warehouse_headers[0]] = stock.quantity
assert result == expected_result
def test_add_collection_info_to_data(product):
# given
pk = product.pk
collection = "test_collection"
input_data = {pk: {}}
# when
result = add_collection_info_to_data(product.pk, collection, input_data)
# then
assert result[pk]["collections__slug"] == {collection}
def test_add_collection_info_to_data_update_collections(product):
# given
pk = product.pk
existing_collection = "test2"
collection = "test_collection"
input_data = {pk: {"collections__slug": {existing_collection}}}
# when
result = add_collection_info_to_data(product.pk, collection, input_data)
# then
assert result[pk]["collections__slug"] == {collection, existing_collection}
def test_add_collection_info_to_data_no_collection(product):
# given
pk = product.pk
collection = None
input_data = {pk: {}}
# when
result = add_collection_info_to_data(product.pk, collection, input_data)
# then
assert result == input_data
def test_add_image_uris_to_data(product):
# given
pk = product.pk
image_path = "test/path/image.jpg"
field = "variant_images"
input_data = {pk: {}}
# when
result = add_image_uris_to_data(product.pk, image_path, field, input_data)
# then
assert result[pk][field] == {"http://mirumee.com/media/" + image_path}
def test_add_image_uris_to_data_update_images(product):
# given
pk = product.pk
old_path = "http://mirumee.com/media/test/image0.jpg"
image_path = "test/path/image.jpg"
input_data = {pk: {"product_images": {old_path}}}
field = "product_images"
# when
result = add_image_uris_to_data(product.pk, image_path, field, input_data)
# then
assert result[pk][field] == {"http://mirumee.com/media/" + image_path, old_path}
def test_add_image_uris_to_data_no_image_path(product):
# given
pk = product.pk
image_path = None
input_data = {pk: {"name": "test"}}
# when
result = add_image_uris_to_data(
product.pk, image_path, "product_images", input_data
)
# then
assert result == input_data
def test_add_attribute_info_to_data(product):
# given
pk = product.pk
slug = "test_attribute_slug"
value = "test value"
attribute_data = {
"slug": slug,
"value": value,
}
input_data = {pk: {}}
# when
result = add_attribute_info_to_data(
product.pk, attribute_data, "product attribute", input_data
)
# then
expected_header = f"{slug} (product attribute)"
assert result[pk][expected_header] == {value}
def test_add_attribute_info_to_data_update_attribute_data(product):
# given
pk = product.pk
slug = "test_attribute_slug"
value = "test value"
expected_header = f"{slug} (variant attribute)"
attribute_data = {
"slug": slug,
"value": value,
}
input_data = {pk: {expected_header: {"value1"}}}
# when
result = add_attribute_info_to_data(
product.pk, attribute_data, "variant attribute", input_data
)
# then
assert result[pk][expected_header] == {value, "value1"}
def test_add_attribute_info_to_data_no_slug(product):
# given
pk = product.pk
attribute_data = {
"slug": None,
"value": None,
}
input_data = {pk: {}}
# when
result = add_attribute_info_to_data(
product.pk, attribute_data, "variant attribute", input_data
)
# then
assert result == input_data
def test_add_warehouse_info_to_data(product):
# given
pk = product.pk
slug = "test_warehouse"
warehouse_data = {
"slug": slug,
"qty": 12,
"qty_alc": 10,
}
input_data = {pk: {}}
# when
result = add_warehouse_info_to_data(product.pk, warehouse_data, input_data)
# then
expected_header = f"{slug} (warehouse quantity)"
assert result[pk][expected_header] == 12
def test_add_warehouse_info_to_data_data_not_changed(product):
# given
pk = product.pk
slug = "test_warehouse"
warehouse_data = {
"slug": slug,
"qty": 12,
"qty_alc": 10,
}
input_data = {
pk: {
f"{slug} (warehouse quantity)": 5,
f"{slug} (warehouse quantity allocated)": 8,
}
}
# when
result = add_warehouse_info_to_data(product.pk, warehouse_data, input_data)
# then
assert result == input_data
def test_add_warehouse_info_to_data_data_no_slug(product):
# given
pk = product.pk
warehouse_data = {
"slug": None,
"qty": None,
"qty_alc": None,
}
input_data = {pk: {}}
# when
result = add_warehouse_info_to_data(product.pk, warehouse_data, input_data)
# then
assert result == input_data
| {
"pile_set_name": "Github"
} |
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
'use strict';
/**
* The Position namespace provides helper functions to work with
* [Position](#Position) literals.
*/
export var Position;
(function (Position) {
/**
* Creates a new Position literal from the given line and character.
* @param line The position's line.
* @param character The position's character.
*/
function create(line, character) {
return { line: line, character: character };
}
Position.create = create;
/**
* Checks whether the given liternal conforms to the [Position](#Position) interface.
*/
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);
}
Position.is = is;
})(Position || (Position = {}));
/**
* The Range namespace provides helper functions to work with
* [Range](#Range) literals.
*/
export var Range;
(function (Range) {
function create(one, two, three, four) {
if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {
return { start: Position.create(one, two), end: Position.create(three, four) };
}
else if (Position.is(one) && Position.is(two)) {
return { start: one, end: two };
}
else {
throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
}
}
Range.create = create;
/**
* Checks whether the given literal conforms to the [Range](#Range) interface.
*/
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
}
Range.is = is;
})(Range || (Range = {}));
/**
* The Location namespace provides helper functions to work with
* [Location](#Location) literals.
*/
export var Location;
(function (Location) {
/**
* Creates a Location literal.
* @param uri The location's uri.
* @param range The location's range.
*/
function create(uri, range) {
return { uri: uri, range: range };
}
Location.create = create;
/**
* Checks whether the given literal conforms to the [Location](#Location) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
}
Location.is = is;
})(Location || (Location = {}));
/**
* The LocationLink namespace provides helper functions to work with
* [LocationLink](#LocationLink) literals.
*/
export var LocationLink;
(function (LocationLink) {
/**
* Creates a LocationLink literal.
* @param targetUri The definition's uri.
* @param targetRange The full range of the definition.
* @param targetSelectionRange The span of the symbol definition at the target.
* @param originSelectionRange The span of the symbol being defined in the originating source file.
*/
function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };
}
LocationLink.create = create;
/**
* Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)
&& (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))
&& (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
}
LocationLink.is = is;
})(LocationLink || (LocationLink = {}));
/**
* The Color namespace provides helper functions to work with
* [Color](#Color) literals.
*/
export var Color;
(function (Color) {
/**
* Creates a new Color literal.
*/
function create(red, green, blue, alpha) {
return {
red: red,
green: green,
blue: blue,
alpha: alpha,
};
}
Color.create = create;
/**
* Checks whether the given literal conforms to the [Color](#Color) interface.
*/
function is(value) {
var candidate = value;
return Is.number(candidate.red)
&& Is.number(candidate.green)
&& Is.number(candidate.blue)
&& Is.number(candidate.alpha);
}
Color.is = is;
})(Color || (Color = {}));
/**
* The ColorInformation namespace provides helper functions to work with
* [ColorInformation](#ColorInformation) literals.
*/
export var ColorInformation;
(function (ColorInformation) {
/**
* Creates a new ColorInformation literal.
*/
function create(range, color) {
return {
range: range,
color: color,
};
}
ColorInformation.create = create;
/**
* Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
*/
function is(value) {
var candidate = value;
return Range.is(candidate.range) && Color.is(candidate.color);
}
ColorInformation.is = is;
})(ColorInformation || (ColorInformation = {}));
/**
* The Color namespace provides helper functions to work with
* [ColorPresentation](#ColorPresentation) literals.
*/
export var ColorPresentation;
(function (ColorPresentation) {
/**
* Creates a new ColorInformation literal.
*/
function create(label, textEdit, additionalTextEdits) {
return {
label: label,
textEdit: textEdit,
additionalTextEdits: additionalTextEdits,
};
}
ColorPresentation.create = create;
/**
* Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
*/
function is(value) {
var candidate = value;
return Is.string(candidate.label)
&& (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))
&& (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
}
ColorPresentation.is = is;
})(ColorPresentation || (ColorPresentation = {}));
/**
* Enum of known range kinds
*/
export var FoldingRangeKind;
(function (FoldingRangeKind) {
/**
* Folding range for a comment
*/
FoldingRangeKind["Comment"] = "comment";
/**
* Folding range for a imports or includes
*/
FoldingRangeKind["Imports"] = "imports";
/**
* Folding range for a region (e.g. `#region`)
*/
FoldingRangeKind["Region"] = "region";
})(FoldingRangeKind || (FoldingRangeKind = {}));
/**
* The folding range namespace provides helper functions to work with
* [FoldingRange](#FoldingRange) literals.
*/
export var FoldingRange;
(function (FoldingRange) {
/**
* Creates a new FoldingRange literal.
*/
function create(startLine, endLine, startCharacter, endCharacter, kind) {
var result = {
startLine: startLine,
endLine: endLine
};
if (Is.defined(startCharacter)) {
result.startCharacter = startCharacter;
}
if (Is.defined(endCharacter)) {
result.endCharacter = endCharacter;
}
if (Is.defined(kind)) {
result.kind = kind;
}
return result;
}
FoldingRange.create = create;
/**
* Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.
*/
function is(value) {
var candidate = value;
return Is.number(candidate.startLine) && Is.number(candidate.startLine)
&& (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter))
&& (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter))
&& (Is.undefined(candidate.kind) || Is.string(candidate.kind));
}
FoldingRange.is = is;
})(FoldingRange || (FoldingRange = {}));
/**
* The DiagnosticRelatedInformation namespace provides helper functions to work with
* [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.
*/
export var DiagnosticRelatedInformation;
(function (DiagnosticRelatedInformation) {
/**
* Creates a new DiagnosticRelatedInformation literal.
*/
function create(location, message) {
return {
location: location,
message: message
};
}
DiagnosticRelatedInformation.create = create;
/**
* Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
}
DiagnosticRelatedInformation.is = is;
})(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
/**
* The diagnostic's severity.
*/
export var DiagnosticSeverity;
(function (DiagnosticSeverity) {
/**
* Reports an error.
*/
DiagnosticSeverity.Error = 1;
/**
* Reports a warning.
*/
DiagnosticSeverity.Warning = 2;
/**
* Reports an information.
*/
DiagnosticSeverity.Information = 3;
/**
* Reports a hint.
*/
DiagnosticSeverity.Hint = 4;
})(DiagnosticSeverity || (DiagnosticSeverity = {}));
/**
* The Diagnostic namespace provides helper functions to work with
* [Diagnostic](#Diagnostic) literals.
*/
export var Diagnostic;
(function (Diagnostic) {
/**
* Creates a new Diagnostic literal.
*/
function create(range, message, severity, code, source, relatedInformation) {
var result = { range: range, message: message };
if (Is.defined(severity)) {
result.severity = severity;
}
if (Is.defined(code)) {
result.code = code;
}
if (Is.defined(source)) {
result.source = source;
}
if (Is.defined(relatedInformation)) {
result.relatedInformation = relatedInformation;
}
return result;
}
Diagnostic.create = create;
/**
* Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate)
&& Range.is(candidate.range)
&& Is.string(candidate.message)
&& (Is.number(candidate.severity) || Is.undefined(candidate.severity))
&& (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))
&& (Is.string(candidate.source) || Is.undefined(candidate.source))
&& (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
}
Diagnostic.is = is;
})(Diagnostic || (Diagnostic = {}));
/**
* The Command namespace provides helper functions to work with
* [Command](#Command) literals.
*/
export var Command;
(function (Command) {
/**
* Creates a new Command literal.
*/
function create(title, command) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
var result = { title: title, command: command };
if (Is.defined(args) && args.length > 0) {
result.arguments = args;
}
return result;
}
Command.create = create;
/**
* Checks whether the given literal conforms to the [Command](#Command) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
}
Command.is = is;
})(Command || (Command = {}));
/**
* The TextEdit namespace provides helper function to create replace,
* insert and delete edits more easily.
*/
export var TextEdit;
(function (TextEdit) {
/**
* Creates a replace text edit.
* @param range The range of text to be replaced.
* @param newText The new text.
*/
function replace(range, newText) {
return { range: range, newText: newText };
}
TextEdit.replace = replace;
/**
* Creates a insert text edit.
* @param position The position to insert the text at.
* @param newText The text to be inserted.
*/
function insert(position, newText) {
return { range: { start: position, end: position }, newText: newText };
}
TextEdit.insert = insert;
/**
* Creates a delete text edit.
* @param range The range of text to be deleted.
*/
function del(range) {
return { range: range, newText: '' };
}
TextEdit.del = del;
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate)
&& Is.string(candidate.newText)
&& Range.is(candidate.range);
}
TextEdit.is = is;
})(TextEdit || (TextEdit = {}));
/**
* The TextDocumentEdit namespace provides helper function to create
* an edit that manipulates a text document.
*/
export var TextDocumentEdit;
(function (TextDocumentEdit) {
/**
* Creates a new `TextDocumentEdit`
*/
function create(textDocument, edits) {
return { textDocument: textDocument, edits: edits };
}
TextDocumentEdit.create = create;
function is(value) {
var candidate = value;
return Is.defined(candidate)
&& VersionedTextDocumentIdentifier.is(candidate.textDocument)
&& Array.isArray(candidate.edits);
}
TextDocumentEdit.is = is;
})(TextDocumentEdit || (TextDocumentEdit = {}));
export var CreateFile;
(function (CreateFile) {
function create(uri, options) {
var result = {
kind: 'create',
uri: uri
};
if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
result.options = options;
}
return result;
}
CreateFile.create = create;
function is(value) {
var candidate = value;
return candidate && candidate.kind === 'create' && Is.string(candidate.uri) &&
(candidate.options === void 0 ||
((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
}
CreateFile.is = is;
})(CreateFile || (CreateFile = {}));
export var RenameFile;
(function (RenameFile) {
function create(oldUri, newUri, options) {
var result = {
kind: 'rename',
oldUri: oldUri,
newUri: newUri
};
if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
result.options = options;
}
return result;
}
RenameFile.create = create;
function is(value) {
var candidate = value;
return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) &&
(candidate.options === void 0 ||
((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
}
RenameFile.is = is;
})(RenameFile || (RenameFile = {}));
export var DeleteFile;
(function (DeleteFile) {
function create(uri, options) {
var result = {
kind: 'delete',
uri: uri
};
if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
result.options = options;
}
return result;
}
DeleteFile.create = create;
function is(value) {
var candidate = value;
return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) &&
(candidate.options === void 0 ||
((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))));
}
DeleteFile.is = is;
})(DeleteFile || (DeleteFile = {}));
export var WorkspaceEdit;
(function (WorkspaceEdit) {
function is(value) {
var candidate = value;
return candidate &&
(candidate.changes !== void 0 || candidate.documentChanges !== void 0) &&
(candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) {
if (Is.string(change.kind)) {
return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
}
else {
return TextDocumentEdit.is(change);
}
}));
}
WorkspaceEdit.is = is;
})(WorkspaceEdit || (WorkspaceEdit = {}));
var TextEditChangeImpl = /** @class */ (function () {
function TextEditChangeImpl(edits) {
this.edits = edits;
}
TextEditChangeImpl.prototype.insert = function (position, newText) {
this.edits.push(TextEdit.insert(position, newText));
};
TextEditChangeImpl.prototype.replace = function (range, newText) {
this.edits.push(TextEdit.replace(range, newText));
};
TextEditChangeImpl.prototype.delete = function (range) {
this.edits.push(TextEdit.del(range));
};
TextEditChangeImpl.prototype.add = function (edit) {
this.edits.push(edit);
};
TextEditChangeImpl.prototype.all = function () {
return this.edits;
};
TextEditChangeImpl.prototype.clear = function () {
this.edits.splice(0, this.edits.length);
};
return TextEditChangeImpl;
}());
/**
* A workspace change helps constructing changes to a workspace.
*/
var WorkspaceChange = /** @class */ (function () {
function WorkspaceChange(workspaceEdit) {
var _this = this;
this._textEditChanges = Object.create(null);
if (workspaceEdit) {
this._workspaceEdit = workspaceEdit;
if (workspaceEdit.documentChanges) {
workspaceEdit.documentChanges.forEach(function (change) {
if (TextDocumentEdit.is(change)) {
var textEditChange = new TextEditChangeImpl(change.edits);
_this._textEditChanges[change.textDocument.uri] = textEditChange;
}
});
}
else if (workspaceEdit.changes) {
Object.keys(workspaceEdit.changes).forEach(function (key) {
var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
_this._textEditChanges[key] = textEditChange;
});
}
}
}
Object.defineProperty(WorkspaceChange.prototype, "edit", {
/**
* Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal
* use to be returned from a workspace edit operation like rename.
*/
get: function () {
return this._workspaceEdit;
},
enumerable: true,
configurable: true
});
WorkspaceChange.prototype.getTextEditChange = function (key) {
if (VersionedTextDocumentIdentifier.is(key)) {
if (!this._workspaceEdit) {
this._workspaceEdit = {
documentChanges: []
};
}
if (!this._workspaceEdit.documentChanges) {
throw new Error('Workspace edit is not configured for document changes.');
}
var textDocument = key;
var result = this._textEditChanges[textDocument.uri];
if (!result) {
var edits = [];
var textDocumentEdit = {
textDocument: textDocument,
edits: edits
};
this._workspaceEdit.documentChanges.push(textDocumentEdit);
result = new TextEditChangeImpl(edits);
this._textEditChanges[textDocument.uri] = result;
}
return result;
}
else {
if (!this._workspaceEdit) {
this._workspaceEdit = {
changes: Object.create(null)
};
}
if (!this._workspaceEdit.changes) {
throw new Error('Workspace edit is not configured for normal text edit changes.');
}
var result = this._textEditChanges[key];
if (!result) {
var edits = [];
this._workspaceEdit.changes[key] = edits;
result = new TextEditChangeImpl(edits);
this._textEditChanges[key] = result;
}
return result;
}
};
WorkspaceChange.prototype.createFile = function (uri, options) {
this.checkDocumentChanges();
this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));
};
WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) {
this.checkDocumentChanges();
this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));
};
WorkspaceChange.prototype.deleteFile = function (uri, options) {
this.checkDocumentChanges();
this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));
};
WorkspaceChange.prototype.checkDocumentChanges = function () {
if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {
throw new Error('Workspace edit is not configured for document changes.');
}
};
return WorkspaceChange;
}());
export { WorkspaceChange };
/**
* The TextDocumentIdentifier namespace provides helper functions to work with
* [TextDocumentIdentifier](#TextDocumentIdentifier) literals.
*/
export var TextDocumentIdentifier;
(function (TextDocumentIdentifier) {
/**
* Creates a new TextDocumentIdentifier literal.
* @param uri The document's uri.
*/
function create(uri) {
return { uri: uri };
}
TextDocumentIdentifier.create = create;
/**
* Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.string(candidate.uri);
}
TextDocumentIdentifier.is = is;
})(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
/**
* The VersionedTextDocumentIdentifier namespace provides helper functions to work with
* [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.
*/
export var VersionedTextDocumentIdentifier;
(function (VersionedTextDocumentIdentifier) {
/**
* Creates a new VersionedTextDocumentIdentifier literal.
* @param uri The document's uri.
* @param uri The document's text.
*/
function create(uri, version) {
return { uri: uri, version: version };
}
VersionedTextDocumentIdentifier.create = create;
/**
* Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));
}
VersionedTextDocumentIdentifier.is = is;
})(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
/**
* The TextDocumentItem namespace provides helper functions to work with
* [TextDocumentItem](#TextDocumentItem) literals.
*/
export var TextDocumentItem;
(function (TextDocumentItem) {
/**
* Creates a new TextDocumentItem literal.
* @param uri The document's uri.
* @param languageId The document's language identifier.
* @param version The document's version number.
* @param text The document's text.
*/
function create(uri, languageId, version, text) {
return { uri: uri, languageId: languageId, version: version, text: text };
}
TextDocumentItem.create = create;
/**
* Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);
}
TextDocumentItem.is = is;
})(TextDocumentItem || (TextDocumentItem = {}));
/**
* Describes the content type that a client supports in various
* result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
*
* Please note that `MarkupKinds` must not start with a `$`. This kinds
* are reserved for internal usage.
*/
export var MarkupKind;
(function (MarkupKind) {
/**
* Plain text is supported as a content format
*/
MarkupKind.PlainText = 'plaintext';
/**
* Markdown is supported as a content format
*/
MarkupKind.Markdown = 'markdown';
})(MarkupKind || (MarkupKind = {}));
(function (MarkupKind) {
/**
* Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.
*/
function is(value) {
var candidate = value;
return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
}
MarkupKind.is = is;
})(MarkupKind || (MarkupKind = {}));
export var MarkupContent;
(function (MarkupContent) {
/**
* Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.
*/
function is(value) {
var candidate = value;
return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
}
MarkupContent.is = is;
})(MarkupContent || (MarkupContent = {}));
/**
* The kind of a completion entry.
*/
export var CompletionItemKind;
(function (CompletionItemKind) {
CompletionItemKind.Text = 1;
CompletionItemKind.Method = 2;
CompletionItemKind.Function = 3;
CompletionItemKind.Constructor = 4;
CompletionItemKind.Field = 5;
CompletionItemKind.Variable = 6;
CompletionItemKind.Class = 7;
CompletionItemKind.Interface = 8;
CompletionItemKind.Module = 9;
CompletionItemKind.Property = 10;
CompletionItemKind.Unit = 11;
CompletionItemKind.Value = 12;
CompletionItemKind.Enum = 13;
CompletionItemKind.Keyword = 14;
CompletionItemKind.Snippet = 15;
CompletionItemKind.Color = 16;
CompletionItemKind.File = 17;
CompletionItemKind.Reference = 18;
CompletionItemKind.Folder = 19;
CompletionItemKind.EnumMember = 20;
CompletionItemKind.Constant = 21;
CompletionItemKind.Struct = 22;
CompletionItemKind.Event = 23;
CompletionItemKind.Operator = 24;
CompletionItemKind.TypeParameter = 25;
})(CompletionItemKind || (CompletionItemKind = {}));
/**
* Defines whether the insert text in a completion item should be interpreted as
* plain text or a snippet.
*/
export var InsertTextFormat;
(function (InsertTextFormat) {
/**
* The primary text to be inserted is treated as a plain string.
*/
InsertTextFormat.PlainText = 1;
/**
* The primary text to be inserted is treated as a snippet.
*
* A snippet can define tab stops and placeholders with `$1`, `$2`
* and `${3:foo}`. `$0` defines the final tab stop, it defaults to
* the end of the snippet. Placeholders with equal identifiers are linked,
* that is typing in one will update others too.
*
* See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md
*/
InsertTextFormat.Snippet = 2;
})(InsertTextFormat || (InsertTextFormat = {}));
/**
* The CompletionItem namespace provides functions to deal with
* completion items.
*/
export var CompletionItem;
(function (CompletionItem) {
/**
* Create a completion item and seed it with a label.
* @param label The completion item's label
*/
function create(label) {
return { label: label };
}
CompletionItem.create = create;
})(CompletionItem || (CompletionItem = {}));
/**
* The CompletionList namespace provides functions to deal with
* completion lists.
*/
export var CompletionList;
(function (CompletionList) {
/**
* Creates a new completion list.
*
* @param items The completion items.
* @param isIncomplete The list is not complete.
*/
function create(items, isIncomplete) {
return { items: items ? items : [], isIncomplete: !!isIncomplete };
}
CompletionList.create = create;
})(CompletionList || (CompletionList = {}));
export var MarkedString;
(function (MarkedString) {
/**
* Creates a marked string from plain text.
*
* @param plainText The plain text.
*/
function fromPlainText(plainText) {
return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&"); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
}
MarkedString.fromPlainText = fromPlainText;
/**
* Checks whether the given value conforms to the [MarkedString](#MarkedString) type.
*/
function is(value) {
var candidate = value;
return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));
}
MarkedString.is = is;
})(MarkedString || (MarkedString = {}));
export var Hover;
(function (Hover) {
/**
* Checks whether the given value conforms to the [Hover](#Hover) interface.
*/
function is(value) {
var candidate = value;
return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
MarkedString.is(candidate.contents) ||
Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));
}
Hover.is = is;
})(Hover || (Hover = {}));
/**
* The ParameterInformation namespace provides helper functions to work with
* [ParameterInformation](#ParameterInformation) literals.
*/
export var ParameterInformation;
(function (ParameterInformation) {
/**
* Creates a new parameter information literal.
*
* @param label A label string.
* @param documentation A doc string.
*/
function create(label, documentation) {
return documentation ? { label: label, documentation: documentation } : { label: label };
}
ParameterInformation.create = create;
;
})(ParameterInformation || (ParameterInformation = {}));
/**
* The SignatureInformation namespace provides helper functions to work with
* [SignatureInformation](#SignatureInformation) literals.
*/
export var SignatureInformation;
(function (SignatureInformation) {
function create(label, documentation) {
var parameters = [];
for (var _i = 2; _i < arguments.length; _i++) {
parameters[_i - 2] = arguments[_i];
}
var result = { label: label };
if (Is.defined(documentation)) {
result.documentation = documentation;
}
if (Is.defined(parameters)) {
result.parameters = parameters;
}
else {
result.parameters = [];
}
return result;
}
SignatureInformation.create = create;
})(SignatureInformation || (SignatureInformation = {}));
/**
* A document highlight kind.
*/
export var DocumentHighlightKind;
(function (DocumentHighlightKind) {
/**
* A textual occurrence.
*/
DocumentHighlightKind.Text = 1;
/**
* Read-access of a symbol, like reading a variable.
*/
DocumentHighlightKind.Read = 2;
/**
* Write-access of a symbol, like writing to a variable.
*/
DocumentHighlightKind.Write = 3;
})(DocumentHighlightKind || (DocumentHighlightKind = {}));
/**
* DocumentHighlight namespace to provide helper functions to work with
* [DocumentHighlight](#DocumentHighlight) literals.
*/
export var DocumentHighlight;
(function (DocumentHighlight) {
/**
* Create a DocumentHighlight object.
* @param range The range the highlight applies to.
*/
function create(range, kind) {
var result = { range: range };
if (Is.number(kind)) {
result.kind = kind;
}
return result;
}
DocumentHighlight.create = create;
})(DocumentHighlight || (DocumentHighlight = {}));
/**
* A symbol kind.
*/
export var SymbolKind;
(function (SymbolKind) {
SymbolKind.File = 1;
SymbolKind.Module = 2;
SymbolKind.Namespace = 3;
SymbolKind.Package = 4;
SymbolKind.Class = 5;
SymbolKind.Method = 6;
SymbolKind.Property = 7;
SymbolKind.Field = 8;
SymbolKind.Constructor = 9;
SymbolKind.Enum = 10;
SymbolKind.Interface = 11;
SymbolKind.Function = 12;
SymbolKind.Variable = 13;
SymbolKind.Constant = 14;
SymbolKind.String = 15;
SymbolKind.Number = 16;
SymbolKind.Boolean = 17;
SymbolKind.Array = 18;
SymbolKind.Object = 19;
SymbolKind.Key = 20;
SymbolKind.Null = 21;
SymbolKind.EnumMember = 22;
SymbolKind.Struct = 23;
SymbolKind.Event = 24;
SymbolKind.Operator = 25;
SymbolKind.TypeParameter = 26;
})(SymbolKind || (SymbolKind = {}));
export var SymbolInformation;
(function (SymbolInformation) {
/**
* Creates a new symbol information literal.
*
* @param name The name of the symbol.
* @param kind The kind of the symbol.
* @param range The range of the location of the symbol.
* @param uri The resource of the location of symbol, defaults to the current document.
* @param containerName The name of the symbol containing the symbol.
*/
function create(name, kind, range, uri, containerName) {
var result = {
name: name,
kind: kind,
location: { uri: uri, range: range }
};
if (containerName) {
result.containerName = containerName;
}
return result;
}
SymbolInformation.create = create;
})(SymbolInformation || (SymbolInformation = {}));
/**
* Represents programming constructs like variables, classes, interfaces etc.
* that appear in a document. Document symbols can be hierarchical and they
* have two ranges: one that encloses its definition and one that points to
* its most interesting range, e.g. the range of an identifier.
*/
var DocumentSymbol = /** @class */ (function () {
function DocumentSymbol() {
}
return DocumentSymbol;
}());
export { DocumentSymbol };
(function (DocumentSymbol) {
/**
* Creates a new symbol information literal.
*
* @param name The name of the symbol.
* @param detail The detail of the symbol.
* @param kind The kind of the symbol.
* @param range The range of the symbol.
* @param selectionRange The selectionRange of the symbol.
* @param children Children of the symbol.
*/
function create(name, detail, kind, range, selectionRange, children) {
var result = {
name: name,
detail: detail,
kind: kind,
range: range,
selectionRange: selectionRange
};
if (children !== void 0) {
result.children = children;
}
return result;
}
DocumentSymbol.create = create;
/**
* Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.
*/
function is(value) {
var candidate = value;
return candidate &&
Is.string(candidate.name) && Is.number(candidate.kind) &&
Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
(candidate.detail === void 0 || Is.string(candidate.detail)) &&
(candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) &&
(candidate.children === void 0 || Array.isArray(candidate.children));
}
DocumentSymbol.is = is;
})(DocumentSymbol || (DocumentSymbol = {}));
/**
* A set of predefined code action kinds
*/
export var CodeActionKind;
(function (CodeActionKind) {
/**
* Base kind for quickfix actions: 'quickfix'
*/
CodeActionKind.QuickFix = 'quickfix';
/**
* Base kind for refactoring actions: 'refactor'
*/
CodeActionKind.Refactor = 'refactor';
/**
* Base kind for refactoring extraction actions: 'refactor.extract'
*
* Example extract actions:
*
* - Extract method
* - Extract function
* - Extract variable
* - Extract interface from class
* - ...
*/
CodeActionKind.RefactorExtract = 'refactor.extract';
/**
* Base kind for refactoring inline actions: 'refactor.inline'
*
* Example inline actions:
*
* - Inline function
* - Inline variable
* - Inline constant
* - ...
*/
CodeActionKind.RefactorInline = 'refactor.inline';
/**
* Base kind for refactoring rewrite actions: 'refactor.rewrite'
*
* Example rewrite actions:
*
* - Convert JavaScript function to class
* - Add or remove parameter
* - Encapsulate field
* - Make method static
* - Move method to base class
* - ...
*/
CodeActionKind.RefactorRewrite = 'refactor.rewrite';
/**
* Base kind for source actions: `source`
*
* Source code actions apply to the entire file.
*/
CodeActionKind.Source = 'source';
/**
* Base kind for an organize imports source action: `source.organizeImports`
*/
CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
})(CodeActionKind || (CodeActionKind = {}));
/**
* The CodeActionContext namespace provides helper functions to work with
* [CodeActionContext](#CodeActionContext) literals.
*/
export var CodeActionContext;
(function (CodeActionContext) {
/**
* Creates a new CodeActionContext literal.
*/
function create(diagnostics, only) {
var result = { diagnostics: diagnostics };
if (only !== void 0 && only !== null) {
result.only = only;
}
return result;
}
CodeActionContext.create = create;
/**
* Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));
}
CodeActionContext.is = is;
})(CodeActionContext || (CodeActionContext = {}));
export var CodeAction;
(function (CodeAction) {
function create(title, commandOrEdit, kind) {
var result = { title: title };
if (Command.is(commandOrEdit)) {
result.command = commandOrEdit;
}
else {
result.edit = commandOrEdit;
}
if (kind !== void null) {
result.kind = kind;
}
return result;
}
CodeAction.create = create;
function is(value) {
var candidate = value;
return candidate && Is.string(candidate.title) &&
(candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&
(candidate.kind === void 0 || Is.string(candidate.kind)) &&
(candidate.edit !== void 0 || candidate.command !== void 0) &&
(candidate.command === void 0 || Command.is(candidate.command)) &&
(candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
}
CodeAction.is = is;
})(CodeAction || (CodeAction = {}));
/**
* The CodeLens namespace provides helper functions to work with
* [CodeLens](#CodeLens) literals.
*/
export var CodeLens;
(function (CodeLens) {
/**
* Creates a new CodeLens literal.
*/
function create(range, data) {
var result = { range: range };
if (Is.defined(data))
result.data = data;
return result;
}
CodeLens.create = create;
/**
* Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
}
CodeLens.is = is;
})(CodeLens || (CodeLens = {}));
/**
* The FormattingOptions namespace provides helper functions to work with
* [FormattingOptions](#FormattingOptions) literals.
*/
export var FormattingOptions;
(function (FormattingOptions) {
/**
* Creates a new FormattingOptions literal.
*/
function create(tabSize, insertSpaces) {
return { tabSize: tabSize, insertSpaces: insertSpaces };
}
FormattingOptions.create = create;
/**
* Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
}
FormattingOptions.is = is;
})(FormattingOptions || (FormattingOptions = {}));
/**
* A document link is a range in a text document that links to an internal or external resource, like another
* text document or a web site.
*/
var DocumentLink = /** @class */ (function () {
function DocumentLink() {
}
return DocumentLink;
}());
export { DocumentLink };
/**
* The DocumentLink namespace provides helper functions to work with
* [DocumentLink](#DocumentLink) literals.
*/
(function (DocumentLink) {
/**
* Creates a new DocumentLink literal.
*/
function create(range, target, data) {
return { range: range, target: target, data: data };
}
DocumentLink.create = create;
/**
* Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
}
DocumentLink.is = is;
})(DocumentLink || (DocumentLink = {}));
export var EOL = ['\n', '\r\n', '\r'];
export var TextDocument;
(function (TextDocument) {
/**
* Creates a new ITextDocument literal from the given uri and content.
* @param uri The document's uri.
* @param languageId The document's language Id.
* @param content The document's content.
*/
function create(uri, languageId, version, content) {
return new FullTextDocument(uri, languageId, version, content);
}
TextDocument.create = create;
/**
* Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount)
&& Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
}
TextDocument.is = is;
function applyEdits(document, edits) {
var text = document.getText();
var sortedEdits = mergeSort(edits, function (a, b) {
var diff = a.range.start.line - b.range.start.line;
if (diff === 0) {
return a.range.start.character - b.range.start.character;
}
return diff;
});
var lastModifiedOffset = text.length;
for (var i = sortedEdits.length - 1; i >= 0; i--) {
var e = sortedEdits[i];
var startOffset = document.offsetAt(e.range.start);
var endOffset = document.offsetAt(e.range.end);
if (endOffset <= lastModifiedOffset) {
text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
}
else {
throw new Error('Overlapping edit');
}
lastModifiedOffset = startOffset;
}
return text;
}
TextDocument.applyEdits = applyEdits;
function mergeSort(data, compare) {
if (data.length <= 1) {
// sorted
return data;
}
var p = (data.length / 2) | 0;
var left = data.slice(0, p);
var right = data.slice(p);
mergeSort(left, compare);
mergeSort(right, compare);
var leftIdx = 0;
var rightIdx = 0;
var i = 0;
while (leftIdx < left.length && rightIdx < right.length) {
var ret = compare(left[leftIdx], right[rightIdx]);
if (ret <= 0) {
// smaller_equal -> take left to preserve order
data[i++] = left[leftIdx++];
}
else {
// greater -> take right
data[i++] = right[rightIdx++];
}
}
while (leftIdx < left.length) {
data[i++] = left[leftIdx++];
}
while (rightIdx < right.length) {
data[i++] = right[rightIdx++];
}
return data;
}
})(TextDocument || (TextDocument = {}));
/**
* Represents reasons why a text document is saved.
*/
export var TextDocumentSaveReason;
(function (TextDocumentSaveReason) {
/**
* Manually triggered, e.g. by the user pressing save, by starting debugging,
* or by an API call.
*/
TextDocumentSaveReason.Manual = 1;
/**
* Automatic after a delay.
*/
TextDocumentSaveReason.AfterDelay = 2;
/**
* When the editor lost focus.
*/
TextDocumentSaveReason.FocusOut = 3;
})(TextDocumentSaveReason || (TextDocumentSaveReason = {}));
var FullTextDocument = /** @class */ (function () {
function FullTextDocument(uri, languageId, version, content) {
this._uri = uri;
this._languageId = languageId;
this._version = version;
this._content = content;
this._lineOffsets = null;
}
Object.defineProperty(FullTextDocument.prototype, "uri", {
get: function () {
return this._uri;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FullTextDocument.prototype, "languageId", {
get: function () {
return this._languageId;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FullTextDocument.prototype, "version", {
get: function () {
return this._version;
},
enumerable: true,
configurable: true
});
FullTextDocument.prototype.getText = function (range) {
if (range) {
var start = this.offsetAt(range.start);
var end = this.offsetAt(range.end);
return this._content.substring(start, end);
}
return this._content;
};
FullTextDocument.prototype.update = function (event, version) {
this._content = event.text;
this._version = version;
this._lineOffsets = null;
};
FullTextDocument.prototype.getLineOffsets = function () {
if (this._lineOffsets === null) {
var lineOffsets = [];
var text = this._content;
var isLineStart = true;
for (var i = 0; i < text.length; i++) {
if (isLineStart) {
lineOffsets.push(i);
isLineStart = false;
}
var ch = text.charAt(i);
isLineStart = (ch === '\r' || ch === '\n');
if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
i++;
}
}
if (isLineStart && text.length > 0) {
lineOffsets.push(text.length);
}
this._lineOffsets = lineOffsets;
}
return this._lineOffsets;
};
FullTextDocument.prototype.positionAt = function (offset) {
offset = Math.max(Math.min(offset, this._content.length), 0);
var lineOffsets = this.getLineOffsets();
var low = 0, high = lineOffsets.length;
if (high === 0) {
return Position.create(0, offset);
}
while (low < high) {
var mid = Math.floor((low + high) / 2);
if (lineOffsets[mid] > offset) {
high = mid;
}
else {
low = mid + 1;
}
}
// low is the least x for which the line offset is larger than the current offset
// or array.length if no line offset is larger than the current offset
var line = low - 1;
return Position.create(line, offset - lineOffsets[line]);
};
FullTextDocument.prototype.offsetAt = function (position) {
var lineOffsets = this.getLineOffsets();
if (position.line >= lineOffsets.length) {
return this._content.length;
}
else if (position.line < 0) {
return 0;
}
var lineOffset = lineOffsets[position.line];
var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
};
Object.defineProperty(FullTextDocument.prototype, "lineCount", {
get: function () {
return this.getLineOffsets().length;
},
enumerable: true,
configurable: true
});
return FullTextDocument;
}());
var Is;
(function (Is) {
var toString = Object.prototype.toString;
function defined(value) {
return typeof value !== 'undefined';
}
Is.defined = defined;
function undefined(value) {
return typeof value === 'undefined';
}
Is.undefined = undefined;
function boolean(value) {
return value === true || value === false;
}
Is.boolean = boolean;
function string(value) {
return toString.call(value) === '[object String]';
}
Is.string = string;
function number(value) {
return toString.call(value) === '[object Number]';
}
Is.number = number;
function func(value) {
return toString.call(value) === '[object Function]';
}
Is.func = func;
function objectLiteral(value) {
// Strictly speaking class instances pass this check as well. Since the LSP
// doesn't use classes we ignore this for now. If we do we need to add something
// like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
return value !== null && typeof value === 'object';
}
Is.objectLiteral = objectLiteral;
function typedArray(value, check) {
return Array.isArray(value) && value.every(check);
}
Is.typedArray = typedArray;
})(Is || (Is = {}));
| {
"pile_set_name": "Github"
} |
[require]
VK_KHR_spirv_1_4
[compute shader spirv]
; Use the MinIterations loop control.
; Generated from with modified loop control:
;
; #version 430
;
;
; layout(std430, binding = 0) buffer input_buffer
; {
; int in_size;
; ivec4 data_SSBO[];
; };
;
; layout(std430, binding = 1) buffer output_buffer
; {
; int out_size;
; ivec4 out_SSBO[];
; };
;
; void main() {
; for( int i = 0; i < in_size; ++i ) {
; out_SSBO[i] = data_SSBO[i];
; }
; }
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint GLCompute %main "main" %_ %__0
OpExecutionMode %main LocalSize 1 1 1
OpSource GLSL 430
OpSourceExtension "GL_GOOGLE_cpp_style_line_directive"
OpSourceExtension "GL_GOOGLE_include_directive"
OpName %main "main"
OpName %i "i"
OpName %input_buffer "input_buffer"
OpMemberName %input_buffer 0 "in_size"
OpMemberName %input_buffer 1 "data_SSBO"
OpName %_ ""
OpName %output_buffer "output_buffer"
OpMemberName %output_buffer 0 "out_size"
OpMemberName %output_buffer 1 "out_SSBO"
OpName %__0 ""
OpDecorate %_runtimearr_v4int ArrayStride 16
OpMemberDecorate %input_buffer 0 Offset 0
OpMemberDecorate %input_buffer 1 Offset 16
OpDecorate %input_buffer Block
OpDecorate %_ DescriptorSet 0
OpDecorate %_ Binding 0
OpDecorate %_runtimearr_v4int_0 ArrayStride 16
OpMemberDecorate %output_buffer 0 Offset 0
OpMemberDecorate %output_buffer 1 Offset 16
OpDecorate %output_buffer Block
OpDecorate %__0 DescriptorSet 0
OpDecorate %__0 Binding 1
%void = OpTypeVoid
%3 = OpTypeFunction %void
%int = OpTypeInt 32 1
%_ptr_Function_int = OpTypePointer Function %int
%int_0 = OpConstant %int 0
%v4int = OpTypeVector %int 4
%_runtimearr_v4int = OpTypeRuntimeArray %v4int
%input_buffer = OpTypeStruct %int %_runtimearr_v4int
%_ptr_StorageBuffer_input_buffer = OpTypePointer StorageBuffer %input_buffer
%_ = OpVariable %_ptr_StorageBuffer_input_buffer StorageBuffer
%_ptr_StorageBuffer_int = OpTypePointer StorageBuffer %int
%bool = OpTypeBool
%_runtimearr_v4int_0 = OpTypeRuntimeArray %v4int
%output_buffer = OpTypeStruct %int %_runtimearr_v4int_0
%_ptr_StorageBuffer_output_buffer = OpTypePointer StorageBuffer %output_buffer
%__0 = OpVariable %_ptr_StorageBuffer_output_buffer StorageBuffer
%int_1 = OpConstant %int 1
%_ptr_StorageBuffer_v4int = OpTypePointer StorageBuffer %v4int
%main = OpFunction %void None %3
%5 = OpLabel
%i = OpVariable %_ptr_Function_int Function
OpStore %i %int_0
OpBranch %10
%10 = OpLabel
OpLoopMerge %12 %13 MinIterations 4
OpBranch %14
%14 = OpLabel
%15 = OpLoad %int %i
%23 = OpAccessChain %_ptr_StorageBuffer_int %_ %int_0
%24 = OpLoad %int %23
%26 = OpSLessThan %bool %15 %24
OpBranchConditional %26 %11 %12
%11 = OpLabel
%32 = OpLoad %int %i
%33 = OpLoad %int %i
%35 = OpAccessChain %_ptr_StorageBuffer_v4int %_ %int_1 %33
%36 = OpLoad %v4int %35
%37 = OpAccessChain %_ptr_StorageBuffer_v4int %__0 %int_1 %32
OpStore %37 %36
OpBranch %13
%13 = OpLabel
%38 = OpLoad %int %i
%39 = OpIAdd %int %38 %int_1
OpStore %i %39
OpBranch %10
%12 = OpLabel
OpReturn
OpFunctionEnd
[test]
ssbo 0:0 112
ssbo 0:0 subdata int 0 6 0 0 0
ssbo 0:0 subdata int 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
ssbo 0:1 112
ssbo 0:1 subdata int 0 6 0 0 0
ssbo 0:1 subdata int 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
compute entrypoint main
compute 1 1 1
probe ssbo int 0:1 16 == 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| {
"pile_set_name": "Github"
} |
var convert = require('./convert'),
func = convert('escape', require('../escape'), require('./_falseOptions'));
func.placeholder = require('./placeholder');
module.exports = func;
| {
"pile_set_name": "Github"
} |
/* Copyright (c) 2002-2005 CrystalClear Software, Inc.
* Use, modification and distribution is subject to the
* Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
* Author: Jeff Garland, Bart Garst
* $Date$
*/
#ifndef BOOST_DATE_TIME_SOURCE
#define BOOST_DATE_TIME_SOURCE
#endif
#include "boost/date_time/gregorian/greg_month.hpp"
#include "boost/date_time/gregorian/greg_facet.hpp"
#include "boost/date_time/date_format_simple.hpp"
#include "boost/date_time/compiler_config.hpp"
#if defined(BOOST_DATE_TIME_INCLUDE_LIMITED_HEADERS)
#include "boost/date_time/gregorian/formatters_limited.hpp"
#else
#include "boost/date_time/gregorian/formatters.hpp"
#endif
#include "boost/date_time/date_parsing.hpp"
#include "boost/date_time/gregorian/parsers.hpp"
#include "greg_names.hpp"
namespace boost {
namespace gregorian {
/*! Returns a shared pointer to a map of Month strings & numbers.
* Strings are both full names and abbreviations.
* Ex. ("jan",1), ("february",2), etc...
* Note: All characters are lowercase - for case insensitivity
*/
greg_month::month_map_ptr_type greg_month::get_month_map_ptr()
{
static month_map_ptr_type month_map_ptr(new greg_month::month_map_type());
if(month_map_ptr->empty()) {
std::string s("");
for(unsigned short i = 1; i <= 12; ++i) {
greg_month m(static_cast<month_enum>(i));
s = m.as_long_string();
s = date_time::convert_to_lower(s);
month_map_ptr->insert(std::make_pair(s, i));
s = m.as_short_string();
s = date_time::convert_to_lower(s);
month_map_ptr->insert(std::make_pair(s, i));
}
}
return month_map_ptr;
}
//! Returns 3 char english string for the month ex: Jan, Feb, Mar, Apr
const char*
greg_month::as_short_string() const
{
return short_month_names[value_-1];
}
//! Returns full name of month as string in english ex: January, February
const char*
greg_month::as_long_string() const
{
return long_month_names[value_-1];
}
//! Return special_value from string argument
/*! Return special_value from string argument. If argument is
* not one of the special value names (defined in names.hpp),
* return 'not_special' */
special_values special_value_from_string(const std::string& s) {
short i = date_time::find_match(special_value_names,
special_value_names,
date_time::NumSpecialValues,
s);
if(i >= date_time::NumSpecialValues) { // match not found
return not_special;
}
else {
return static_cast<special_values>(i);
}
}
#ifndef BOOST_NO_STD_WSTRING
//! Returns 3 wchar_t english string for the month ex: Jan, Feb, Mar, Apr
const wchar_t*
greg_month::as_short_wstring() const
{
return w_short_month_names[value_-1];
}
//! Returns full name of month as wchar_t string in english ex: January, February
const wchar_t*
greg_month::as_long_wstring() const
{
return w_long_month_names[value_-1];
}
#endif // BOOST_NO_STD_WSTRING
#ifndef BOOST_DATE_TIME_NO_LOCALE
/*! creates an all_date_names_put object with the correct set of names.
* This function is only called in the event of an exception where
* the imbued locale containing the needed facet is for some reason
* unreachable.
*/
BOOST_DATE_TIME_DECL
boost::date_time::all_date_names_put<greg_facet_config, char>*
create_facet_def(char /*type*/)
{
typedef
boost::date_time::all_date_names_put<greg_facet_config, char> facet_def;
return new facet_def(short_month_names,
long_month_names,
special_value_names,
short_weekday_names,
long_weekday_names);
}
//! generates a locale with the set of gregorian name-strings of type char*
BOOST_DATE_TIME_DECL std::locale generate_locale(std::locale& loc, char /*type*/){
typedef boost::date_time::all_date_names_put<greg_facet_config, char> facet_def;
return std::locale(loc, new facet_def(short_month_names,
long_month_names,
special_value_names,
short_weekday_names,
long_weekday_names)
);
}
#ifndef BOOST_NO_STD_WSTRING
/*! creates an all_date_names_put object with the correct set of names.
* This function is only called in the event of an exception where
* the imbued locale containing the needed facet is for some reason
* unreachable.
*/
BOOST_DATE_TIME_DECL
boost::date_time::all_date_names_put<greg_facet_config, wchar_t>*
create_facet_def(wchar_t /*type*/)
{
typedef
boost::date_time::all_date_names_put<greg_facet_config,wchar_t> facet_def;
return new facet_def(w_short_month_names,
w_long_month_names,
w_special_value_names,
w_short_weekday_names,
w_long_weekday_names);
}
//! generates a locale with the set of gregorian name-strings of type wchar_t*
BOOST_DATE_TIME_DECL std::locale generate_locale(std::locale& loc, wchar_t /*type*/){
typedef boost::date_time::all_date_names_put<greg_facet_config, wchar_t> facet_def;
return std::locale(loc, new facet_def(w_short_month_names,
w_long_month_names,
w_special_value_names,
w_short_weekday_names,
w_long_weekday_names)
);
}
#endif // BOOST_NO_STD_WSTRING
#endif // BOOST_DATE_TIME_NO_LOCALE
} } //namespace gregorian
| {
"pile_set_name": "Github"
} |
package schema1
import (
"encoding/json"
"time"
"github.com/Microsoft/go-winio/pkg/guid"
hcsschema "github.com/Microsoft/hcsshim/internal/schema2"
)
// ProcessConfig is used as both the input of Container.CreateProcess
// and to convert the parameters to JSON for passing onto the HCS
type ProcessConfig struct {
ApplicationName string `json:",omitempty"`
CommandLine string `json:",omitempty"`
CommandArgs []string `json:",omitempty"` // Used by Linux Containers on Windows
User string `json:",omitempty"`
WorkingDirectory string `json:",omitempty"`
Environment map[string]string `json:",omitempty"`
EmulateConsole bool `json:",omitempty"`
CreateStdInPipe bool `json:",omitempty"`
CreateStdOutPipe bool `json:",omitempty"`
CreateStdErrPipe bool `json:",omitempty"`
ConsoleSize [2]uint `json:",omitempty"`
CreateInUtilityVm bool `json:",omitempty"` // Used by Linux Containers on Windows
OCISpecification *json.RawMessage `json:",omitempty"` // Used by Linux Containers on Windows
}
type Layer struct {
ID string
Path string
}
type MappedDir struct {
HostPath string
ContainerPath string
ReadOnly bool
BandwidthMaximum uint64
IOPSMaximum uint64
CreateInUtilityVM bool
// LinuxMetadata - Support added in 1803/RS4+.
LinuxMetadata bool `json:",omitempty"`
}
type MappedPipe struct {
HostPath string
ContainerPipeName string
}
type HvRuntime struct {
ImagePath string `json:",omitempty"`
SkipTemplate bool `json:",omitempty"`
LinuxInitrdFile string `json:",omitempty"` // File under ImagePath on host containing an initrd image for starting a Linux utility VM
LinuxKernelFile string `json:",omitempty"` // File under ImagePath on host containing a kernel for starting a Linux utility VM
LinuxBootParameters string `json:",omitempty"` // Additional boot parameters for starting a Linux Utility VM in initrd mode
BootSource string `json:",omitempty"` // "Vhd" for Linux Utility VM booting from VHD
WritableBootSource bool `json:",omitempty"` // Linux Utility VM booting from VHD
}
type MappedVirtualDisk struct {
HostPath string `json:",omitempty"` // Path to VHD on the host
ContainerPath string // Platform-specific mount point path in the container
CreateInUtilityVM bool `json:",omitempty"`
ReadOnly bool `json:",omitempty"`
Cache string `json:",omitempty"` // "" (Unspecified); "Disabled"; "Enabled"; "Private"; "PrivateAllowSharing"
AttachOnly bool `json:",omitempty"`
}
// AssignedDevice represents a device that has been directly assigned to a container
//
// NOTE: Support added in RS5
type AssignedDevice struct {
// InterfaceClassGUID of the device to assign to container.
InterfaceClassGUID string `json:"InterfaceClassGuid,omitempty"`
}
// ContainerConfig is used as both the input of CreateContainer
// and to convert the parameters to JSON for passing onto the HCS
type ContainerConfig struct {
SystemType string // HCS requires this to be hard-coded to "Container"
Name string // Name of the container. We use the docker ID.
Owner string `json:",omitempty"` // The management platform that created this container
VolumePath string `json:",omitempty"` // Windows volume path for scratch space. Used by Windows Server Containers only. Format \\?\\Volume{GUID}
IgnoreFlushesDuringBoot bool `json:",omitempty"` // Optimization hint for container startup in Windows
LayerFolderPath string `json:",omitempty"` // Where the layer folders are located. Used by Windows Server Containers only. Format %root%\windowsfilter\containerID
Layers []Layer // List of storage layers. Required for Windows Server and Hyper-V Containers. Format ID=GUID;Path=%root%\windowsfilter\layerID
Credentials string `json:",omitempty"` // Credentials information
ProcessorCount uint32 `json:",omitempty"` // Number of processors to assign to the container.
ProcessorWeight uint64 `json:",omitempty"` // CPU shares (relative weight to other containers with cpu shares). Range is from 1 to 10000. A value of 0 results in default shares.
ProcessorMaximum int64 `json:",omitempty"` // Specifies the portion of processor cycles that this container can use as a percentage times 100. Range is from 1 to 10000. A value of 0 results in no limit.
StorageIOPSMaximum uint64 `json:",omitempty"` // Maximum Storage IOPS
StorageBandwidthMaximum uint64 `json:",omitempty"` // Maximum Storage Bandwidth in bytes per second
StorageSandboxSize uint64 `json:",omitempty"` // Size in bytes that the container system drive should be expanded to if smaller
MemoryMaximumInMB int64 `json:",omitempty"` // Maximum memory available to the container in Megabytes
HostName string `json:",omitempty"` // Hostname
MappedDirectories []MappedDir `json:",omitempty"` // List of mapped directories (volumes/mounts)
MappedPipes []MappedPipe `json:",omitempty"` // List of mapped Windows named pipes
HvPartition bool // True if it a Hyper-V Container
NetworkSharedContainerName string `json:",omitempty"` // Name (ID) of the container that we will share the network stack with.
EndpointList []string `json:",omitempty"` // List of networking endpoints to be attached to container
HvRuntime *HvRuntime `json:",omitempty"` // Hyper-V container settings. Used by Hyper-V containers only. Format ImagePath=%root%\BaseLayerID\UtilityVM
Servicing bool `json:",omitempty"` // True if this container is for servicing
AllowUnqualifiedDNSQuery bool `json:",omitempty"` // True to allow unqualified DNS name resolution
DNSSearchList string `json:",omitempty"` // Comma seperated list of DNS suffixes to use for name resolution
ContainerType string `json:",omitempty"` // "Linux" for Linux containers on Windows. Omitted otherwise.
TerminateOnLastHandleClosed bool `json:",omitempty"` // Should HCS terminate the container once all handles have been closed
MappedVirtualDisks []MappedVirtualDisk `json:",omitempty"` // Array of virtual disks to mount at start
AssignedDevices []AssignedDevice `json:",omitempty"` // Array of devices to assign. NOTE: Support added in RS5
}
type ComputeSystemQuery struct {
IDs []string `json:"Ids,omitempty"`
Types []string `json:",omitempty"`
Names []string `json:",omitempty"`
Owners []string `json:",omitempty"`
}
type PropertyType string
const (
PropertyTypeStatistics PropertyType = "Statistics" // V1 and V2
PropertyTypeProcessList = "ProcessList" // V1 and V2
PropertyTypeMappedVirtualDisk = "MappedVirtualDisk" // Not supported in V2 schema call
PropertyTypeGuestConnection = "GuestConnection" // V1 and V2. Nil return from HCS before RS5
)
type PropertyQuery struct {
PropertyTypes []PropertyType `json:",omitempty"`
}
// ContainerProperties holds the properties for a container and the processes running in that container
type ContainerProperties struct {
ID string `json:"Id"`
State string
Name string
SystemType string
RuntimeOSType string `json:"RuntimeOsType,omitempty"`
Owner string
SiloGUID string `json:"SiloGuid,omitempty"`
RuntimeID guid.GUID `json:"RuntimeId,omitempty"`
IsRuntimeTemplate bool `json:",omitempty"`
RuntimeImagePath string `json:",omitempty"`
Stopped bool `json:",omitempty"`
ExitType string `json:",omitempty"`
AreUpdatesPending bool `json:",omitempty"`
ObRoot string `json:",omitempty"`
Statistics Statistics `json:",omitempty"`
ProcessList []ProcessListItem `json:",omitempty"`
MappedVirtualDiskControllers map[int]MappedVirtualDiskController `json:",omitempty"`
GuestConnectionInfo GuestConnectionInfo `json:",omitempty"`
}
// MemoryStats holds the memory statistics for a container
type MemoryStats struct {
UsageCommitBytes uint64 `json:"MemoryUsageCommitBytes,omitempty"`
UsageCommitPeakBytes uint64 `json:"MemoryUsageCommitPeakBytes,omitempty"`
UsagePrivateWorkingSetBytes uint64 `json:"MemoryUsagePrivateWorkingSetBytes,omitempty"`
}
// ProcessorStats holds the processor statistics for a container
type ProcessorStats struct {
TotalRuntime100ns uint64 `json:",omitempty"`
RuntimeUser100ns uint64 `json:",omitempty"`
RuntimeKernel100ns uint64 `json:",omitempty"`
}
// StorageStats holds the storage statistics for a container
type StorageStats struct {
ReadCountNormalized uint64 `json:",omitempty"`
ReadSizeBytes uint64 `json:",omitempty"`
WriteCountNormalized uint64 `json:",omitempty"`
WriteSizeBytes uint64 `json:",omitempty"`
}
// NetworkStats holds the network statistics for a container
type NetworkStats struct {
BytesReceived uint64 `json:",omitempty"`
BytesSent uint64 `json:",omitempty"`
PacketsReceived uint64 `json:",omitempty"`
PacketsSent uint64 `json:",omitempty"`
DroppedPacketsIncoming uint64 `json:",omitempty"`
DroppedPacketsOutgoing uint64 `json:",omitempty"`
EndpointId string `json:",omitempty"`
InstanceId string `json:",omitempty"`
}
// Statistics is the structure returned by a statistics call on a container
type Statistics struct {
Timestamp time.Time `json:",omitempty"`
ContainerStartTime time.Time `json:",omitempty"`
Uptime100ns uint64 `json:",omitempty"`
Memory MemoryStats `json:",omitempty"`
Processor ProcessorStats `json:",omitempty"`
Storage StorageStats `json:",omitempty"`
Network []NetworkStats `json:",omitempty"`
}
// ProcessList is the structure of an item returned by a ProcessList call on a container
type ProcessListItem struct {
CreateTimestamp time.Time `json:",omitempty"`
ImageName string `json:",omitempty"`
KernelTime100ns uint64 `json:",omitempty"`
MemoryCommitBytes uint64 `json:",omitempty"`
MemoryWorkingSetPrivateBytes uint64 `json:",omitempty"`
MemoryWorkingSetSharedBytes uint64 `json:",omitempty"`
ProcessId uint32 `json:",omitempty"`
UserTime100ns uint64 `json:",omitempty"`
}
// MappedVirtualDiskController is the structure of an item returned by a MappedVirtualDiskList call on a container
type MappedVirtualDiskController struct {
MappedVirtualDisks map[int]MappedVirtualDisk `json:",omitempty"`
}
// GuestDefinedCapabilities is part of the GuestConnectionInfo returned by a GuestConnection call on a utility VM
type GuestDefinedCapabilities struct {
NamespaceAddRequestSupported bool `json:",omitempty"`
SignalProcessSupported bool `json:",omitempty"`
DumpStacksSupported bool `json:",omitempty"`
}
// GuestConnectionInfo is the structure of an iterm return by a GuestConnection call on a utility VM
type GuestConnectionInfo struct {
SupportedSchemaVersions []hcsschema.Version `json:",omitempty"`
ProtocolVersion uint32 `json:",omitempty"`
GuestDefinedCapabilities GuestDefinedCapabilities `json:",omitempty"`
}
// Type of Request Support in ModifySystem
type RequestType string
// Type of Resource Support in ModifySystem
type ResourceType string
// RequestType const
const (
Add RequestType = "Add"
Remove RequestType = "Remove"
Network ResourceType = "Network"
)
// ResourceModificationRequestResponse is the structure used to send request to the container to modify the system
// Supported resource types are Network and Request Types are Add/Remove
type ResourceModificationRequestResponse struct {
Resource ResourceType `json:"ResourceType"`
Data interface{} `json:"Settings"`
Request RequestType `json:"RequestType,omitempty"`
}
| {
"pile_set_name": "Github"
} |
# Copyright (c) 2012-2014 Roger Light <[email protected]>
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# and Eclipse Distribution License v1.0 which accompany this distribution.
#
# The Eclipse Public License is available at
# http://www.eclipse.org/legal/epl-v10.html
# and the Eclipse Distribution License is available at
# http://www.eclipse.org/org/documents/edl-v10.php.
#
# Contributors:
# Roger Light - initial API and implementation
"""
This is an MQTT v3.1 client module. MQTT is a lightweight pub/sub messaging
protocol that is easy to implement and suitable for low powered devices.
"""
import errno
import platform
import random
import select
import socket
HAVE_SSL = True
try:
import ssl
cert_reqs = ssl.CERT_REQUIRED
tls_version = ssl.PROTOCOL_TLSv1
except:
HAVE_SSL = False
cert_reqs = None
tls_version = None
import struct
import sys
import threading
import time
HAVE_DNS = True
try:
import dns.resolver
except ImportError:
HAVE_DNS = False
if platform.system() == 'Windows':
EAGAIN = errno.WSAEWOULDBLOCK
else:
EAGAIN = errno.EAGAIN
VERSION_MAJOR=1
VERSION_MINOR=0
VERSION_REVISION=0
VERSION_NUMBER=(VERSION_MAJOR*1000000+VERSION_MINOR*1000+VERSION_REVISION)
MQTTv31 = 3
MQTTv311 = 4
if sys.version_info[0] < 3:
PROTOCOL_NAMEv31 = "MQIsdp"
PROTOCOL_NAMEv311 = "MQTT"
else:
PROTOCOL_NAMEv31 = b"MQIsdp"
PROTOCOL_NAMEv311 = b"MQTT"
PROTOCOL_VERSION = 3
# Message types
CONNECT = 0x10
CONNACK = 0x20
PUBLISH = 0x30
PUBACK = 0x40
PUBREC = 0x50
PUBREL = 0x60
PUBCOMP = 0x70
SUBSCRIBE = 0x80
SUBACK = 0x90
UNSUBSCRIBE = 0xA0
UNSUBACK = 0xB0
PINGREQ = 0xC0
PINGRESP = 0xD0
DISCONNECT = 0xE0
# Log levels
MQTT_LOG_INFO = 0x01
MQTT_LOG_NOTICE = 0x02
MQTT_LOG_WARNING = 0x04
MQTT_LOG_ERR = 0x08
MQTT_LOG_DEBUG = 0x10
# CONNACK codes
CONNACK_ACCEPTED = 0
CONNACK_REFUSED_PROTOCOL_VERSION = 1
CONNACK_REFUSED_IDENTIFIER_REJECTED = 2
CONNACK_REFUSED_SERVER_UNAVAILABLE = 3
CONNACK_REFUSED_BAD_USERNAME_PASSWORD = 4
CONNACK_REFUSED_NOT_AUTHORIZED = 5
# Connection state
mqtt_cs_new = 0
mqtt_cs_connected = 1
mqtt_cs_disconnecting = 2
mqtt_cs_connect_async = 3
# Message state
mqtt_ms_invalid = 0
mqtt_ms_publish= 1
mqtt_ms_wait_for_puback = 2
mqtt_ms_wait_for_pubrec = 3
mqtt_ms_resend_pubrel = 4
mqtt_ms_wait_for_pubrel = 5
mqtt_ms_resend_pubcomp = 6
mqtt_ms_wait_for_pubcomp = 7
mqtt_ms_send_pubrec = 8
mqtt_ms_queued = 9
# Error values
MQTT_ERR_AGAIN = -1
MQTT_ERR_SUCCESS = 0
MQTT_ERR_NOMEM = 1
MQTT_ERR_PROTOCOL = 2
MQTT_ERR_INVAL = 3
MQTT_ERR_NO_CONN = 4
MQTT_ERR_CONN_REFUSED = 5
MQTT_ERR_NOT_FOUND = 6
MQTT_ERR_CONN_LOST = 7
MQTT_ERR_TLS = 8
MQTT_ERR_PAYLOAD_SIZE = 9
MQTT_ERR_NOT_SUPPORTED = 10
MQTT_ERR_AUTH = 11
MQTT_ERR_ACL_DENIED = 12
MQTT_ERR_UNKNOWN = 13
MQTT_ERR_ERRNO = 14
if sys.version_info[0] < 3:
sockpair_data = "0"
else:
sockpair_data = b"0"
def error_string(mqtt_errno):
"""Return the error string associated with an mqtt error number."""
if mqtt_errno == MQTT_ERR_SUCCESS:
return "No error."
elif mqtt_errno == MQTT_ERR_NOMEM:
return "Out of memory."
elif mqtt_errno == MQTT_ERR_PROTOCOL:
return "A network protocol error occurred when communicating with the broker."
elif mqtt_errno == MQTT_ERR_INVAL:
return "Invalid function arguments provided."
elif mqtt_errno == MQTT_ERR_NO_CONN:
return "The client is not currently connected."
elif mqtt_errno == MQTT_ERR_CONN_REFUSED:
return "The connection was refused."
elif mqtt_errno == MQTT_ERR_NOT_FOUND:
return "Message not found (internal error)."
elif mqtt_errno == MQTT_ERR_CONN_LOST:
return "The connection was lost."
elif mqtt_errno == MQTT_ERR_TLS:
return "A TLS error occurred."
elif mqtt_errno == MQTT_ERR_PAYLOAD_SIZE:
return "Payload too large."
elif mqtt_errno == MQTT_ERR_NOT_SUPPORTED:
return "This feature is not supported."
elif mqtt_errno == MQTT_ERR_AUTH:
return "Authorisation failed."
elif mqtt_errno == MQTT_ERR_ACL_DENIED:
return "Access denied by ACL."
elif mqtt_errno == MQTT_ERR_UNKNOWN:
return "Unknown error."
elif mqtt_errno == MQTT_ERR_ERRNO:
return "Error defined by errno."
else:
return "Unknown error."
def connack_string(connack_code):
"""Return the string associated with a CONNACK result."""
if connack_code == 0:
return "Connection Accepted."
elif connack_code == 1:
return "Connection Refused: unacceptable protocol version."
elif connack_code == 2:
return "Connection Refused: identifier rejected."
elif connack_code == 3:
return "Connection Refused: broker unavailable."
elif connack_code == 4:
return "Connection Refused: bad user name or password."
elif connack_code == 5:
return "Connection Refused: not authorised."
else:
return "Connection Refused: unknown reason."
def topic_matches_sub(sub, topic):
"""Check whether a topic matches a subscription.
For example:
foo/bar would match the subscription foo/# or +/bar
non/matching would not match the subscription non/+/+
"""
result = True
multilevel_wildcard = False
slen = len(sub)
tlen = len(topic)
if slen > 0 and tlen > 0:
if (sub[0] == '$' and topic[0] != '$') or (topic[0] == '$' and sub[0] != '$'):
return False
spos = 0
tpos = 0
while spos < slen and tpos < tlen:
if sub[spos] == topic[tpos]:
if tpos == tlen-1:
# Check for e.g. foo matching foo/#
if spos == slen-3 and sub[spos+1] == '/' and sub[spos+2] == '#':
result = True
multilevel_wildcard = True
break
spos += 1
tpos += 1
if tpos == tlen and spos == slen-1 and sub[spos] == '+':
spos += 1
result = True
break
else:
if sub[spos] == '+':
spos += 1
while tpos < tlen and topic[tpos] != '/':
tpos += 1
if tpos == tlen and spos == slen:
result = True
break
elif sub[spos] == '#':
multilevel_wildcard = True
if spos+1 != slen:
result = False
break
else:
result = True
break
else:
result = False
break
if not multilevel_wildcard and (tpos < tlen or spos < slen):
result = False
return result
def _socketpair_compat():
"""TCP/IP socketpair including Windows support"""
listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listensock.bind(("127.0.0.1", 0))
listensock.listen(1)
iface, port = listensock.getsockname()
sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
sock1.setblocking(0)
try:
sock1.connect(("localhost", port))
except socket.error as err:
if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
raise
sock2, address = listensock.accept()
sock2.setblocking(0)
listensock.close()
return (sock1, sock2)
class MQTTMessage:
""" This is a class that describes an incoming message. It is passed to the
on_message callback as the message parameter.
Members:
topic : String. topic that the message was published on.
payload : String/bytes the message payload.
qos : Integer. The message Quality of Service 0, 1 or 2.
retain : Boolean. If true, the message is a retained message and not fresh.
mid : Integer. The message id.
"""
def __init__(self):
self.timestamp = 0
self.state = mqtt_ms_invalid
self.dup = False
self.mid = 0
self.topic = ""
self.payload = None
self.qos = 0
self.retain = False
class Client(object):
"""MQTT version 3.1/3.1.1 client class.
This is the main class for use communicating with an MQTT broker.
General usage flow:
* Use connect()/connect_async() to connect to a broker
* Call loop() frequently to maintain network traffic flow with the broker
* Or use loop_start() to set a thread running to call loop() for you.
* Or use loop_forever() to handle calling loop() for you in a blocking
* function.
* Use subscribe() to subscribe to a topic and receive messages
* Use publish() to send messages
* Use disconnect() to disconnect from the broker
Data returned from the broker is made available with the use of callback
functions as described below.
Callbacks
=========
A number of callback functions are available to receive data back from the
broker. To use a callback, define a function and then assign it to the
client:
def on_connect(client, userdata, flags, rc):
print("Connection returned " + str(rc))
client.on_connect = on_connect
All of the callbacks as described below have a "client" and an "userdata"
argument. "client" is the Client instance that is calling the callback.
"userdata" is user data of any type and can be set when creating a new client
instance or with user_data_set(userdata).
The callbacks:
on_connect(client, userdata, flags, rc): called when the broker responds to our connection
request.
flags is a dict that contains response flags from the broker:
flags['session present'] - this flag is useful for clients that are
using clean session set to 0 only. If a client with clean
session=0, that reconnects to a broker that it has previously
connected to, this flag indicates whether the broker still has the
session information for the client. If 1, the session still exists.
The value of rc determines success or not:
0: Connection successful
1: Connection refused - incorrect protocol version
2: Connection refused - invalid client identifier
3: Connection refused - server unavailable
4: Connection refused - bad username or password
5: Connection refused - not authorised
6-255: Currently unused.
on_disconnect(client, userdata, rc): called when the client disconnects from the broker.
The rc parameter indicates the disconnection state. If MQTT_ERR_SUCCESS
(0), the callback was called in response to a disconnect() call. If any
other value the disconnection was unexpected, such as might be caused by
a network error.
on_message(client, userdata, message): called when a message has been received on a
topic that the client subscribes to. The message variable is a
MQTTMessage that describes all of the message parameters.
on_publish(client, userdata, mid): called when a message that was to be sent using the
publish() call has completed transmission to the broker. For messages
with QoS levels 1 and 2, this means that the appropriate handshakes have
completed. For QoS 0, this simply means that the message has left the
client. The mid variable matches the mid variable returned from the
corresponding publish() call, to allow outgoing messages to be tracked.
This callback is important because even if the publish() call returns
success, it does not always mean that the message has been sent.
on_subscribe(client, userdata, mid, granted_qos): called when the broker responds to a
subscribe request. The mid variable matches the mid variable returned
from the corresponding subscribe() call. The granted_qos variable is a
list of integers that give the QoS level the broker has granted for each
of the different subscription requests.
on_unsubscribe(client, userdata, mid): called when the broker responds to an unsubscribe
request. The mid variable matches the mid variable returned from the
corresponding unsubscribe() call.
on_log(client, userdata, level, buf): called when the client has log information. Define
to allow debugging. The level variable gives the severity of the message
and will be one of MQTT_LOG_INFO, MQTT_LOG_NOTICE, MQTT_LOG_WARNING,
MQTT_LOG_ERR, and MQTT_LOG_DEBUG. The message itself is in buf.
"""
def __init__(self, client_id="", clean_session=True, userdata=None, protocol=MQTTv31):
"""client_id is the unique client id string used when connecting to the
broker. If client_id is zero length or None, then one will be randomly
generated. In this case, clean_session must be True. If this is not the
case a ValueError will be raised.
clean_session is a boolean that determines the client type. If True,
the broker will remove all information about this client when it
disconnects. If False, the client is a persistent client and
subscription information and queued messages will be retained when the
client disconnects.
Note that a client will never discard its own outgoing messages on
disconnect. Calling connect() or reconnect() will cause the messages to
be resent. Use reinitialise() to reset a client to its original state.
userdata is user defined data of any type that is passed as the "userdata"
parameter to callbacks. It may be updated at a later point with the
user_data_set() function.
The protocol argument allows explicit setting of the MQTT version to
use for this client. Can be paho.mqtt.client.MQTTv311 (v3.1.1) or
paho.mqtt.client.MQTTv31 (v3.1), with the default being v3.1. If the
broker reports that the client connected with an invalid protocol
version, the client will automatically attempt to reconnect using v3.1
instead.
"""
if not clean_session and (client_id == "" or client_id is None):
raise ValueError('A client id must be provided if clean session is False.')
self._protocol = protocol
self._userdata = userdata
self._sock = None
self._sockpairR, self._sockpairW = _socketpair_compat()
self._keepalive = 60
self._message_retry = 20
self._last_retry_check = 0
self._clean_session = clean_session
if client_id == "" or client_id is None:
self._client_id = "paho/" + "".join(random.choice("0123456789ADCDEF") for x in range(23-5))
else:
self._client_id = client_id
self._username = ""
self._password = ""
self._in_packet = {
"command": 0,
"have_remaining": 0,
"remaining_count": [],
"remaining_mult": 1,
"remaining_length": 0,
"packet": b"",
"to_process": 0,
"pos": 0}
self._out_packet = []
self._current_out_packet = None
self._last_msg_in = time.time()
self._last_msg_out = time.time()
self._ping_t = 0
self._last_mid = 0
self._state = mqtt_cs_new
self._out_messages = []
self._in_messages = []
self._max_inflight_messages = 20
self._inflight_messages = 0
self._will = False
self._will_topic = ""
self._will_payload = None
self._will_qos = 0
self._will_retain = False
self.on_disconnect = None
self.on_connect = None
self.on_publish = None
self.on_message = None
self.on_message_filtered = []
self.on_subscribe = None
self.on_unsubscribe = None
self.on_log = None
self._host = ""
self._port = 1883
self._bind_address = ""
self._in_callback = False
self._strict_protocol = False
self._callback_mutex = threading.Lock()
self._state_mutex = threading.Lock()
self._out_packet_mutex = threading.Lock()
self._current_out_packet_mutex = threading.Lock()
self._msgtime_mutex = threading.Lock()
self._out_message_mutex = threading.Lock()
self._in_message_mutex = threading.Lock()
self._thread = None
self._thread_terminate = False
self._ssl = None
self._tls_certfile = None
self._tls_keyfile = None
self._tls_ca_certs = None
self._tls_cert_reqs = None
self._tls_ciphers = None
self._tls_version = tls_version
self._tls_insecure = False
def __del__(self):
pass
def reinitialise(self, client_id="", clean_session=True, userdata=None):
if self._ssl:
self._ssl.close()
self._ssl = None
self._sock = None
elif self._sock:
self._sock.close()
self._sock = None
if self._sockpairR:
self._sockpairR.close()
self._sockpairR = None
if self._sockpairW:
self._sockpairW.close()
self._sockpairW = None
self.__init__(client_id, clean_session, userdata)
def tls_set(self, ca_certs, certfile=None, keyfile=None, cert_reqs=cert_reqs, tls_version=tls_version, ciphers=None):
"""Configure network encryption and authentication options. Enables SSL/TLS support.
ca_certs : a string path to the Certificate Authority certificate files
that are to be treated as trusted by this client. If this is the only
option given then the client will operate in a similar manner to a web
browser. That is to say it will require the broker to have a
certificate signed by the Certificate Authorities in ca_certs and will
communicate using TLS v1, but will not attempt any form of
authentication. This provides basic network encryption but may not be
sufficient depending on how the broker is configured.
certfile and keyfile are strings pointing to the PEM encoded client
certificate and private keys respectively. If these arguments are not
None then they will be used as client information for TLS based
authentication. Support for this feature is broker dependent. Note
that if either of these files in encrypted and needs a password to
decrypt it, Python will ask for the password at the command line. It is
not currently possible to define a callback to provide the password.
cert_reqs allows the certificate requirements that the client imposes
on the broker to be changed. By default this is ssl.CERT_REQUIRED,
which means that the broker must provide a certificate. See the ssl
pydoc for more information on this parameter.
tls_version allows the version of the SSL/TLS protocol used to be
specified. By default TLS v1 is used. Previous versions (all versions
beginning with SSL) are possible but not recommended due to possible
security problems.
ciphers is a string specifying which encryption ciphers are allowable
for this connection, or None to use the defaults. See the ssl pydoc for
more information.
Must be called before connect() or connect_async()."""
if HAVE_SSL is False:
raise ValueError('This platform has no SSL/TLS.')
if sys.version < '2.7':
raise ValueError('Python 2.7 is the minimum supported version for TLS.')
if ca_certs is None:
raise ValueError('ca_certs must not be None.')
try:
f = open(ca_certs, "r")
except IOError as err:
raise IOError(ca_certs+": "+err.strerror)
else:
f.close()
if certfile is not None:
try:
f = open(certfile, "r")
except IOError as err:
raise IOError(certfile+": "+err.strerror)
else:
f.close()
if keyfile is not None:
try:
f = open(keyfile, "r")
except IOError as err:
raise IOError(keyfile+": "+err.strerror)
else:
f.close()
self._tls_ca_certs = ca_certs
self._tls_certfile = certfile
self._tls_keyfile = keyfile
self._tls_cert_reqs = cert_reqs
self._tls_version = tls_version
self._tls_ciphers = ciphers
def tls_insecure_set(self, value):
"""Configure verification of the server hostname in the server certificate.
If value is set to true, it is impossible to guarantee that the host
you are connecting to is not impersonating your server. This can be
useful in initial server testing, but makes it possible for a malicious
third party to impersonate your server through DNS spoofing, for
example.
Do not use this function in a real system. Setting value to true means
there is no point using encryption.
Must be called before connect()."""
if HAVE_SSL is False:
raise ValueError('This platform has no SSL/TLS.')
self._tls_insecure = value
def connect(self, host, port=1883, keepalive=60, bind_address=""):
"""Connect to a remote broker.
host is the hostname or IP address of the remote broker.
port is the network port of the server host to connect to. Defaults to
1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you
are using tls_set() the port may need providing.
keepalive: Maximum period in seconds between communications with the
broker. If no other messages are being exchanged, this controls the
rate at which the client will send ping messages to the broker.
"""
self.connect_async(host, port, keepalive, bind_address)
return self.reconnect()
def connect_srv(self, domain=None, keepalive=60, bind_address=""):
"""Connect to a remote broker.
domain is the DNS domain to search for SRV records; if None,
try to determine local domain name.
keepalive and bind_address are as for connect()
"""
if HAVE_DNS is False:
raise ValueError('No DNS resolver library found.')
if domain is None:
domain = socket.getfqdn()
domain = domain[domain.find('.') + 1:]
try:
rr = '_mqtt._tcp.%s' % domain
if self._ssl is not None:
# IANA specifies secure-mqtt (not mqtts) for port 8883
rr = '_secure-mqtt._tcp.%s' % domain
answers = []
for answer in dns.resolver.query(rr, dns.rdatatype.SRV):
addr = answer.target.to_text()[:-1]
answers.append((addr, answer.port, answer.priority, answer.weight))
except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers):
raise ValueError("No answer/NXDOMAIN for SRV in %s" % (domain))
# FIXME: doesn't account for weight
for answer in answers:
host, port, prio, weight = answer
try:
return self.connect(host, port, keepalive, bind_address)
except:
pass
raise ValueError("No SRV hosts responded")
def connect_async(self, host, port=1883, keepalive=60, bind_address=""):
"""Connect to a remote broker asynchronously. This is a non-blocking
connect call that can be used with loop_start() to provide very quick
start.
host is the hostname or IP address of the remote broker.
port is the network port of the server host to connect to. Defaults to
1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you
are using tls_set() the port may need providing.
keepalive: Maximum period in seconds between communications with the
broker. If no other messages are being exchanged, this controls the
rate at which the client will send ping messages to the broker.
"""
if host is None or len(host) == 0:
raise ValueError('Invalid host.')
if port <= 0:
raise ValueError('Invalid port number.')
if keepalive < 0:
raise ValueError('Keepalive must be >=0.')
if bind_address != "" and bind_address is not None:
if (sys.version_info[0] == 2 and sys.version_info[1] < 7) or (sys.version_info[0] == 3 and sys.version_info[1] < 2):
raise ValueError('bind_address requires Python 2.7 or 3.2.')
self._host = host
self._port = port
self._keepalive = keepalive
self._bind_address = bind_address
self._state_mutex.acquire()
self._state = mqtt_cs_connect_async
self._state_mutex.release()
def reconnect(self):
"""Reconnect the client after a disconnect. Can only be called after
connect()/connect_async()."""
if len(self._host) == 0:
raise ValueError('Invalid host.')
if self._port <= 0:
raise ValueError('Invalid port number.')
self._in_packet = {
"command": 0,
"have_remaining": 0,
"remaining_count": [],
"remaining_mult": 1,
"remaining_length": 0,
"packet": b"",
"to_process": 0,
"pos": 0}
self._out_packet_mutex.acquire()
self._out_packet = []
self._out_packet_mutex.release()
self._current_out_packet_mutex.acquire()
self._current_out_packet = None
self._current_out_packet_mutex.release()
self._msgtime_mutex.acquire()
self._last_msg_in = time.time()
self._last_msg_out = time.time()
self._msgtime_mutex.release()
self._ping_t = 0
self._state_mutex.acquire()
self._state = mqtt_cs_new
self._state_mutex.release()
if self._ssl:
self._ssl.close()
self._ssl = None
self._sock = None
elif self._sock:
self._sock.close()
self._sock = None
# Put messages in progress in a valid state.
self._messages_reconnect_reset()
try:
if (sys.version_info[0] == 2 and sys.version_info[1] < 7) or (sys.version_info[0] == 3 and sys.version_info[1] < 2):
sock = socket.create_connection((self._host, self._port))
else:
sock = socket.create_connection((self._host, self._port), source_address=(self._bind_address, 0))
except socket.error as err:
if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
raise
if self._tls_ca_certs is not None:
self._ssl = ssl.wrap_socket(
sock,
certfile=self._tls_certfile,
keyfile=self._tls_keyfile,
ca_certs=self._tls_ca_certs,
cert_reqs=self._tls_cert_reqs,
ssl_version=self._tls_version,
ciphers=self._tls_ciphers)
if self._tls_insecure is False:
if sys.version_info[0] < 3 or (sys.version_info[0] == 3 and sys.version_info[1] < 2):
self._tls_match_hostname()
else:
ssl.match_hostname(self._ssl.getpeercert(), self._host)
self._sock = sock
self._sock.setblocking(0)
return self._send_connect(self._keepalive, self._clean_session)
def loop(self, timeout=1.0, max_packets=1):
"""Process network events.
This function must be called regularly to ensure communication with the
broker is carried out. It calls select() on the network socket to wait
for network events. If incoming data is present it will then be
processed. Outgoing commands, from e.g. publish(), are normally sent
immediately that their function is called, but this is not always
possible. loop() will also attempt to send any remaining outgoing
messages, which also includes commands that are part of the flow for
messages with QoS>0.
timeout: The time in seconds to wait for incoming/outgoing network
traffic before timing out and returning.
max_packets: Not currently used.
Returns MQTT_ERR_SUCCESS on success.
Returns >0 on error.
A ValueError will be raised if timeout < 0"""
if timeout < 0.0:
raise ValueError('Invalid timeout.')
self._current_out_packet_mutex.acquire()
self._out_packet_mutex.acquire()
if self._current_out_packet is None and len(self._out_packet) > 0:
self._current_out_packet = self._out_packet.pop(0)
if self._current_out_packet:
wlist = [self.socket()]
else:
wlist = []
self._out_packet_mutex.release()
self._current_out_packet_mutex.release()
# sockpairR is used to break out of select() before the timeout, on a
# call to publish() etc.
rlist = [self.socket(), self._sockpairR]
try:
socklist = select.select(rlist, wlist, [], timeout)
except TypeError:
# Socket isn't correct type, in likelihood connection is lost
return MQTT_ERR_CONN_LOST
except ValueError:
# Can occur if we just reconnected but rlist/wlist contain a -1 for
# some reason.
return MQTT_ERR_CONN_LOST
except:
return MQTT_ERR_UNKNOWN
if self.socket() in socklist[0]:
rc = self.loop_read(max_packets)
if rc or (self._ssl is None and self._sock is None):
return rc
if self._sockpairR in socklist[0]:
# Stimulate output write even though we didn't ask for it, because
# at that point the publish or other command wasn't present.
socklist[1].insert(0, self.socket())
# Clear sockpairR - only ever a single byte written.
try:
self._sockpairR.recv(1)
except socket.error as err:
if err.errno != EAGAIN:
raise
if self.socket() in socklist[1]:
rc = self.loop_write(max_packets)
if rc or (self._ssl is None and self._sock is None):
return rc
return self.loop_misc()
def publish(self, topic, payload=None, qos=0, retain=False):
"""Publish a message on a topic.
This causes a message to be sent to the broker and subsequently from
the broker to any clients subscribing to matching topics.
topic: The topic that the message should be published on.
payload: The actual message to send. If not given, or set to None a
zero length message will be used. Passing an int or float will result
in the payload being converted to a string representing that number. If
you wish to send a true int/float, use struct.pack() to create the
payload you require.
qos: The quality of service level to use.
retain: If set to true, the message will be set as the "last known
good"/retained message for the topic.
Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS to
indicate success or MQTT_ERR_NO_CONN if the client is not currently
connected. mid is the message ID for the publish request. The mid
value can be used to track the publish request by checking against the
mid argument in the on_publish() callback if it is defined.
A ValueError will be raised if topic is None, has zero length or is
invalid (contains a wildcard), if qos is not one of 0, 1 or 2, or if
the length of the payload is greater than 268435455 bytes."""
if topic is None or len(topic) == 0:
raise ValueError('Invalid topic.')
if qos<0 or qos>2:
raise ValueError('Invalid QoS level.')
if isinstance(payload, str) or isinstance(payload, bytearray):
local_payload = payload
elif sys.version_info[0] < 3 and isinstance(payload, unicode):
local_payload = payload
elif isinstance(payload, int) or isinstance(payload, float):
local_payload = str(payload)
elif payload is None:
local_payload = None
else:
raise TypeError('payload must be a string, bytearray, int, float or None.')
if local_payload is not None and len(local_payload) > 268435455:
raise ValueError('Payload too large.')
if self._topic_wildcard_len_check(topic) != MQTT_ERR_SUCCESS:
raise ValueError('Publish topic cannot contain wildcards.')
local_mid = self._mid_generate()
if qos == 0:
rc = self._send_publish(local_mid, topic, local_payload, qos, retain, False)
return (rc, local_mid)
else:
message = MQTTMessage()
message.timestamp = time.time()
message.mid = local_mid
message.topic = topic
if local_payload is None or len(local_payload) == 0:
message.payload = None
else:
message.payload = local_payload
message.qos = qos
message.retain = retain
message.dup = False
self._out_message_mutex.acquire()
self._out_messages.append(message)
if self._max_inflight_messages == 0 or self._inflight_messages < self._max_inflight_messages:
self._inflight_messages = self._inflight_messages+1
if qos == 1:
message.state = mqtt_ms_wait_for_puback
elif qos == 2:
message.state = mqtt_ms_wait_for_pubrec
self._out_message_mutex.release()
rc = self._send_publish(message.mid, message.topic, message.payload, message.qos, message.retain, message.dup)
# remove from inflight messages so it will be send after a connection is made
if rc is MQTT_ERR_NO_CONN:
with self._out_message_mutex:
self._inflight_messages -= 1
message.state = mqtt_ms_publish
return (rc, local_mid)
else:
message.state = mqtt_ms_queued;
self._out_message_mutex.release()
return (MQTT_ERR_SUCCESS, local_mid)
def username_pw_set(self, username, password=None):
"""Set a username and optionally a password for broker authentication.
Must be called before connect() to have any effect.
Requires a broker that supports MQTT v3.1.
username: The username to authenticate with. Need have no relationship to the client id.
password: The password to authenticate with. Optional, set to None if not required.
"""
self._username = username.encode('utf-8')
self._password = password
def disconnect(self):
"""Disconnect a connected client from the broker."""
self._state_mutex.acquire()
self._state = mqtt_cs_disconnecting
self._state_mutex.release()
if self._sock is None and self._ssl is None:
return MQTT_ERR_NO_CONN
return self._send_disconnect()
def subscribe(self, topic, qos=0):
"""Subscribe the client to one or more topics.
This function may be called in three different ways:
Simple string and integer
-------------------------
e.g. subscribe("my/topic", 2)
topic: A string specifying the subscription topic to subscribe to.
qos: The desired quality of service level for the subscription.
Defaults to 0.
String and integer tuple
------------------------
e.g. subscribe(("my/topic", 1))
topic: A tuple of (topic, qos). Both topic and qos must be present in
the tuple.
qos: Not used.
List of string and integer tuples
------------------------
e.g. subscribe([("my/topic", 0), ("another/topic", 2)])
This allows multiple topic subscriptions in a single SUBSCRIPTION
command, which is more efficient than using multiple calls to
subscribe().
topic: A list of tuple of format (topic, qos). Both topic and qos must
be present in all of the tuples.
qos: Not used.
The function returns a tuple (result, mid), where result is
MQTT_ERR_SUCCESS to indicate success or (MQTT_ERR_NO_CONN, None) if the
client is not currently connected. mid is the message ID for the
subscribe request. The mid value can be used to track the subscribe
request by checking against the mid argument in the on_subscribe()
callback if it is defined.
Raises a ValueError if qos is not 0, 1 or 2, or if topic is None or has
zero string length, or if topic is not a string, tuple or list.
"""
topic_qos_list = None
if isinstance(topic, str):
if qos<0 or qos>2:
raise ValueError('Invalid QoS level.')
if topic is None or len(topic) == 0:
raise ValueError('Invalid topic.')
topic_qos_list = [(topic.encode('utf-8'), qos)]
elif isinstance(topic, tuple):
if topic[1]<0 or topic[1]>2:
raise ValueError('Invalid QoS level.')
if topic[0] is None or len(topic[0]) == 0 or not isinstance(topic[0], str):
raise ValueError('Invalid topic.')
topic_qos_list = [(topic[0].encode('utf-8'), topic[1])]
elif isinstance(topic, list):
topic_qos_list = []
for t in topic:
if t[1]<0 or t[1]>2:
raise ValueError('Invalid QoS level.')
if t[0] is None or len(t[0]) == 0 or not isinstance(t[0], str):
raise ValueError('Invalid topic.')
topic_qos_list.append((t[0].encode('utf-8'), t[1]))
if topic_qos_list is None:
raise ValueError("No topic specified, or incorrect topic type.")
if self._sock is None and self._ssl is None:
return (MQTT_ERR_NO_CONN, None)
return self._send_subscribe(False, topic_qos_list)
def unsubscribe(self, topic):
"""Unsubscribe the client from one or more topics.
topic: A single string, or list of strings that are the subscription
topics to unsubscribe from.
Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS
to indicate success or (MQTT_ERR_NO_CONN, None) if the client is not
currently connected.
mid is the message ID for the unsubscribe request. The mid value can be
used to track the unsubscribe request by checking against the mid
argument in the on_unsubscribe() callback if it is defined.
Raises a ValueError if topic is None or has zero string length, or is
not a string or list.
"""
topic_list = None
if topic is None:
raise ValueError('Invalid topic.')
if isinstance(topic, str):
if len(topic) == 0:
raise ValueError('Invalid topic.')
topic_list = [topic.encode('utf-8')]
elif isinstance(topic, list):
topic_list = []
for t in topic:
if len(t) == 0 or not isinstance(t, str):
raise ValueError('Invalid topic.')
topic_list.append(t.encode('utf-8'))
if topic_list is None:
raise ValueError("No topic specified, or incorrect topic type.")
if self._sock is None and self._ssl is None:
return (MQTT_ERR_NO_CONN, None)
return self._send_unsubscribe(False, topic_list)
def loop_read(self, max_packets=1):
"""Process read network events. Use in place of calling loop() if you
wish to handle your client reads as part of your own application.
Use socket() to obtain the client socket to call select() or equivalent
on.
Do not use if you are using the threaded interface loop_start()."""
if self._sock is None and self._ssl is None:
return MQTT_ERR_NO_CONN
max_packets = len(self._out_messages) + len(self._in_messages)
if max_packets < 1:
max_packets = 1
for i in range(0, max_packets):
rc = self._packet_read()
if rc > 0:
return self._loop_rc_handle(rc)
elif rc == MQTT_ERR_AGAIN:
return MQTT_ERR_SUCCESS
return MQTT_ERR_SUCCESS
def loop_write(self, max_packets=1):
"""Process read network events. Use in place of calling loop() if you
wish to handle your client reads as part of your own application.
Use socket() to obtain the client socket to call select() or equivalent
on.
Use want_write() to determine if there is data waiting to be written.
Do not use if you are using the threaded interface loop_start()."""
if self._sock is None and self._ssl is None:
return MQTT_ERR_NO_CONN
max_packets = len(self._out_packet) + 1
if max_packets < 1:
max_packets = 1
for i in range(0, max_packets):
rc = self._packet_write()
if rc > 0:
return self._loop_rc_handle(rc)
elif rc == MQTT_ERR_AGAIN:
return MQTT_ERR_SUCCESS
return MQTT_ERR_SUCCESS
def want_write(self):
"""Call to determine if there is network data waiting to be written.
Useful if you are calling select() yourself rather than using loop().
"""
if self._current_out_packet or len(self._out_packet) > 0:
return True
else:
return False
def loop_misc(self):
"""Process miscellaneous network events. Use in place of calling loop() if you
wish to call select() or equivalent on.
Do not use if you are using the threaded interface loop_start()."""
if self._sock is None and self._ssl is None:
return MQTT_ERR_NO_CONN
now = time.time()
self._check_keepalive()
if self._last_retry_check+1 < now:
# Only check once a second at most
self._message_retry_check()
self._last_retry_check = now
if self._ping_t > 0 and now - self._ping_t >= self._keepalive:
# client->ping_t != 0 means we are waiting for a pingresp.
# This hasn't happened in the keepalive time so we should disconnect.
if self._ssl:
self._ssl.close()
self._ssl = None
elif self._sock:
self._sock.close()
self._sock = None
self._callback_mutex.acquire()
if self._state == mqtt_cs_disconnecting:
rc = MQTT_ERR_SUCCESS
else:
rc = 1
if self.on_disconnect:
self._in_callback = True
self.on_disconnect(self, self._userdata, rc)
self._in_callback = False
self._callback_mutex.release()
return MQTT_ERR_CONN_LOST
return MQTT_ERR_SUCCESS
def max_inflight_messages_set(self, inflight):
"""Set the maximum number of messages with QoS>0 that can be part way
through their network flow at once. Defaults to 20."""
if inflight < 0:
raise ValueError('Invalid inflight.')
self._max_inflight_messages = inflight
def message_retry_set(self, retry):
"""Set the timeout in seconds before a message with QoS>0 is retried.
20 seconds by default."""
if retry < 0:
raise ValueError('Invalid retry.')
self._message_retry = retry
def user_data_set(self, userdata):
"""Set the user data variable passed to callbacks. May be any data type."""
self._userdata = userdata
def will_set(self, topic, payload=None, qos=0, retain=False):
"""Set a Will to be sent by the broker in case the client disconnects unexpectedly.
This must be called before connect() to have any effect.
topic: The topic that the will message should be published on.
payload: The message to send as a will. If not given, or set to None a
zero length message will be used as the will. Passing an int or float
will result in the payload being converted to a string representing
that number. If you wish to send a true int/float, use struct.pack() to
create the payload you require.
qos: The quality of service level to use for the will.
retain: If set to true, the will message will be set as the "last known
good"/retained message for the topic.
Raises a ValueError if qos is not 0, 1 or 2, or if topic is None or has
zero string length.
"""
if topic is None or len(topic) == 0:
raise ValueError('Invalid topic.')
if qos<0 or qos>2:
raise ValueError('Invalid QoS level.')
if isinstance(payload, str):
self._will_payload = payload.encode('utf-8')
elif isinstance(payload, bytearray):
self._will_payload = payload
elif isinstance(payload, int) or isinstance(payload, float):
self._will_payload = str(payload)
elif payload is None:
self._will_payload = None
else:
raise TypeError('payload must be a string, bytearray, int, float or None.')
self._will = True
self._will_topic = topic.encode('utf-8')
self._will_qos = qos
self._will_retain = retain
def will_clear(self):
""" Removes a will that was previously configured with will_set().
Must be called before connect() to have any effect."""
self._will = False
self._will_topic = ""
self._will_payload = None
self._will_qos = 0
self._will_retain = False
def socket(self):
"""Return the socket or ssl object for this client."""
if self._ssl:
return self._ssl
else:
return self._sock
def loop_forever(self, timeout=1.0, max_packets=1, retry_first_connection=False):
"""This function call loop() for you in an infinite blocking loop. It
is useful for the case where you only want to run the MQTT client loop
in your program.
loop_forever() will handle reconnecting for you. If you call
disconnect() in a callback it will return.
timeout: The time in seconds to wait for incoming/outgoing network
traffic before timing out and returning.
max_packets: Not currently used.
retry_first_connection: Should the first connection attempt be retried on failure.
Raises socket.error on first connection failures unless retry_first_connection=True
"""
run = True
while run:
if self._state == mqtt_cs_connect_async:
try:
self.reconnect()
except socket.error:
if not retry_first_connection:
raise
self._easy_log(MQTT_LOG_DEBUG, "Connection failed, retrying")
time.sleep(1)
else:
break
while run:
rc = MQTT_ERR_SUCCESS
while rc == MQTT_ERR_SUCCESS:
rc = self.loop(timeout, max_packets)
# We don't need to worry about locking here, because we've
# either called loop_forever() when in single threaded mode, or
# in multi threaded mode when loop_stop() has been called and
# so no other threads can access _current_out_packet,
# _out_packet or _messages.
if (self._thread_terminate is True
and self._current_out_packet is None
and len(self._out_packet) == 0
and len(self._out_messages) == 0):
rc = 1
run = False
self._state_mutex.acquire()
if self._state == mqtt_cs_disconnecting or run is False or self._thread_terminate is True:
run = False
self._state_mutex.release()
else:
self._state_mutex.release()
time.sleep(1)
self._state_mutex.acquire()
if self._state == mqtt_cs_disconnecting or run is False or self._thread_terminate is True:
run = False
self._state_mutex.release()
else:
self._state_mutex.release()
try:
self.reconnect()
except socket.error as err:
pass
return rc
def loop_start(self):
"""This is part of the threaded client interface. Call this once to
start a new thread to process network traffic. This provides an
alternative to repeatedly calling loop() yourself.
"""
if self._thread is not None:
return MQTT_ERR_INVAL
self._thread_terminate = False
self._thread = threading.Thread(target=self._thread_main)
self._thread.daemon = True
self._thread.start()
def loop_stop(self, force=False):
"""This is part of the threaded client interface. Call this once to
stop the network thread previously created with loop_start(). This call
will block until the network thread finishes.
The force parameter is currently ignored.
"""
if self._thread is None:
return MQTT_ERR_INVAL
self._thread_terminate = True
self._thread.join()
self._thread = None
def message_callback_add(self, sub, callback):
"""Register a message callback for a specific topic.
Messages that match 'sub' will be passed to 'callback'. Any
non-matching messages will be passed to the default on_message
callback.
Call multiple times with different 'sub' to define multiple topic
specific callbacks.
Topic specific callbacks may be removed with
message_callback_remove()."""
if callback is None or sub is None:
raise ValueError("sub and callback must both be defined.")
self._callback_mutex.acquire()
for i in range(0, len(self.on_message_filtered)):
if self.on_message_filtered[i][0] == sub:
self.on_message_filtered[i] = (sub, callback)
self._callback_mutex.release()
return
self.on_message_filtered.append((sub, callback))
self._callback_mutex.release()
def message_callback_remove(self, sub):
"""Remove a message callback previously registered with
message_callback_add()."""
if sub is None:
raise ValueError("sub must defined.")
self._callback_mutex.acquire()
for i in range(0, len(self.on_message_filtered)):
if self.on_message_filtered[i][0] == sub:
self.on_message_filtered.pop(i)
self._callback_mutex.release()
return
self._callback_mutex.release()
# ============================================================
# Private functions
# ============================================================
def _loop_rc_handle(self, rc):
if rc:
if self._ssl:
self._ssl.close()
self._ssl = None
elif self._sock:
self._sock.close()
self._sock = None
self._state_mutex.acquire()
if self._state == mqtt_cs_disconnecting:
rc = MQTT_ERR_SUCCESS
self._state_mutex.release()
self._callback_mutex.acquire()
if self.on_disconnect:
self._in_callback = True
self.on_disconnect(self, self._userdata, rc)
self._in_callback = False
self._callback_mutex.release()
return rc
def _packet_read(self):
# This gets called if pselect() indicates that there is network data
# available - ie. at least one byte. What we do depends on what data we
# already have.
# If we've not got a command, attempt to read one and save it. This should
# always work because it's only a single byte.
# Then try to read the remaining length. This may fail because it is may
# be more than one byte - will need to save data pending next read if it
# does fail.
# Then try to read the remaining payload, where 'payload' here means the
# combined variable header and actual payload. This is the most likely to
# fail due to longer length, so save current data and current position.
# After all data is read, send to _mqtt_handle_packet() to deal with.
# Finally, free the memory and reset everything to starting conditions.
if self._in_packet['command'] == 0:
try:
if self._ssl:
command = self._ssl.read(1)
else:
command = self._sock.recv(1)
except socket.error as err:
if self._ssl and (err.errno == ssl.SSL_ERROR_WANT_READ or err.errno == ssl.SSL_ERROR_WANT_WRITE):
return MQTT_ERR_AGAIN
if err.errno == EAGAIN:
return MQTT_ERR_AGAIN
print(err)
return 1
else:
if len(command) == 0:
return 1
command = struct.unpack("!B", command)
self._in_packet['command'] = command[0]
if self._in_packet['have_remaining'] == 0:
# Read remaining
# Algorithm for decoding taken from pseudo code at
# http://publib.boulder.ibm.com/infocenter/wmbhelp/v6r0m0/topic/com.ibm.etools.mft.doc/ac10870_.htm
while True:
try:
if self._ssl:
byte = self._ssl.read(1)
else:
byte = self._sock.recv(1)
except socket.error as err:
if self._ssl and (err.errno == ssl.SSL_ERROR_WANT_READ or err.errno == ssl.SSL_ERROR_WANT_WRITE):
return MQTT_ERR_AGAIN
if err.errno == EAGAIN:
return MQTT_ERR_AGAIN
print(err)
return 1
else:
byte = struct.unpack("!B", byte)
byte = byte[0]
self._in_packet['remaining_count'].append(byte)
# Max 4 bytes length for remaining length as defined by protocol.
# Anything more likely means a broken/malicious client.
if len(self._in_packet['remaining_count']) > 4:
return MQTT_ERR_PROTOCOL
self._in_packet['remaining_length'] = self._in_packet['remaining_length'] + (byte & 127)*self._in_packet['remaining_mult']
self._in_packet['remaining_mult'] = self._in_packet['remaining_mult'] * 128
if (byte & 128) == 0:
break
self._in_packet['have_remaining'] = 1
self._in_packet['to_process'] = self._in_packet['remaining_length']
while self._in_packet['to_process'] > 0:
try:
if self._ssl:
data = self._ssl.read(self._in_packet['to_process'])
else:
data = self._sock.recv(self._in_packet['to_process'])
except socket.error as err:
if self._ssl and (err.errno == ssl.SSL_ERROR_WANT_READ or err.errno == ssl.SSL_ERROR_WANT_WRITE):
return MQTT_ERR_AGAIN
if err.errno == EAGAIN:
return MQTT_ERR_AGAIN
print(err)
return 1
else:
self._in_packet['to_process'] = self._in_packet['to_process'] - len(data)
self._in_packet['packet'] = self._in_packet['packet'] + data
# All data for this packet is read.
self._in_packet['pos'] = 0
rc = self._packet_handle()
# Free data and reset values
self._in_packet = dict(
command=0,
have_remaining=0,
remaining_count=[],
remaining_mult=1,
remaining_length=0,
packet=b"",
to_process=0,
pos=0)
self._msgtime_mutex.acquire()
self._last_msg_in = time.time()
self._msgtime_mutex.release()
return rc
def _packet_write(self):
self._current_out_packet_mutex.acquire()
while self._current_out_packet:
packet = self._current_out_packet
try:
if self._ssl:
write_length = self._ssl.write(packet['packet'][packet['pos']:])
else:
write_length = self._sock.send(packet['packet'][packet['pos']:])
except AttributeError:
self._current_out_packet_mutex.release()
return MQTT_ERR_SUCCESS
except socket.error as err:
self._current_out_packet_mutex.release()
if self._ssl and (err.errno == ssl.SSL_ERROR_WANT_READ or err.errno == ssl.SSL_ERROR_WANT_WRITE):
return MQTT_ERR_AGAIN
if err.errno == EAGAIN:
return MQTT_ERR_AGAIN
print(err)
return 1
if write_length > 0:
packet['to_process'] = packet['to_process'] - write_length
packet['pos'] = packet['pos'] + write_length
if packet['to_process'] == 0:
if (packet['command'] & 0xF0) == PUBLISH and packet['qos'] == 0:
self._callback_mutex.acquire()
if self.on_publish:
self._in_callback = True
self.on_publish(self, self._userdata, packet['mid'])
self._in_callback = False
self._callback_mutex.release()
if (packet['command'] & 0xF0) == DISCONNECT:
self._current_out_packet_mutex.release()
self._msgtime_mutex.acquire()
self._last_msg_out = time.time()
self._msgtime_mutex.release()
self._callback_mutex.acquire()
if self.on_disconnect:
self._in_callback = True
self.on_disconnect(self, self._userdata, 0)
self._in_callback = False
self._callback_mutex.release()
if self._ssl:
self._ssl.close()
self._ssl = None
if self._sock:
self._sock.close()
self._sock = None
return MQTT_ERR_SUCCESS
self._out_packet_mutex.acquire()
if len(self._out_packet) > 0:
self._current_out_packet = self._out_packet.pop(0)
else:
self._current_out_packet = None
self._out_packet_mutex.release()
else:
pass # FIXME
self._current_out_packet_mutex.release()
self._msgtime_mutex.acquire()
self._last_msg_out = time.time()
self._msgtime_mutex.release()
return MQTT_ERR_SUCCESS
def _easy_log(self, level, buf):
if self.on_log:
self.on_log(self, self._userdata, level, buf)
def _check_keepalive(self):
now = time.time()
self._msgtime_mutex.acquire()
last_msg_out = self._last_msg_out
last_msg_in = self._last_msg_in
self._msgtime_mutex.release()
if (self._sock is not None or self._ssl is not None) and (now - last_msg_out >= self._keepalive or now - last_msg_in >= self._keepalive):
if self._state == mqtt_cs_connected and self._ping_t == 0:
self._send_pingreq()
self._msgtime_mutex.acquire()
self._last_msg_out = now
self._last_msg_in = now
self._msgtime_mutex.release()
else:
if self._ssl:
self._ssl.close()
self._ssl = None
elif self._sock:
self._sock.close()
self._sock = None
if self._state == mqtt_cs_disconnecting:
rc = MQTT_ERR_SUCCESS
else:
rc = 1
self._callback_mutex.acquire()
if self.on_disconnect:
self._in_callback = True
self.on_disconnect(self, self._userdata, rc)
self._in_callback = False
self._callback_mutex.release()
def _mid_generate(self):
self._last_mid = self._last_mid + 1
if self._last_mid == 65536:
self._last_mid = 1
return self._last_mid
def _topic_wildcard_len_check(self, topic):
# Search for + or # in a topic. Return MQTT_ERR_INVAL if found.
# Also returns MQTT_ERR_INVAL if the topic string is too long.
# Returns MQTT_ERR_SUCCESS if everything is fine.
if '+' in topic or '#' in topic or len(topic) == 0 or len(topic) > 65535:
return MQTT_ERR_INVAL
else:
return MQTT_ERR_SUCCESS
def _send_pingreq(self):
self._easy_log(MQTT_LOG_DEBUG, "Sending PINGREQ")
rc = self._send_simple_command(PINGREQ)
if rc == MQTT_ERR_SUCCESS:
self._ping_t = time.time()
return rc
def _send_pingresp(self):
self._easy_log(MQTT_LOG_DEBUG, "Sending PINGRESP")
return self._send_simple_command(PINGRESP)
def _send_puback(self, mid):
self._easy_log(MQTT_LOG_DEBUG, "Sending PUBACK (Mid: "+str(mid)+")")
return self._send_command_with_mid(PUBACK, mid, False)
def _send_pubcomp(self, mid):
self._easy_log(MQTT_LOG_DEBUG, "Sending PUBCOMP (Mid: "+str(mid)+")")
return self._send_command_with_mid(PUBCOMP, mid, False)
def _pack_remaining_length(self, packet, remaining_length):
remaining_bytes = []
while True:
byte = remaining_length % 128
remaining_length = remaining_length // 128
# If there are more digits to encode, set the top bit of this digit
if remaining_length > 0:
byte = byte | 0x80
remaining_bytes.append(byte)
packet.extend(struct.pack("!B", byte))
if remaining_length == 0:
# FIXME - this doesn't deal with incorrectly large payloads
return packet
def _pack_str16(self, packet, data):
if sys.version_info[0] < 3:
if isinstance(data, bytearray):
packet.extend(struct.pack("!H", len(data)))
packet.extend(data)
elif isinstance(data, str):
udata = data.encode('utf-8')
pack_format = "!H" + str(len(udata)) + "s"
packet.extend(struct.pack(pack_format, len(udata), udata))
elif isinstance(data, unicode):
udata = data.encode('utf-8')
pack_format = "!H" + str(len(udata)) + "s"
packet.extend(struct.pack(pack_format, len(udata), udata))
else:
raise TypeError
else:
if isinstance(data, bytearray) or isinstance(data, bytes):
packet.extend(struct.pack("!H", len(data)))
packet.extend(data)
elif isinstance(data, str):
udata = data.encode('utf-8')
pack_format = "!H" + str(len(udata)) + "s"
packet.extend(struct.pack(pack_format, len(udata), udata))
else:
raise TypeError
def _send_publish(self, mid, topic, payload=None, qos=0, retain=False, dup=False):
if self._sock is None and self._ssl is None:
return MQTT_ERR_NO_CONN
utopic = topic.encode('utf-8')
command = PUBLISH | ((dup&0x1)<<3) | (qos<<1) | retain
packet = bytearray()
packet.extend(struct.pack("!B", command))
if payload is None:
remaining_length = 2+len(utopic)
self._easy_log(MQTT_LOG_DEBUG, "Sending PUBLISH (d"+str(dup)+", q"+str(qos)+", r"+str(int(retain))+", m"+str(mid)+", '"+topic+"' (NULL payload)")
else:
if isinstance(payload, str):
upayload = payload.encode('utf-8')
payloadlen = len(upayload)
elif isinstance(payload, bytearray):
payloadlen = len(payload)
elif isinstance(payload, unicode):
upayload = payload.encode('utf-8')
payloadlen = len(upayload)
remaining_length = 2+len(utopic) + payloadlen
self._easy_log(MQTT_LOG_DEBUG, "Sending PUBLISH (d"+str(dup)+", q"+str(qos)+", r"+str(int(retain))+", m"+str(mid)+", '"+topic+"', ... ("+str(payloadlen)+" bytes)")
if qos > 0:
# For message id
remaining_length = remaining_length + 2
self._pack_remaining_length(packet, remaining_length)
self._pack_str16(packet, topic)
if qos > 0:
# For message id
packet.extend(struct.pack("!H", mid))
if payload is not None:
if isinstance(payload, str):
pack_format = str(payloadlen) + "s"
packet.extend(struct.pack(pack_format, upayload))
elif isinstance(payload, bytearray):
packet.extend(payload)
elif isinstance(payload, unicode):
pack_format = str(payloadlen) + "s"
packet.extend(struct.pack(pack_format, upayload))
else:
raise TypeError('payload must be a string, unicode or a bytearray.')
return self._packet_queue(PUBLISH, packet, mid, qos)
def _send_pubrec(self, mid):
self._easy_log(MQTT_LOG_DEBUG, "Sending PUBREC (Mid: "+str(mid)+")")
return self._send_command_with_mid(PUBREC, mid, False)
def _send_pubrel(self, mid, dup=False):
self._easy_log(MQTT_LOG_DEBUG, "Sending PUBREL (Mid: "+str(mid)+")")
return self._send_command_with_mid(PUBREL|2, mid, dup)
def _send_command_with_mid(self, command, mid, dup):
# For PUBACK, PUBCOMP, PUBREC, and PUBREL
if dup:
command = command | 8
remaining_length = 2
packet = struct.pack('!BBH', command, remaining_length, mid)
return self._packet_queue(command, packet, mid, 1)
def _send_simple_command(self, command):
# For DISCONNECT, PINGREQ and PINGRESP
remaining_length = 0
packet = struct.pack('!BB', command, remaining_length)
return self._packet_queue(command, packet, 0, 0)
def _send_connect(self, keepalive, clean_session):
if self._protocol == MQTTv31:
protocol = PROTOCOL_NAMEv31
proto_ver = 3
else:
protocol = PROTOCOL_NAMEv311
proto_ver = 4
remaining_length = 2+len(protocol) + 1+1+2 + 2+len(self._client_id)
connect_flags = 0
if clean_session:
connect_flags = connect_flags | 0x02
if self._will:
if self._will_payload is not None:
remaining_length = remaining_length + 2+len(self._will_topic) + 2+len(self._will_payload)
else:
remaining_length = remaining_length + 2+len(self._will_topic) + 2
connect_flags = connect_flags | 0x04 | ((self._will_qos&0x03) << 3) | ((self._will_retain&0x01) << 5)
if self._username:
remaining_length = remaining_length + 2+len(self._username)
connect_flags = connect_flags | 0x80
if self._password:
connect_flags = connect_flags | 0x40
remaining_length = remaining_length + 2+len(self._password)
command = CONNECT
packet = bytearray()
packet.extend(struct.pack("!B", command))
self._pack_remaining_length(packet, remaining_length)
packet.extend(struct.pack("!H"+str(len(protocol))+"sBBH", len(protocol), protocol, proto_ver, connect_flags, keepalive))
self._pack_str16(packet, self._client_id)
if self._will:
self._pack_str16(packet, self._will_topic)
if self._will_payload is None or len(self._will_payload) == 0:
packet.extend(struct.pack("!H", 0))
else:
self._pack_str16(packet, self._will_payload)
if self._username:
self._pack_str16(packet, self._username)
if self._password:
self._pack_str16(packet, self._password)
self._keepalive = keepalive
return self._packet_queue(command, packet, 0, 0)
def _send_disconnect(self):
return self._send_simple_command(DISCONNECT)
def _send_subscribe(self, dup, topics):
remaining_length = 2
for t in topics:
remaining_length = remaining_length + 2+len(t[0])+1
command = SUBSCRIBE | (dup<<3) | (1<<1)
packet = bytearray()
packet.extend(struct.pack("!B", command))
self._pack_remaining_length(packet, remaining_length)
local_mid = self._mid_generate()
packet.extend(struct.pack("!H", local_mid))
for t in topics:
self._pack_str16(packet, t[0])
packet.extend(struct.pack("B", t[1]))
return (self._packet_queue(command, packet, local_mid, 1), local_mid)
def _send_unsubscribe(self, dup, topics):
remaining_length = 2
for t in topics:
remaining_length = remaining_length + 2+len(t)
command = UNSUBSCRIBE | (dup<<3) | (1<<1)
packet = bytearray()
packet.extend(struct.pack("!B", command))
self._pack_remaining_length(packet, remaining_length)
local_mid = self._mid_generate()
packet.extend(struct.pack("!H", local_mid))
for t in topics:
self._pack_str16(packet, t)
return (self._packet_queue(command, packet, local_mid, 1), local_mid)
def _message_retry_check_actual(self, messages, mutex):
mutex.acquire()
now = time.time()
for m in messages:
if m.timestamp + self._message_retry < now:
if m.state == mqtt_ms_wait_for_puback or m.state == mqtt_ms_wait_for_pubrec:
m.timestamp = now
m.dup = True
self._send_publish(m.mid, m.topic, m.payload, m.qos, m.retain, m.dup)
elif m.state == mqtt_ms_wait_for_pubrel:
m.timestamp = now
m.dup = True
self._send_pubrec(m.mid)
elif m.state == mqtt_ms_wait_for_pubcomp:
m.timestamp = now
m.dup = True
self._send_pubrel(m.mid, True)
mutex.release()
def _message_retry_check(self):
self._message_retry_check_actual(self._out_messages, self._out_message_mutex)
self._message_retry_check_actual(self._in_messages, self._in_message_mutex)
def _messages_reconnect_reset_out(self):
self._out_message_mutex.acquire()
self._inflight_messages = 0
for m in self._out_messages:
m.timestamp = 0
if self._max_inflight_messages == 0 or self._inflight_messages < self._max_inflight_messages:
if m.qos == 0:
m.state = mqtt_ms_publish
elif m.qos == 1:
#self._inflight_messages = self._inflight_messages + 1
if m.state == mqtt_ms_wait_for_puback:
m.dup = True
m.state = mqtt_ms_publish
elif m.qos == 2:
#self._inflight_messages = self._inflight_messages + 1
if m.state == mqtt_ms_wait_for_pubcomp:
m.state = mqtt_ms_resend_pubrel
m.dup = True
else:
if m.state == mqtt_ms_wait_for_pubrec:
m.dup = True
m.state = mqtt_ms_publish
else:
m.state = mqtt_ms_queued
self._out_message_mutex.release()
def _messages_reconnect_reset_in(self):
self._in_message_mutex.acquire()
for m in self._in_messages:
m.timestamp = 0
if m.qos != 2:
self._in_messages.pop(self._in_messages.index(m))
else:
# Preserve current state
pass
self._in_message_mutex.release()
def _messages_reconnect_reset(self):
self._messages_reconnect_reset_out()
self._messages_reconnect_reset_in()
def _packet_queue(self, command, packet, mid, qos):
mpkt = dict(
command = command,
mid = mid,
qos = qos,
pos = 0,
to_process = len(packet),
packet = packet)
self._out_packet_mutex.acquire()
self._out_packet.append(mpkt)
if self._current_out_packet_mutex.acquire(False):
if self._current_out_packet is None and len(self._out_packet) > 0:
self._current_out_packet = self._out_packet.pop(0)
self._current_out_packet_mutex.release()
self._out_packet_mutex.release()
# Write a single byte to sockpairW (connected to sockpairR) to break
# out of select() if in threaded mode.
try:
self._sockpairW.send(sockpair_data)
except socket.error as err:
if err.errno != EAGAIN:
raise
if not self._in_callback and self._thread is None:
return self.loop_write()
else:
return MQTT_ERR_SUCCESS
def _packet_handle(self):
cmd = self._in_packet['command']&0xF0
if cmd == PINGREQ:
return self._handle_pingreq()
elif cmd == PINGRESP:
return self._handle_pingresp()
elif cmd == PUBACK:
return self._handle_pubackcomp("PUBACK")
elif cmd == PUBCOMP:
return self._handle_pubackcomp("PUBCOMP")
elif cmd == PUBLISH:
return self._handle_publish()
elif cmd == PUBREC:
return self._handle_pubrec()
elif cmd == PUBREL:
return self._handle_pubrel()
elif cmd == CONNACK:
return self._handle_connack()
elif cmd == SUBACK:
return self._handle_suback()
elif cmd == UNSUBACK:
return self._handle_unsuback()
else:
# If we don't recognise the command, return an error straight away.
self._easy_log(MQTT_LOG_ERR, "Error: Unrecognised command "+str(cmd))
return MQTT_ERR_PROTOCOL
def _handle_pingreq(self):
if self._strict_protocol:
if self._in_packet['remaining_length'] != 0:
return MQTT_ERR_PROTOCOL
self._easy_log(MQTT_LOG_DEBUG, "Received PINGREQ")
return self._send_pingresp()
def _handle_pingresp(self):
if self._strict_protocol:
if self._in_packet['remaining_length'] != 0:
return MQTT_ERR_PROTOCOL
# No longer waiting for a PINGRESP.
self._ping_t = 0
self._easy_log(MQTT_LOG_DEBUG, "Received PINGRESP")
return MQTT_ERR_SUCCESS
def _handle_connack(self):
if self._strict_protocol:
if self._in_packet['remaining_length'] != 2:
return MQTT_ERR_PROTOCOL
if len(self._in_packet['packet']) != 2:
return MQTT_ERR_PROTOCOL
(flags, result) = struct.unpack("!BB", self._in_packet['packet'])
if result == CONNACK_REFUSED_PROTOCOL_VERSION and self._protocol == MQTTv311:
self._easy_log(MQTT_LOG_DEBUG, "Received CONNACK ("+str(flags)+", "+str(result)+"), attempting downgrade to MQTT v3.1.")
# Downgrade to MQTT v3.1
self._protocol = MQTTv31
return self.reconnect()
if result == 0:
self._state = mqtt_cs_connected
self._easy_log(MQTT_LOG_DEBUG, "Received CONNACK ("+str(flags)+", "+str(result)+")")
self._callback_mutex.acquire()
if self.on_connect:
self._in_callback = True
if sys.version_info[0] < 3:
argcount = self.on_connect.func_code.co_argcount
else:
argcount = self.on_connect.__code__.co_argcount
if argcount == 3:
self.on_connect(self, self._userdata, result)
else:
flags_dict = dict()
flags_dict['session present'] = flags & 0x01
self.on_connect(self, self._userdata, flags_dict, result)
self._in_callback = False
self._callback_mutex.release()
if result == 0:
rc = 0
self._out_message_mutex.acquire()
for m in self._out_messages:
m.timestamp = time.time()
if m.state == mqtt_ms_queued:
self.loop_write() # Process outgoing messages that have just been queued up
self._out_message_mutex.release()
return MQTT_ERR_SUCCESS
if m.qos == 0:
self._in_callback = True # Don't call loop_write after _send_publish()
rc = self._send_publish(m.mid, m.topic, m.payload, m.qos, m.retain, m.dup)
self._in_callback = False
if rc != 0:
self._out_message_mutex.release()
return rc
elif m.qos == 1:
if m.state == mqtt_ms_publish:
self._inflight_messages = self._inflight_messages + 1
m.state = mqtt_ms_wait_for_puback
self._in_callback = True # Don't call loop_write after _send_publish()
rc = self._send_publish(m.mid, m.topic, m.payload, m.qos, m.retain, m.dup)
self._in_callback = False
if rc != 0:
self._out_message_mutex.release()
return rc
elif m.qos == 2:
if m.state == mqtt_ms_publish:
self._inflight_messages = self._inflight_messages + 1
m.state = mqtt_ms_wait_for_pubrec
self._in_callback = True # Don't call loop_write after _send_publish()
rc = self._send_publish(m.mid, m.topic, m.payload, m.qos, m.retain, m.dup)
self._in_callback = False
if rc != 0:
self._out_message_mutex.release()
return rc
elif m.state == mqtt_ms_resend_pubrel:
self._inflight_messages = self._inflight_messages + 1
m.state = mqtt_ms_wait_for_pubcomp
self._in_callback = True # Don't call loop_write after _send_pubrel()
rc = self._send_pubrel(m.mid, m.dup)
self._in_callback = False
if rc != 0:
self._out_message_mutex.release()
return rc
self.loop_write() # Process outgoing messages that have just been queued up
self._out_message_mutex.release()
return rc
elif result > 0 and result < 6:
return MQTT_ERR_CONN_REFUSED
else:
return MQTT_ERR_PROTOCOL
def _handle_suback(self):
self._easy_log(MQTT_LOG_DEBUG, "Received SUBACK")
pack_format = "!H" + str(len(self._in_packet['packet'])-2) + 's'
(mid, packet) = struct.unpack(pack_format, self._in_packet['packet'])
pack_format = "!" + "B"*len(packet)
granted_qos = struct.unpack(pack_format, packet)
self._callback_mutex.acquire()
if self.on_subscribe:
self._in_callback = True
self.on_subscribe(self, self._userdata, mid, granted_qos)
self._in_callback = False
self._callback_mutex.release()
return MQTT_ERR_SUCCESS
def _handle_publish(self):
rc = 0
header = self._in_packet['command']
message = MQTTMessage()
message.dup = (header & 0x08)>>3
message.qos = (header & 0x06)>>1
message.retain = (header & 0x01)
pack_format = "!H" + str(len(self._in_packet['packet'])-2) + 's'
(slen, packet) = struct.unpack(pack_format, self._in_packet['packet'])
pack_format = '!' + str(slen) + 's' + str(len(packet)-slen) + 's'
(message.topic, packet) = struct.unpack(pack_format, packet)
if len(message.topic) == 0:
return MQTT_ERR_PROTOCOL
if sys.version_info[0] >= 3:
message.topic = message.topic.decode('utf-8')
if message.qos > 0:
pack_format = "!H" + str(len(packet)-2) + 's'
(message.mid, packet) = struct.unpack(pack_format, packet)
message.payload = packet
self._easy_log(
MQTT_LOG_DEBUG,
"Received PUBLISH (d"+str(message.dup)+
", q"+str(message.qos)+", r"+str(message.retain)+
", m"+str(message.mid)+", '"+message.topic+
"', ... ("+str(len(message.payload))+" bytes)")
message.timestamp = time.time()
if message.qos == 0:
self._handle_on_message(message)
return MQTT_ERR_SUCCESS
elif message.qos == 1:
rc = self._send_puback(message.mid)
self._handle_on_message(message)
return rc
elif message.qos == 2:
rc = self._send_pubrec(message.mid)
message.state = mqtt_ms_wait_for_pubrel
self._in_message_mutex.acquire()
self._in_messages.append(message)
self._in_message_mutex.release()
return rc
else:
return MQTT_ERR_PROTOCOL
def _handle_pubrel(self):
if self._strict_protocol:
if self._in_packet['remaining_length'] != 2:
return MQTT_ERR_PROTOCOL
if len(self._in_packet['packet']) != 2:
return MQTT_ERR_PROTOCOL
mid = struct.unpack("!H", self._in_packet['packet'])
mid = mid[0]
self._easy_log(MQTT_LOG_DEBUG, "Received PUBREL (Mid: "+str(mid)+")")
self._in_message_mutex.acquire()
for i in range(len(self._in_messages)):
if self._in_messages[i].mid == mid:
# Only pass the message on if we have removed it from the queue - this
# prevents multiple callbacks for the same message.
self._handle_on_message(self._in_messages[i])
self._in_messages.pop(i)
self._inflight_messages = self._inflight_messages - 1
if self._max_inflight_messages > 0:
self._out_message_mutex.acquire()
rc = self._update_inflight()
self._out_message_mutex.release()
if rc != MQTT_ERR_SUCCESS:
self._in_message_mutex.release()
return rc
self._in_message_mutex.release()
return self._send_pubcomp(mid)
self._in_message_mutex.release()
return MQTT_ERR_SUCCESS
def _update_inflight(self):
# Dont lock message_mutex here
for m in self._out_messages:
if self._inflight_messages < self._max_inflight_messages:
if m.qos > 0 and m.state == mqtt_ms_queued:
self._inflight_messages = self._inflight_messages + 1
if m.qos == 1:
m.state = mqtt_ms_wait_for_puback
elif m.qos == 2:
m.state = mqtt_ms_wait_for_pubrec
rc = self._send_publish(m.mid, m.topic, m.payload, m.qos, m.retain, m.dup)
if rc != 0:
return rc
else:
return MQTT_ERR_SUCCESS
return MQTT_ERR_SUCCESS
def _handle_pubrec(self):
if self._strict_protocol:
if self._in_packet['remaining_length'] != 2:
return MQTT_ERR_PROTOCOL
mid = struct.unpack("!H", self._in_packet['packet'])
mid = mid[0]
self._easy_log(MQTT_LOG_DEBUG, "Received PUBREC (Mid: "+str(mid)+")")
self._out_message_mutex.acquire()
for m in self._out_messages:
if m.mid == mid:
m.state = mqtt_ms_wait_for_pubcomp
m.timestamp = time.time()
self._out_message_mutex.release()
return self._send_pubrel(mid, False)
self._out_message_mutex.release()
return MQTT_ERR_SUCCESS
def _handle_unsuback(self):
if self._strict_protocol:
if self._in_packet['remaining_length'] != 2:
return MQTT_ERR_PROTOCOL
mid = struct.unpack("!H", self._in_packet['packet'])
mid = mid[0]
self._easy_log(MQTT_LOG_DEBUG, "Received UNSUBACK (Mid: "+str(mid)+")")
self._callback_mutex.acquire()
if self.on_unsubscribe:
self._in_callback = True
self.on_unsubscribe(self, self._userdata, mid)
self._in_callback = False
self._callback_mutex.release()
return MQTT_ERR_SUCCESS
def _handle_pubackcomp(self, cmd):
if self._strict_protocol:
if self._in_packet['remaining_length'] != 2:
return MQTT_ERR_PROTOCOL
mid = struct.unpack("!H", self._in_packet['packet'])
mid = mid[0]
self._easy_log(MQTT_LOG_DEBUG, "Received "+cmd+" (Mid: "+str(mid)+")")
self._out_message_mutex.acquire()
for i in range(len(self._out_messages)):
try:
if self._out_messages[i].mid == mid:
# Only inform the client the message has been sent once.
self._callback_mutex.acquire()
if self.on_publish:
self._out_message_mutex.release()
self._in_callback = True
self.on_publish(self, self._userdata, mid)
self._in_callback = False
self._out_message_mutex.acquire()
self._callback_mutex.release()
self._out_messages.pop(i)
self._inflight_messages = self._inflight_messages - 1
if self._max_inflight_messages > 0:
rc = self._update_inflight()
if rc != MQTT_ERR_SUCCESS:
self._out_message_mutex.release()
return rc
self._out_message_mutex.release()
return MQTT_ERR_SUCCESS
except IndexError:
# Have removed item so i>count.
# Not really an error.
pass
self._out_message_mutex.release()
return MQTT_ERR_SUCCESS
def _handle_on_message(self, message):
self._callback_mutex.acquire()
matched = False
for t in self.on_message_filtered:
if topic_matches_sub(t[0], message.topic):
self._in_callback = True
t[1](self, self._userdata, message)
self._in_callback = False
matched = True
if matched == False and self.on_message:
self._in_callback = True
self.on_message(self, self._userdata, message)
self._in_callback = False
self._callback_mutex.release()
def _thread_main(self):
self._state_mutex.acquire()
if self._state == mqtt_cs_connect_async:
self._state_mutex.release()
self.reconnect()
else:
self._state_mutex.release()
self.loop_forever()
def _host_matches_cert(self, host, cert_host):
if cert_host[0:2] == "*.":
if cert_host.count("*") != 1:
return False
host_match = host.split(".", 1)[1]
cert_match = cert_host.split(".", 1)[1]
if host_match == cert_match:
return True
else:
return False
else:
if host == cert_host:
return True
else:
return False
def _tls_match_hostname(self):
cert = self._ssl.getpeercert()
san = cert.get('subjectAltName')
if san:
have_san_dns = False
for (key, value) in san:
if key == 'DNS':
have_san_dns = True
if self._host_matches_cert(self._host.lower(), value.lower()) == True:
return
if key == 'IP Address':
have_san_dns = True
if value.lower() == self._host.lower():
return
if have_san_dns:
# Only check subject if subjectAltName dns not found.
raise ssl.SSLError('Certificate subject does not match remote hostname.')
subject = cert.get('subject')
if subject:
for ((key, value),) in subject:
if key == 'commonName':
if self._host_matches_cert(self._host.lower(), value.lower()) == True:
return
raise ssl.SSLError('Certificate subject does not match remote hostname.')
# Compatibility class for easy porting from mosquitto.py.
class Mosquitto(Client):
def __init__(self, client_id="", clean_session=True, userdata=None):
super(Mosquitto, self).__init__(client_id, clean_session, userdata)
| {
"pile_set_name": "Github"
} |
-- update module version
UPDATE `sys_modules` SET `version` = '1.3.5' WHERE `uri` = 'photos' AND `version` = '1.3.4';
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved.
*
* OpenArkCompiler is licensed under the Mulan PSL v1.
* You can use this software according to the terms and conditions of the Mulan PSL v1.
* You may obtain a copy of Mulan PSL v1 at:
*
* http://license.coscl.org.cn/MulanPSL
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v1 for more details.
* -@TestCaseID: ThreadConstructors14
*- @TestCaseName: Thread_ThreadConstructors14.java
*- @RequirementName: Java Thread
*- @Title/Destination: Negative input for Constructors Thread(ThreadGroup group, Runnable target)
*- @Brief: see below
* -#step1: Create a thread instance.
* -#step2: Start the thread.
* -#step3: Test Thread(ThreadGroup group, Runnable target) with null params.
* -#step4: Check that no wrong or exception when Thread(ThreadGroup group, Runnable target)'s params are null.
*- @Expect: expected.txt
*- @Priority: High
*- @Source: ThreadConstructors14.java
*- @ExecuteClass: ThreadConstructors14
*- @ExecuteArgs:
*/
public class ThreadConstructors14 extends Thread {
static int i = 0;
public ThreadConstructors14(ThreadGroup group, Runnable target) {
super(group, target);
}
public static void main(String[] args) {
ThreadConstructors14 test_illegal1 = new ThreadConstructors14(null, null);
test_illegal1.start();
try {
test_illegal1.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException");
}
if (i == 1) {
System.out.println("0");
return;
}
System.out.println("2");
return;
}
public void run() {
i++;
super.run();
}
}
// EXEC:%maple %f %build_option -o %n.so
// EXEC:%run %n.so %n %run_option | compare %f
// ASSERT: scan-full 0\n | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8" ?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<wicket:panel xmlns:wicket="http://wicket.apache.org"><input type="submit" value="go" wicket:id="go"/></wicket:panel> | {
"pile_set_name": "Github"
} |
# RUN: llvm-objcopy --version | FileCheck --check-prefix=OBJCOPY %s
# RUN: llvm-objcopy -V | FileCheck --check-prefix=OBJCOPY %s
# RUN: llvm-strip --version | FileCheck --check-prefix=STRIP %s
# RUN: llvm-strip -V | FileCheck --check-prefix=STRIP %s
# RUN: llvm-install-name-tool --version | FileCheck %s
# RUN: llvm-install-name-tool -V | FileCheck %s
# OBJCOPY-DAG: {{ version }}
# OBJCOPY-DAG: GNU objcopy
# STRIP-DAG: {{ version }}
# STRIP-DAG: GNU strip
# CHECK: {{ version }}
| {
"pile_set_name": "Github"
} |
[
{
"status": "played",
"time": "1455451200",
"id": "2043388",
"home": "Arsenal FC",
"score": ["2 ", " 1"],
"away": "Leicester City FC",
"link": "/en-us/match/arsenal-vs-leicester-city/2043388"
},
{
"status": "played",
"time": "1455458700",
"id": "2043390",
"home": "Aston Villa FC",
"score": ["0 ", " 6"],
"away": "Liverpool FC",
"link": "/en-us/match/aston-villa-vs-liverpool/2043390"
},
{
"status": "played",
"time": "1455466500",
"id": "2043399",
"home": "Manchester City FC",
"score": ["1 ", " 2"],
"away": "Tottenham Hotspur FC",
"link": "/en-us/match/manchester-city-vs-tottenham-hotspur/2043399"
},
{
"status": "played",
"time": "1455375600",
"id": "2043398",
"home": "AFC Bournemouth",
"score": ["1 ", " 3"],
"away": "Stoke City FC",
"link": "/en-us/match/afc-bournemouth-vs-stoke-city/2043398"
},
{
"status": "played",
"time": "1455384600",
"id": "2043394",
"home": "Chelsea FC",
"score": ["5 ", " 1"],
"away": "Newcastle United FC",
"link": "/en-us/match/chelsea-vs-newcastle-united/2043394"
},
{
"status": "played",
"time": "1455375600",
"id": "2043401",
"home": "Crystal Palace FC",
"score": ["1 ", " 2"],
"away": "Watford FC",
"link": "/en-us/match/crystal-palace-vs-watford/2043401"
},
{
"status": "played",
"time": "1455375600",
"id": "2043404",
"home": "Everton FC",
"score": ["0 ", " 1"],
"away": "West Bromwich Albion FC",
"link": "/en-us/match/everton-vs-west-bromwich-albion/2043404"
},
{
"status": "played",
"time": "1455375600",
"id": "2043405",
"home": "Norwich City FC",
"score": ["2 ", " 2"],
"away": "West Ham United FC",
"link": "/en-us/match/norwich-city-vs-west-ham-united/2043405"
},
{
"status": "played",
"time": "1455367500",
"id": "2043392",
"home": "Sunderland AFC",
"score": ["2 ", " 1"],
"away": "Manchester United FC",
"link": "/en-us/match/sunderland-vs-manchester-united/2043392"
},
{
"status": "played",
"time": "1455375600",
"id": "2043396",
"home": "Swansea City AFC",
"score": ["0 ", " 1"],
"away": "Southampton FC",
"link": "/en-us/match/swansea-city-vs-southampton/2043396"
},
{
"status": "played",
"time": "1454851800",
"id": "2043372",
"home": "AFC Bournemouth",
"score": ["0 ", " 2"],
"away": "Arsenal FC",
"link": "/en-us/match/afc-bournemouth-vs-arsenal/2043372"
},
{
"status": "played",
"time": "1454860800",
"id": "2043379",
"home": "Chelsea FC",
"score": ["1 ", " 1"],
"away": "Manchester United FC",
"link": "/en-us/match/chelsea-vs-manchester-united/2043379"
},
{
"status": "played",
"time": "1454770800",
"id": "2043380",
"home": "Aston Villa FC",
"score": ["2 ", " 0"],
"away": "Norwich City FC",
"link": "/en-us/match/aston-villa-vs-norwich-city/2043380"
},
{
"status": "played",
"time": "1454770800",
"id": "2043382",
"home": "Liverpool FC",
"score": ["2 ", " 2"],
"away": "Sunderland AFC",
"link": "/en-us/match/liverpool-vs-sunderland/2043382"
},
{
"status": "played",
"time": "1454762700",
"id": "2043377",
"home": "Manchester City FC",
"score": ["1 ", " 3"],
"away": "Leicester City FC",
"link": "/en-us/match/manchester-city-vs-leicester-city/2043377"
},
{
"status": "played",
"time": "1454770800",
"id": "2043385",
"home": "Newcastle United FC",
"score": ["1 ", " 0"],
"away": "West Bromwich Albion FC",
"link": "/en-us/match/newcastle-united-vs-west-bromwich-albion/2043385"
},
{
"status": "played",
"time": "1454779800",
"id": "2043387",
"home": "Southampton FC",
"score": ["1 ", " 0"],
"away": "West Ham United FC",
"link": "/en-us/match/southampton-vs-west-ham-united/2043387"
},
{
"status": "played",
"time": "1454770800",
"id": "2043375",
"home": "Stoke City FC",
"score": ["0 ", " 3"],
"away": "Everton FC",
"link": "/en-us/match/stoke-city-vs-everton/2043375"
},
{
"status": "played",
"time": "1454770800",
"id": "2043373",
"home": "Swansea City AFC",
"score": ["1 ", " 1"],
"away": "Crystal Palace FC",
"link": "/en-us/match/swansea-city-vs-crystal-palace/2043373"
},
{
"status": "played",
"time": "1454770800",
"id": "2043383",
"home": "Tottenham Hotspur FC",
"score": ["1 ", " 0"],
"away": "Watford FC",
"link": "/en-us/match/tottenham-hotspur-vs-watford/2043383"
},
{
"status": "played",
"time": "1454528700",
"id": "2043370",
"home": "Everton FC",
"score": ["3 ", " 0"],
"away": "Newcastle United FC",
"link": "/en-us/match/everton-vs-newcastle-united/2043370"
},
{
"status": "played",
"time": "1454528700",
"id": "2043359",
"home": "Watford FC",
"score": ["0 ", " 0"],
"away": "Chelsea FC",
"link": "/en-us/match/watford-vs-chelsea/2043359"
},
{
"status": "played",
"time": "1454442300",
"id": "2043364",
"home": "Arsenal FC",
"score": ["0 ", " 0"],
"away": "Southampton FC",
"link": "/en-us/match/arsenal-vs-southampton/2043364"
},
{
"status": "played",
"time": "1454443200",
"id": "2043357",
"home": "Crystal Palace FC",
"score": ["1 ", " 2"],
"away": "AFC Bournemouth",
"link": "/en-us/match/crystal-palace-vs-afc-bournemouth/2043357"
},
{
"status": "played",
"time": "1454442300",
"id": "2043361",
"home": "Leicester City FC",
"score": ["2 ", " 0"],
"away": "Liverpool FC",
"link": "/en-us/match/leicester-city-vs-liverpool/2043361"
},
{
"status": "played",
"time": "1454443200",
"id": "2043365",
"home": "Manchester United FC",
"score": ["3 ", " 0"],
"away": "Stoke City FC",
"link": "/en-us/match/manchester-united-vs-stoke-city/2043365"
},
{
"status": "played",
"time": "1454442300",
"id": "2043369",
"home": "Norwich City FC",
"score": ["0 ", " 3"],
"away": "Tottenham Hotspur FC",
"link": "/en-us/match/norwich-city-vs-tottenham-hotspur/2043369"
},
{
"status": "played",
"time": "1454442300",
"id": "2043362",
"home": "Sunderland AFC",
"score": ["0 ", " 1"],
"away": "Manchester City FC",
"link": "/en-us/match/sunderland-vs-manchester-city/2043362"
},
{
"status": "played",
"time": "1454443200",
"id": "2043367",
"home": "West Bromwich Albion FC",
"score": ["1 ", " 1"],
"away": "Swansea City AFC",
"link": "/en-us/match/west-bromwich-albion-vs-swansea-city/2043367"
},
{
"status": "played",
"time": "1454442300",
"id": "2043356",
"home": "West Ham United FC",
"score": ["2 ", " 0"],
"away": "Aston Villa FC",
"link": "/en-us/match/west-ham-united-vs-aston-villa/2043356"
},
{
"status": "played",
"time": "1453651200",
"id": "2043342",
"home": "Arsenal FC",
"score": ["0 ", " 1"],
"away": "Chelsea FC",
"link": "/en-us/match/arsenal-vs-chelsea/2043342"
},
{
"status": "played",
"time": "1453642200",
"id": "2043353",
"home": "Everton FC",
"score": ["1 ", " 2"],
"away": "Swansea City AFC",
"link": "/en-us/match/everton-vs-swansea-city/2043353"
},
{
"status": "played",
"time": "1453561200",
"id": "2043354",
"home": "Crystal Palace FC",
"score": ["1 ", " 3"],
"away": "Tottenham Hotspur FC",
"link": "/en-us/match/crystal-palace-vs-tottenham-hotspur/2043354"
},
{
"status": "played",
"time": "1453561200",
"id": "2043351",
"home": "Leicester City FC",
"score": ["3 ", " 0"],
"away": "Stoke City FC",
"link": "/en-us/match/leicester-city-vs-stoke-city/2043351"
},
{
"status": "played",
"time": "1453561200",
"id": "2043349",
"home": "Manchester United FC",
"score": ["0 ", " 1"],
"away": "Southampton FC",
"link": "/en-us/match/manchester-united-vs-southampton/2043349"
},
{
"status": "played",
"time": "1453553100",
"id": "2043344",
"home": "Norwich City FC",
"score": ["4 ", " 5"],
"away": "Liverpool FC",
"link": "/en-us/match/norwich-city-vs-liverpool/2043344"
},
{
"status": "played",
"time": "1453561200",
"id": "2043340",
"home": "Sunderland AFC",
"score": ["1 ", " 1"],
"away": "AFC Bournemouth",
"link": "/en-us/match/sunderland-vs-afc-bournemouth/2043340"
},
{
"status": "played",
"time": "1453561200",
"id": "2043347",
"home": "Watford FC",
"score": ["2 ", " 1"],
"away": "Newcastle United FC",
"link": "/en-us/match/watford-vs-newcastle-united/2043347"
},
{
"status": "played",
"time": "1453561200",
"id": "2043339",
"home": "West Bromwich Albion FC",
"score": ["0 ", " 0"],
"away": "Aston Villa FC",
"link": "/en-us/match/west-bromwich-albion-vs-aston-villa/2043339"
},
{
"status": "played",
"time": "1453570200",
"id": "2043346",
"home": "West Ham United FC",
"score": ["2 ", " 2"],
"away": "Manchester City FC",
"link": "/en-us/match/west-ham-united-vs-manchester-city/2043346"
},
{
"status": "played",
"time": "1453147200",
"id": "2043334",
"home": "Swansea City AFC",
"score": ["1 ", " 0"],
"away": "Watford FC",
"link": "/en-us/match/swansea-city-vs-watford/2043334"
},
{
"status": "played",
"time": "1453039500",
"id": "2043329",
"home": "Liverpool FC",
"score": ["0 ", " 1"],
"away": "Manchester United FC",
"link": "/en-us/match/liverpool-vs-manchester-united/2043329"
},
{
"status": "played",
"time": "1453047300",
"id": "2043323",
"home": "Stoke City FC",
"score": ["0 ", " 0"],
"away": "Arsenal FC",
"link": "/en-us/match/stoke-city-vs-arsenal/2043323"
},
{
"status": "played",
"time": "1452956400",
"id": "2043331",
"home": "AFC Bournemouth",
"score": ["3 ", " 0"],
"away": "Norwich City FC",
"link": "/en-us/match/afc-bournemouth-vs-norwich-city/2043331"
},
{
"status": "played",
"time": "1452965400",
"id": "2043328",
"home": "Aston Villa FC",
"score": ["1 ", " 1"],
"away": "Leicester City FC",
"link": "/en-us/match/aston-villa-vs-leicester-city/2043328"
},
{
"status": "played",
"time": "1452956400",
"id": "2043326",
"home": "Chelsea FC",
"score": ["3 ", " 3"],
"away": "Everton FC",
"link": "/en-us/match/chelsea-vs-everton/2043326"
},
{
"status": "played",
"time": "1452956400",
"id": "2043324",
"home": "Manchester City FC",
"score": ["4 ", " 0"],
"away": "Crystal Palace FC",
"link": "/en-us/match/manchester-city-vs-crystal-palace/2043324"
},
{
"status": "played",
"time": "1452956400",
"id": "2043338",
"home": "Newcastle United FC",
"score": ["2 ", " 1"],
"away": "West Ham United FC",
"link": "/en-us/match/newcastle-united-vs-west-ham-united/2043338"
},
{
"status": "played",
"time": "1452956400",
"id": "2043336",
"home": "Southampton FC",
"score": ["3 ", " 0"],
"away": "West Bromwich Albion FC",
"link": "/en-us/match/southampton-vs-west-bromwich-albion/2043336"
},
{
"status": "played",
"time": "1452948300",
"id": "2043333",
"home": "Tottenham Hotspur FC",
"score": ["4 ", " 1"],
"away": "Sunderland AFC",
"link": "/en-us/match/tottenham-hotspur-vs-sunderland/2043333"
},
{
"status": "played",
"time": "1452714300",
"id": "2043321",
"home": "Chelsea FC",
"score": ["2 ", " 2"],
"away": "West Bromwich Albion FC",
"link": "/en-us/match/chelsea-vs-west-bromwich-albion/2043321"
},
{
"status": "played",
"time": "1452715200",
"id": "2043306",
"home": "Liverpool FC",
"score": ["3 ", " 3"],
"away": "Arsenal FC",
"link": "/en-us/match/liverpool-vs-arsenal/2043306"
},
{
"status": "played",
"time": "1452714300",
"id": "2043313",
"home": "Manchester City FC",
"score": ["0 ", " 0"],
"away": "Everton FC",
"link": "/en-us/match/manchester-city-vs-everton/2043313"
},
{
"status": "played",
"time": "1452714300",
"id": "2043320",
"home": "Southampton FC",
"score": ["2 ", " 0"],
"away": "Watford FC",
"link": "/en-us/match/southampton-vs-watford/2043320"
},
{
"status": "played",
"time": "1452714300",
"id": "2043318",
"home": "Stoke City FC",
"score": ["3 ", " 1"],
"away": "Norwich City FC",
"link": "/en-us/match/stoke-city-vs-norwich-city/2043318"
},
{
"status": "played",
"time": "1452714300",
"id": "2043309",
"home": "Swansea City AFC",
"score": ["2 ", " 4"],
"away": "Sunderland AFC",
"link": "/en-us/match/swansea-city-vs-sunderland/2043309"
},
{
"status": "played",
"time": "1452715200",
"id": "2043315",
"home": "Tottenham Hotspur FC",
"score": ["0 ", " 1"],
"away": "Leicester City FC",
"link": "/en-us/match/tottenham-hotspur-vs-leicester-city/2043315"
},
{
"status": "played",
"time": "1452627900",
"id": "2043311",
"home": "AFC Bournemouth",
"score": ["1 ", " 3"],
"away": "West Ham United FC",
"link": "/en-us/match/afc-bournemouth-vs-west-ham-united/2043311"
},
{
"status": "played",
"time": "1452627900",
"id": "2043308",
"home": "Aston Villa FC",
"score": ["1 ", " 0"],
"away": "Crystal Palace FC",
"link": "/en-us/match/aston-villa-vs-crystal-palace/2043308"
},
{
"status": "played",
"time": "1452627900",
"id": "2043316",
"home": "Newcastle United FC",
"score": ["3 ", " 3"],
"away": "Manchester United FC",
"link": "/en-us/match/newcastle-united-vs-manchester-united/2043316"
},
{
"status": "played",
"time": "1451827800",
"id": "2043291",
"home": "Crystal Palace FC",
"score": ["0 ", " 3"],
"away": "Chelsea FC",
"link": "/en-us/match/crystal-palace-vs-chelsea/2043291"
},
{
"status": "played",
"time": "1451836800",
"id": "2043304",
"home": "Everton FC",
"score": ["1 ", " 1"],
"away": "Tottenham Hotspur FC",
"link": "/en-us/match/everton-vs-tottenham-hotspur/2043304"
},
{
"status": "played",
"time": "1451746800",
"id": "2043297",
"home": "Arsenal FC",
"score": ["1 ", " 0"],
"away": "Newcastle United FC",
"link": "/en-us/match/arsenal-vs-newcastle-united/2043297"
},
{
"status": "played",
"time": "1451746800",
"id": "2043289",
"home": "Leicester City FC",
"score": ["0 ", " 0"],
"away": "AFC Bournemouth",
"link": "/en-us/match/leicester-city-vs-afc-bournemouth/2043289"
},
{
"status": "played",
"time": "1451746800",
"id": "2043302",
"home": "Manchester United FC",
"score": ["2 ", " 1"],
"away": "Swansea City AFC",
"link": "/en-us/match/manchester-united-vs-swansea-city/2043302"
},
{
"status": "played",
"time": "1451746800",
"id": "2043299",
"home": "Norwich City FC",
"score": ["1 ", " 0"],
"away": "Southampton FC",
"link": "/en-us/match/norwich-city-vs-southampton/2043299"
},
{
"status": "played",
"time": "1451746800",
"id": "2043288",
"home": "Sunderland AFC",
"score": ["3 ", " 1"],
"away": "Aston Villa FC",
"link": "/en-us/match/sunderland-vs-aston-villa/2043288"
},
{
"status": "played",
"time": "1451755800",
"id": "2043295",
"home": "Watford FC",
"score": ["1 ", " 2"],
"away": "Manchester City FC",
"link": "/en-us/match/watford-vs-manchester-city/2043295"
},
{
"status": "played",
"time": "1451746800",
"id": "2043301",
"home": "West Bromwich Albion FC",
"score": ["2 ", " 1"],
"away": "Stoke City FC",
"link": "/en-us/match/west-bromwich-albion-vs-stoke-city/2043301"
},
{
"status": "played",
"time": "1451738700",
"id": "2043293",
"home": "West Ham United FC",
"score": ["2 ", " 0"],
"away": "Liverpool FC",
"link": "/en-us/match/west-ham-united-vs-liverpool/2043293"
},
{
"status": "played",
"time": "1451504700",
"id": "2043275",
"home": "Sunderland AFC",
"score": ["0 ", " 1"],
"away": "Liverpool FC",
"link": "/en-us/match/sunderland-vs-liverpool/2043275"
},
{
"status": "played",
"time": "1451418300",
"id": "2043277",
"home": "Leicester City FC",
"score": ["0 ", " 0"],
"away": "Manchester City FC",
"link": "/en-us/match/leicester-city-vs-manchester-city/2043277"
},
{
"status": "played",
"time": "1451323800",
"id": "2043272",
"home": "Arsenal FC",
"score": ["2 ", " 0"],
"away": "AFC Bournemouth",
"link": "/en-us/match/arsenal-vs-afc-bournemouth/2043272"
},
{
"status": "played",
"time": "1451314800",
"id": "2043284",
"home": "Crystal Palace FC",
"score": ["0 ", " 0"],
"away": "Swansea City AFC",
"link": "/en-us/match/crystal-palace-vs-swansea-city/2043284"
},
{
"status": "played",
"time": "1451314800",
"id": "2043283",
"home": "Everton FC",
"score": ["3 ", " 4"],
"away": "Stoke City FC",
"link": "/en-us/match/everton-vs-stoke-city/2043283"
},
{
"status": "played",
"time": "1451323800",
"id": "2043273",
"home": "Manchester United FC",
"score": ["0 ", " 0"],
"away": "Chelsea FC",
"link": "/en-us/match/manchester-united-vs-chelsea/2043273"
},
{
"status": "played",
"time": "1451314800",
"id": "2043270",
"home": "Norwich City FC",
"score": ["2 ", " 0"],
"away": "Aston Villa FC",
"link": "/en-us/match/norwich-city-vs-aston-villa/2043270"
},
{
"status": "played",
"time": "1451314800",
"id": "2043286",
"home": "Watford FC",
"score": ["1 ", " 2"],
"away": "Tottenham Hotspur FC",
"link": "/en-us/match/watford-vs-tottenham-hotspur/2043286"
},
{
"status": "played",
"time": "1451314800",
"id": "2043279",
"home": "West Bromwich Albion FC",
"score": ["1 ", " 0"],
"away": "Newcastle United FC",
"link": "/en-us/match/west-bromwich-albion-vs-newcastle-united/2043279"
},
{
"status": "played",
"time": "1451323800",
"id": "2043281",
"home": "West Ham United FC",
"score": ["2 ", " 1"],
"away": "Southampton FC",
"link": "/en-us/match/west-ham-united-vs-southampton/2043281"
},
{
"status": "played",
"time": "1451142000",
"id": "2043255",
"home": "AFC Bournemouth",
"score": ["0 ", " 0"],
"away": "Crystal Palace FC",
"link": "/en-us/match/afc-bournemouth-vs-crystal-palace/2043255"
},
{
"status": "played",
"time": "1451142000",
"id": "2043268",
"home": "Aston Villa FC",
"score": ["1 ", " 1"],
"away": "West Ham United FC",
"link": "/en-us/match/aston-villa-vs-west-ham-united/2043268"
},
{
"status": "played",
"time": "1451142000",
"id": "2043265",
"home": "Chelsea FC",
"score": ["2 ", " 2"],
"away": "Watford FC",
"link": "/en-us/match/chelsea-vs-watford/2043265"
},
{
"status": "played",
"time": "1451142000",
"id": "2043258",
"home": "Liverpool FC",
"score": ["1 ", " 0"],
"away": "Leicester City FC",
"link": "/en-us/match/liverpool-vs-leicester-city/2043258"
},
{
"status": "played",
"time": "1451142000",
"id": "2043263",
"home": "Manchester City FC",
"score": ["4 ", " 1"],
"away": "Sunderland AFC",
"link": "/en-us/match/manchester-city-vs-sunderland/2043263"
},
{
"status": "played",
"time": "1451151000",
"id": "2043256",
"home": "Newcastle United FC",
"score": ["0 ", " 1"],
"away": "Everton FC",
"link": "/en-us/match/newcastle-united-vs-everton/2043256"
},
{
"status": "played",
"time": "1451159100",
"id": "2043253",
"home": "Southampton FC",
"score": ["4 ", " 0"],
"away": "Arsenal FC",
"link": "/en-us/match/southampton-vs-arsenal/2043253"
},
{
"status": "played",
"time": "1451133900",
"id": "2043260",
"home": "Stoke City FC",
"score": ["2 ", " 0"],
"away": "Manchester United FC",
"link": "/en-us/match/stoke-city-vs-manchester-united/2043260"
},
{
"status": "played",
"time": "1451142000",
"id": "2043267",
"home": "Swansea City AFC",
"score": ["1 ", " 0"],
"away": "West Bromwich Albion FC",
"link": "/en-us/match/swansea-city-vs-west-bromwich-albion/2043267"
},
{
"status": "played",
"time": "1451142000",
"id": "2043262",
"home": "Tottenham Hotspur FC",
"score": ["3 ", " 0"],
"away": "Norwich City FC",
"link": "/en-us/match/tottenham-hotspur-vs-norwich-city/2043262"
},
{
"status": "played",
"time": "1450728000",
"id": "2043243",
"home": "Arsenal FC",
"score": ["2 ", " 1"],
"away": "Manchester City FC",
"link": "/en-us/match/arsenal-vs-manchester-city/2043243"
},
{
"status": "played",
"time": "1450627200",
"id": "2043251",
"home": "Swansea City AFC",
"score": ["0 ", " 0"],
"away": "West Ham United FC",
"link": "/en-us/match/swansea-city-vs-west-ham-united/2043251"
},
{
"status": "played",
"time": "1450618200",
"id": "2043242",
"home": "Watford FC",
"score": ["3 ", " 0"],
"away": "Liverpool FC",
"link": "/en-us/match/watford-vs-liverpool/2043242"
},
{
"status": "played",
"time": "1450537200",
"id": "2043247",
"home": "Chelsea FC",
"score": ["3 ", " 1"],
"away": "Sunderland AFC",
"link": "/en-us/match/chelsea-vs-sunderland/2043247"
},
{
"status": "played",
"time": "1450537200",
"id": "2043240",
"home": "Everton FC",
"score": ["2 ", " 3"],
"away": "Leicester City FC",
"link": "/en-us/match/everton-vs-leicester-city/2043240"
},
{
"status": "played",
"time": "1450537200",
"id": "2043245",
"home": "Manchester United FC",
"score": ["1 ", " 2"],
"away": "Norwich City FC",
"link": "/en-us/match/manchester-united-vs-norwich-city/2043245"
},
{
"status": "played",
"time": "1450546200",
"id": "2043235",
"home": "Newcastle United FC",
"score": ["1 ", " 1"],
"away": "Aston Villa FC",
"link": "/en-us/match/newcastle-united-vs-aston-villa/2043235"
},
{
"status": "played",
"time": "1450537200",
"id": "2043249",
"home": "Southampton FC",
"score": ["0 ", " 2"],
"away": "Tottenham Hotspur FC",
"link": "/en-us/match/southampton-vs-tottenham-hotspur/2043249"
},
{
"status": "played",
"time": "1450537200",
"id": "2043238",
"home": "Stoke City FC",
"score": ["1 ", " 2"],
"away": "Crystal Palace FC",
"link": "/en-us/match/stoke-city-vs-crystal-palace/2043238"
},
{
"status": "played",
"time": "1450537200",
"id": "2043237",
"home": "West Bromwich Albion FC",
"score": ["1 ", " 2"],
"away": "AFC Bournemouth",
"link": "/en-us/match/west-bromwich-albion-vs-afc-bournemouth/2043237"
},
{
"status": "played",
"time": "1450123200",
"id": "2043220",
"home": "Leicester City FC",
"score": ["2 ", " 1"],
"away": "Chelsea FC",
"link": "/en-us/match/leicester-city-vs-chelsea/2043220"
},
{
"status": "played",
"time": "1450013400",
"id": "2043218",
"home": "Aston Villa FC",
"score": ["0 ", " 2"],
"away": "Arsenal FC",
"link": "/en-us/match/aston-villa-vs-arsenal/2043218"
},
{
"status": "played",
"time": "1450022400",
"id": "2043233",
"home": "Liverpool FC",
"score": ["2 ", " 2"],
"away": "West Bromwich Albion FC",
"link": "/en-us/match/liverpool-vs-west-bromwich-albion/2043233"
},
{
"status": "played",
"time": "1450022400",
"id": "2043225",
"home": "Tottenham Hotspur FC",
"score": ["1 ", " 2"],
"away": "Newcastle United FC",
"link": "/en-us/match/tottenham-hotspur-vs-newcastle-united/2043225"
},
{
"status": "played",
"time": "1449941400",
"id": "2043224",
"home": "AFC Bournemouth",
"score": ["2 ", " 1"],
"away": "Manchester United FC",
"link": "/en-us/match/afc-bournemouth-vs-manchester-united/2043224"
},
{
"status": "played",
"time": "1449932400",
"id": "2043227",
"home": "Crystal Palace FC",
"score": ["1 ", " 0"],
"away": "Southampton FC",
"link": "/en-us/match/crystal-palace-vs-southampton/2043227"
},
{
"status": "played",
"time": "1449932400",
"id": "2043230",
"home": "Manchester City FC",
"score": ["2 ", " 1"],
"away": "Swansea City AFC",
"link": "/en-us/match/manchester-city-vs-swansea-city/2043230"
},
{
"status": "played",
"time": "1449924300",
"id": "2043222",
"home": "Norwich City FC",
"score": ["1 ", " 1"],
"away": "Everton FC",
"link": "/en-us/match/norwich-city-vs-everton/2043222"
},
{
"status": "played",
"time": "1449932400",
"id": "2043232",
"home": "Sunderland AFC",
"score": ["0 ", " 1"],
"away": "Watford FC",
"link": "/en-us/match/sunderland-vs-watford/2043232"
},
{
"status": "played",
"time": "1449932400",
"id": "2043229",
"home": "West Ham United FC",
"score": ["0 ", " 0"],
"away": "Stoke City FC",
"link": "/en-us/match/west-ham-united-vs-stoke-city/2043229"
},
{
"status": "played",
"time": "1449518400",
"id": "2043204",
"home": "Everton FC",
"score": ["1 ", " 1"],
"away": "Crystal Palace FC",
"link": "/en-us/match/everton-vs-crystal-palace/2043204"
},
{
"status": "played",
"time": "1449417600",
"id": "2043207",
"home": "Newcastle United FC",
"score": ["2 ", " 0"],
"away": "Liverpool FC",
"link": "/en-us/match/newcastle-united-vs-liverpool/2043207"
},
{
"status": "played",
"time": "1449327600",
"id": "2043212",
"home": "Arsenal FC",
"score": ["3 ", " 1"],
"away": "Sunderland AFC",
"link": "/en-us/match/arsenal-vs-sunderland/2043212"
},
{
"status": "played",
"time": "1449336600",
"id": "2043202",
"home": "Chelsea FC",
"score": ["0 ", " 1"],
"away": "AFC Bournemouth",
"link": "/en-us/match/chelsea-vs-afc-bournemouth/2043202"
},
{
"status": "played",
"time": "1449327600",
"id": "2043216",
"home": "Manchester United FC",
"score": ["0 ", " 0"],
"away": "West Ham United FC",
"link": "/en-us/match/manchester-united-vs-west-ham-united/2043216"
},
{
"status": "played",
"time": "1449327600",
"id": "2043200",
"home": "Southampton FC",
"score": ["1 ", " 1"],
"away": "Aston Villa FC",
"link": "/en-us/match/southampton-vs-aston-villa/2043200"
},
{
"status": "played",
"time": "1449319500",
"id": "2043209",
"home": "Stoke City FC",
"score": ["2 ", " 0"],
"away": "Manchester City FC",
"link": "/en-us/match/stoke-city-vs-manchester-city/2043209"
},
{
"status": "played",
"time": "1449327600",
"id": "2043205",
"home": "Swansea City AFC",
"score": ["0 ", " 3"],
"away": "Leicester City FC",
"link": "/en-us/match/swansea-city-vs-leicester-city/2043205"
},
{
"status": "played",
"time": "1449327600",
"id": "2043211",
"home": "Watford FC",
"score": ["2 ", " 0"],
"away": "Norwich City FC",
"link": "/en-us/match/watford-vs-norwich-city/2043211"
},
{
"status": "played",
"time": "1449327600",
"id": "2043214",
"home": "West Bromwich Albion FC",
"score": ["1 ", " 1"],
"away": "Tottenham Hotspur FC",
"link": "/en-us/match/west-bromwich-albion-vs-tottenham-hotspur/2043214"
},
{
"status": "played",
"time": "1448813700",
"id": "2043195",
"home": "Liverpool FC",
"score": ["1 ", " 0"],
"away": "Swansea City AFC",
"link": "/en-us/match/liverpool-vs-swansea-city/2043195"
},
{
"status": "played",
"time": "1448813700",
"id": "2043185",
"home": "Norwich City FC",
"score": ["1 ", " 1"],
"away": "Arsenal FC",
"link": "/en-us/match/norwich-city-vs-arsenal/2043185"
},
{
"status": "played",
"time": "1448798400",
"id": "2043186",
"home": "Tottenham Hotspur FC",
"score": ["0 ", " 0"],
"away": "Chelsea FC",
"link": "/en-us/match/tottenham-hotspur-vs-chelsea/2043186"
},
{
"status": "played",
"time": "1448805900",
"id": "2043199",
"home": "West Ham United FC",
"score": ["1 ", " 1"],
"away": "West Bromwich Albion FC",
"link": "/en-us/match/west-ham-united-vs-west-bromwich-albion/2043199"
},
{
"status": "played",
"time": "1448722800",
"id": "2043188",
"home": "AFC Bournemouth",
"score": ["3 ", " 3"],
"away": "Everton FC",
"link": "/en-us/match/afc-bournemouth-vs-everton/2043188"
},
{
"status": "played",
"time": "1448722800",
"id": "2043197",
"home": "Aston Villa FC",
"score": ["2 ", " 3"],
"away": "Watford FC",
"link": "/en-us/match/aston-villa-vs-watford/2043197"
},
{
"status": "played",
"time": "1448722800",
"id": "2043191",
"home": "Crystal Palace FC",
"score": ["5 ", " 1"],
"away": "Newcastle United FC",
"link": "/en-us/match/crystal-palace-vs-newcastle-united/2043191"
},
{
"status": "played",
"time": "1448731800",
"id": "2043189",
"home": "Leicester City FC",
"score": ["1 ", " 1"],
"away": "Manchester United FC",
"link": "/en-us/match/leicester-city-vs-manchester-united/2043189"
},
{
"status": "played",
"time": "1448722800",
"id": "2043193",
"home": "Manchester City FC",
"score": ["3 ", " 1"],
"away": "Southampton FC",
"link": "/en-us/match/manchester-city-vs-southampton/2043193"
},
{
"status": "played",
"time": "1448722800",
"id": "2043194",
"home": "Sunderland AFC",
"score": ["2 ", " 0"],
"away": "Stoke City FC",
"link": "/en-us/match/sunderland-vs-stoke-city/2043194"
},
{
"status": "played",
"time": "1448308800",
"id": "2043182",
"home": "Crystal Palace FC",
"score": ["0 ", " 1"],
"away": "Sunderland AFC",
"link": "/en-us/match/crystal-palace-vs-sunderland/2043182"
},
{
"status": "played",
"time": "1448208000",
"id": "2043183",
"home": "Tottenham Hotspur FC",
"score": ["4 ", " 1"],
"away": "West Ham United FC",
"link": "/en-us/match/tottenham-hotspur-vs-west-ham-united/2043183"
},
{
"status": "played",
"time": "1448118000",
"id": "2043178",
"home": "Chelsea FC",
"score": ["1 ", " 0"],
"away": "Norwich City FC",
"link": "/en-us/match/chelsea-vs-norwich-city/2043178"
},
{
"status": "played",
"time": "1448118000",
"id": "2043170",
"home": "Everton FC",
"score": ["4 ", " 0"],
"away": "Aston Villa FC",
"link": "/en-us/match/everton-vs-aston-villa/2043170"
},
{
"status": "played",
"time": "1448127000",
"id": "2043175",
"home": "Manchester City FC",
"score": ["1 ", " 4"],
"away": "Liverpool FC",
"link": "/en-us/match/manchester-city-vs-liverpool/2043175"
},
{
"status": "played",
"time": "1448118000",
"id": "2043173",
"home": "Newcastle United FC",
"score": ["0 ", " 3"],
"away": "Leicester City FC",
"link": "/en-us/match/newcastle-united-vs-leicester-city/2043173"
},
{
"status": "played",
"time": "1448118000",
"id": "2043180",
"home": "Southampton FC",
"score": ["0 ", " 1"],
"away": "Stoke City FC",
"link": "/en-us/match/southampton-vs-stoke-city/2043180"
},
{
"status": "played",
"time": "1448118000",
"id": "2043172",
"home": "Swansea City AFC",
"score": ["2 ", " 2"],
"away": "AFC Bournemouth",
"link": "/en-us/match/swansea-city-vs-afc-bournemouth/2043172"
},
{
"status": "played",
"time": "1448109900",
"id": "2043177",
"home": "Watford FC",
"score": ["1 ", " 2"],
"away": "Manchester United FC",
"link": "/en-us/match/watford-vs-manchester-united/2043177"
},
{
"status": "played",
"time": "1448118000",
"id": "2043169",
"home": "West Bromwich Albion FC",
"score": ["2 ", " 1"],
"away": "Arsenal FC",
"link": "/en-us/match/west-bromwich-albion-vs-arsenal/2043169"
},
{
"status": "played",
"time": "1446998400",
"id": "2043164",
"home": "Arsenal FC",
"score": ["1 ", " 1"],
"away": "Tottenham Hotspur FC",
"link": "/en-us/match/arsenal-vs-tottenham-hotspur/2043164"
},
{
"status": "played",
"time": "1446989400",
"id": "2043158",
"home": "Aston Villa FC",
"score": ["0 ", " 0"],
"away": "Manchester City FC",
"link": "/en-us/match/aston-villa-vs-manchester-city/2043158"
},
{
"status": "played",
"time": "1446998400",
"id": "2043156",
"home": "Liverpool FC",
"score": ["1 ", " 2"],
"away": "Crystal Palace FC",
"link": "/en-us/match/liverpool-vs-crystal-palace/2043156"
},
{
"status": "played",
"time": "1446900300",
"id": "2043159",
"home": "AFC Bournemouth",
"score": ["0 ", " 1"],
"away": "Newcastle United FC",
"link": "/en-us/match/afc-bournemouth-vs-newcastle-united/2043159"
},
{
"status": "played",
"time": "1446908400",
"id": "2043165",
"home": "Leicester City FC",
"score": ["2 ", " 1"],
"away": "Watford FC",
"link": "/en-us/match/leicester-city-vs-watford/2043165"
},
{
"status": "played",
"time": "1446908400",
"id": "2043167",
"home": "Manchester United FC",
"score": ["2 ", " 0"],
"away": "West Bromwich Albion FC",
"link": "/en-us/match/manchester-united-vs-west-bromwich-albion/2043167"
},
{
"status": "played",
"time": "1446908400",
"id": "2043162",
"home": "Norwich City FC",
"score": ["1 ", " 0"],
"away": "Swansea City AFC",
"link": "/en-us/match/norwich-city-vs-swansea-city/2043162"
},
{
"status": "played",
"time": "1446917400",
"id": "2043155",
"home": "Stoke City FC",
"score": ["1 ", " 0"],
"away": "Chelsea FC",
"link": "/en-us/match/stoke-city-vs-chelsea/2043155"
},
{
"status": "played",
"time": "1446908400",
"id": "2043160",
"home": "Sunderland AFC",
"score": ["0 ", " 1"],
"away": "Southampton FC",
"link": "/en-us/match/sunderland-vs-southampton/2043160"
},
{
"status": "played",
"time": "1446908400",
"id": "2043157",
"home": "West Ham United FC",
"score": ["1 ", " 1"],
"away": "Everton FC",
"link": "/en-us/match/west-ham-united-vs-everton/2043157"
},
{
"status": "played",
"time": "1446494400",
"id": "2043146",
"home": "Tottenham Hotspur FC",
"score": ["3 ", " 1"],
"away": "Aston Villa FC",
"link": "/en-us/match/tottenham-hotspur-vs-aston-villa/2043146"
},
{
"status": "played",
"time": "1446384600",
"id": "2043153",
"home": "Everton FC",
"score": ["6 ", " 2"],
"away": "Sunderland AFC",
"link": "/en-us/match/everton-vs-sunderland/2043153"
},
{
"status": "played",
"time": "1446393600",
"id": "2043147",
"home": "Southampton FC",
"score": ["2 ", " 0"],
"away": "AFC Bournemouth",
"link": "/en-us/match/southampton-vs-afc-bournemouth/2043147"
},
{
"status": "played",
"time": "1446295500",
"id": "2043149",
"home": "Chelsea FC",
"score": ["1 ", " 3"],
"away": "Liverpool FC",
"link": "/en-us/match/chelsea-vs-liverpool/2043149"
},
{
"status": "played",
"time": "1446303600",
"id": "2043150",
"home": "Crystal Palace FC",
"score": ["0 ", " 0"],
"away": "Manchester United FC",
"link": "/en-us/match/crystal-palace-vs-manchester-united/2043150"
},
{
"status": "played",
"time": "1446303600",
"id": "2043151",
"home": "Manchester City FC",
"score": ["2 ", " 1"],
"away": "Norwich City FC",
"link": "/en-us/match/manchester-city-vs-norwich-city/2043151"
},
{
"status": "played",
"time": "1446303600",
"id": "2043152",
"home": "Newcastle United FC",
"score": ["0 ", " 0"],
"away": "Stoke City FC",
"link": "/en-us/match/newcastle-united-vs-stoke-city/2043152"
},
{
"status": "played",
"time": "1446303600",
"id": "2043145",
"home": "Swansea City AFC",
"score": ["0 ", " 3"],
"away": "Arsenal FC",
"link": "/en-us/match/swansea-city-vs-arsenal/2043145"
},
{
"status": "played",
"time": "1446303600",
"id": "2043154",
"home": "Watford FC",
"score": ["2 ", " 0"],
"away": "West Ham United FC",
"link": "/en-us/match/watford-vs-west-ham-united/2043154"
},
{
"status": "played",
"time": "1446303600",
"id": "2043148",
"home": "West Bromwich Albion FC",
"score": ["2 ", " 3"],
"away": "Leicester City FC",
"link": "/en-us/match/west-bromwich-albion-vs-leicester-city/2043148"
},
{
"status": "played",
"time": "1445781900",
"id": "2043142",
"home": "AFC Bournemouth",
"score": ["1 ", " 5"],
"away": "Tottenham Hotspur FC",
"link": "/en-us/match/afc-bournemouth-vs-tottenham-hotspur/2043142"
},
{
"status": "played",
"time": "1445789700",
"id": "2043140",
"home": "Liverpool FC",
"score": ["1 ", " 1"],
"away": "Southampton FC",
"link": "/en-us/match/liverpool-vs-southampton/2043140"
},
{
"status": "played",
"time": "1445781900",
"id": "2043138",
"home": "Manchester United FC",
"score": ["0 ", " 0"],
"away": "Manchester City FC",
"link": "/en-us/match/manchester-united-vs-manchester-city/2043138"
},
{
"status": "played",
"time": "1445774400",
"id": "2043139",
"home": "Sunderland AFC",
"score": ["3 ", " 0"],
"away": "Newcastle United FC",
"link": "/en-us/match/sunderland-vs-newcastle-united/2043139"
},
{
"status": "played",
"time": "1445704200",
"id": "2043137",
"home": "Arsenal FC",
"score": ["2 ", " 1"],
"away": "Everton FC",
"link": "/en-us/match/arsenal-vs-everton/2043137"
},
{
"status": "played",
"time": "1445695200",
"id": "2043141",
"home": "Aston Villa FC",
"score": ["1 ", " 2"],
"away": "Swansea City AFC",
"link": "/en-us/match/aston-villa-vs-swansea-city/2043141"
},
{
"status": "played",
"time": "1445695200",
"id": "2043136",
"home": "Leicester City FC",
"score": ["1 ", " 0"],
"away": "Crystal Palace FC",
"link": "/en-us/match/leicester-city-vs-crystal-palace/2043136"
},
{
"status": "played",
"time": "1445695200",
"id": "2043144",
"home": "Norwich City FC",
"score": ["0 ", " 1"],
"away": "West Bromwich Albion FC",
"link": "/en-us/match/norwich-city-vs-west-bromwich-albion/2043144"
},
{
"status": "played",
"time": "1445695200",
"id": "2043143",
"home": "Stoke City FC",
"score": ["0 ", " 2"],
"away": "Watford FC",
"link": "/en-us/match/stoke-city-vs-watford/2043143"
},
{
"status": "played",
"time": "1445695200",
"id": "2043135",
"home": "West Ham United FC",
"score": ["2 ", " 1"],
"away": "Chelsea FC",
"link": "/en-us/match/west-ham-united-vs-chelsea/2043135"
},
{
"status": "played",
"time": "1445281200",
"id": "2043132",
"home": "Swansea City AFC",
"score": ["0 ", " 1"],
"away": "Stoke City FC",
"link": "/en-us/match/swansea-city-vs-stoke-city/2043132"
},
{
"status": "played",
"time": "1445180400",
"id": "2043131",
"home": "Newcastle United FC",
"score": ["6 ", " 2"],
"away": "Norwich City FC",
"link": "/en-us/match/newcastle-united-vs-norwich-city/2043131"
},
{
"status": "played",
"time": "1445090400",
"id": "2043126",
"home": "Chelsea FC",
"score": ["2 ", " 0"],
"away": "Aston Villa FC",
"link": "/en-us/match/chelsea-vs-aston-villa/2043126"
},
{
"status": "played",
"time": "1445090400",
"id": "2043134",
"home": "Crystal Palace FC",
"score": ["1 ", " 3"],
"away": "West Ham United FC",
"link": "/en-us/match/crystal-palace-vs-west-ham-united/2043134"
},
{
"status": "played",
"time": "1445090400",
"id": "2043130",
"home": "Everton FC",
"score": ["0 ", " 3"],
"away": "Manchester United FC",
"link": "/en-us/match/everton-vs-manchester-united/2043130"
},
{
"status": "played",
"time": "1445090400",
"id": "2043127",
"home": "Manchester City FC",
"score": ["5 ", " 1"],
"away": "AFC Bournemouth",
"link": "/en-us/match/manchester-city-vs-afc-bournemouth/2043127"
},
{
"status": "played",
"time": "1445090400",
"id": "2043128",
"home": "Southampton FC",
"score": ["2 ", " 2"],
"away": "Leicester City FC",
"link": "/en-us/match/southampton-vs-leicester-city/2043128"
},
{
"status": "played",
"time": "1445082300",
"id": "2043129",
"home": "Tottenham Hotspur FC",
"score": ["0 ", " 0"],
"away": "Liverpool FC",
"link": "/en-us/match/tottenham-hotspur-vs-liverpool/2043129"
},
{
"status": "played",
"time": "1445099400",
"id": "2043125",
"home": "Watford FC",
"score": ["0 ", " 3"],
"away": "Arsenal FC",
"link": "/en-us/match/watford-vs-arsenal/2043125"
},
{
"status": "played",
"time": "1445090400",
"id": "2043133",
"home": "West Bromwich Albion FC",
"score": ["1 ", " 0"],
"away": "Sunderland AFC",
"link": "/en-us/match/west-bromwich-albion-vs-sunderland/2043133"
},
{
"status": "played",
"time": "1443970800",
"id": "2043117",
"home": "Arsenal FC",
"score": ["3 ", " 0"],
"away": "Manchester United FC",
"link": "/en-us/match/arsenal-vs-manchester-united/2043117"
},
{
"status": "played",
"time": "1443961800",
"id": "2043116",
"home": "Everton FC",
"score": ["1 ", " 1"],
"away": "Liverpool FC",
"link": "/en-us/match/everton-vs-liverpool/2043116"
},
{
"status": "played",
"time": "1443970800",
"id": "2043121",
"home": "Swansea City AFC",
"score": ["2 ", " 2"],
"away": "Tottenham Hotspur FC",
"link": "/en-us/match/swansea-city-vs-tottenham-hotspur/2043121"
},
{
"status": "played",
"time": "1443880800",
"id": "2043122",
"home": "AFC Bournemouth",
"score": ["1 ", " 1"],
"away": "Watford FC",
"link": "/en-us/match/afc-bournemouth-vs-watford/2043122"
},
{
"status": "played",
"time": "1443880800",
"id": "2043120",
"home": "Aston Villa FC",
"score": ["0 ", " 1"],
"away": "Stoke City FC",
"link": "/en-us/match/aston-villa-vs-stoke-city/2043120"
},
{
"status": "played",
"time": "1443889800",
"id": "2043119",
"home": "Chelsea FC",
"score": ["1 ", " 3"],
"away": "Southampton FC",
"link": "/en-us/match/chelsea-vs-southampton/2043119"
},
{
"status": "played",
"time": "1443872700",
"id": "2043123",
"home": "Crystal Palace FC",
"score": ["2 ", " 0"],
"away": "West Bromwich Albion FC",
"link": "/en-us/match/crystal-palace-vs-west-bromwich-albion/2043123"
},
{
"status": "played",
"time": "1443880800",
"id": "2043118",
"home": "Manchester City FC",
"score": ["6 ", " 1"],
"away": "Newcastle United FC",
"link": "/en-us/match/manchester-city-vs-newcastle-united/2043118"
},
{
"status": "played",
"time": "1443880800",
"id": "2043115",
"home": "Norwich City FC",
"score": ["1 ", " 2"],
"away": "Leicester City FC",
"link": "/en-us/match/norwich-city-vs-leicester-city/2043115"
},
{
"status": "played",
"time": "1443880800",
"id": "2043124",
"home": "Sunderland AFC",
"score": ["2 ", " 2"],
"away": "West Ham United FC",
"link": "/en-us/match/sunderland-vs-west-ham-united/2043124"
},
{
"status": "played",
"time": "1443466800",
"id": "2043110",
"home": "West Bromwich Albion FC",
"score": ["2 ", " 3"],
"away": "Everton FC",
"link": "/en-us/match/west-bromwich-albion-vs-everton/2043110"
},
{
"status": "played",
"time": "1443366000",
"id": "2043109",
"home": "Watford FC",
"score": ["0 ", " 1"],
"away": "Crystal Palace FC",
"link": "/en-us/match/watford-vs-crystal-palace/2043109"
},
{
"status": "played",
"time": "1443276000",
"id": "2043105",
"home": "Leicester City FC",
"score": ["2 ", " 5"],
"away": "Arsenal FC",
"link": "/en-us/match/leicester-city-vs-arsenal/2043105"
},
{
"status": "played",
"time": "1443276000",
"id": "2043106",
"home": "Liverpool FC",
"score": ["3 ", " 2"],
"away": "Aston Villa FC",
"link": "/en-us/match/liverpool-vs-aston-villa/2043106"
},
{
"status": "played",
"time": "1443276000",
"id": "2043113",
"home": "Manchester United FC",
"score": ["3 ", " 0"],
"away": "Sunderland AFC",
"link": "/en-us/match/manchester-united-vs-sunderland/2043113"
},
{
"status": "played",
"time": "1443285000",
"id": "2043108",
"home": "Newcastle United FC",
"score": ["2 ", " 2"],
"away": "Chelsea FC",
"link": "/en-us/match/newcastle-united-vs-chelsea/2043108"
},
{
"status": "played",
"time": "1443276000",
"id": "2043114",
"home": "Southampton FC",
"score": ["3 ", " 1"],
"away": "Swansea City AFC",
"link": "/en-us/match/southampton-vs-swansea-city/2043114"
},
{
"status": "played",
"time": "1443276000",
"id": "2043107",
"home": "Stoke City FC",
"score": ["2 ", " 1"],
"away": "AFC Bournemouth",
"link": "/en-us/match/stoke-city-vs-afc-bournemouth/2043107"
},
{
"status": "played",
"time": "1443267900",
"id": "2043111",
"home": "Tottenham Hotspur FC",
"score": ["4 ", " 1"],
"away": "Manchester City FC",
"link": "/en-us/match/tottenham-hotspur-vs-manchester-city/2043111"
},
{
"status": "played",
"time": "1443276000",
"id": "2043112",
"home": "West Ham United FC",
"score": ["2 ", " 2"],
"away": "Norwich City FC",
"link": "/en-us/match/west-ham-united-vs-norwich-city/2043112"
},
{
"status": "played",
"time": "1442761200",
"id": "2043100",
"home": "Liverpool FC",
"score": ["1 ", " 1"],
"away": "Norwich City FC",
"link": "/en-us/match/liverpool-vs-norwich-city/2043100"
},
{
"status": "played",
"time": "1442761200",
"id": "2043099",
"home": "Southampton FC",
"score": ["2 ", " 3"],
"away": "Manchester United FC",
"link": "/en-us/match/southampton-vs-manchester-united/2043099"
},
{
"status": "played",
"time": "1442752200",
"id": "2043096",
"home": "Tottenham Hotspur FC",
"score": ["1 ", " 0"],
"away": "Crystal Palace FC",
"link": "/en-us/match/tottenham-hotspur-vs-crystal-palace/2043096"
},
{
"status": "played",
"time": "1442671200",
"id": "2043101",
"home": "AFC Bournemouth",
"score": ["2 ", " 0"],
"away": "Sunderland AFC",
"link": "/en-us/match/afc-bournemouth-vs-sunderland/2043101"
},
{
"status": "played",
"time": "1442671200",
"id": "2043103",
"home": "Aston Villa FC",
"score": ["0 ", " 1"],
"away": "West Bromwich Albion FC",
"link": "/en-us/match/aston-villa-vs-west-bromwich-albion/2043103"
},
{
"status": "played",
"time": "1442663100",
"id": "2043095",
"home": "Chelsea FC",
"score": ["2 ", " 0"],
"away": "Arsenal FC",
"link": "/en-us/match/chelsea-vs-arsenal/2043095"
},
{
"status": "played",
"time": "1442680200",
"id": "2043104",
"home": "Manchester City FC",
"score": ["1 ", " 2"],
"away": "West Ham United FC",
"link": "/en-us/match/manchester-city-vs-west-ham-united/2043104"
},
{
"status": "played",
"time": "1442671200",
"id": "2043102",
"home": "Newcastle United FC",
"score": ["1 ", " 2"],
"away": "Watford FC",
"link": "/en-us/match/newcastle-united-vs-watford/2043102"
},
{
"status": "played",
"time": "1442671200",
"id": "2043098",
"home": "Stoke City FC",
"score": ["2 ", " 2"],
"away": "Leicester City FC",
"link": "/en-us/match/stoke-city-vs-leicester-city/2043098"
},
{
"status": "played",
"time": "1442671200",
"id": "2043097",
"home": "Swansea City AFC",
"score": ["0 ", " 0"],
"away": "Everton FC",
"link": "/en-us/match/swansea-city-vs-everton/2043097"
},
{
"status": "played",
"time": "1442257200",
"id": "2043090",
"home": "West Ham United FC",
"score": ["2 ", " 0"],
"away": "Newcastle United FC",
"link": "/en-us/match/west-ham-united-vs-newcastle-united/2043090"
},
{
"status": "played",
"time": "1442156400",
"id": "2043085",
"home": "Leicester City FC",
"score": ["3 ", " 2"],
"away": "Aston Villa FC",
"link": "/en-us/match/leicester-city-vs-aston-villa/2043085"
},
{
"status": "played",
"time": "1442147400",
"id": "2043094",
"home": "Sunderland AFC",
"score": ["0 ", " 1"],
"away": "Tottenham Hotspur FC",
"link": "/en-us/match/sunderland-vs-tottenham-hotspur/2043094"
},
{
"status": "played",
"time": "1442066400",
"id": "2043092",
"home": "Arsenal FC",
"score": ["2 ", " 0"],
"away": "Stoke City FC",
"link": "/en-us/match/arsenal-vs-stoke-city/2043092"
},
{
"status": "played",
"time": "1442066400",
"id": "2043089",
"home": "Crystal Palace FC",
"score": ["0 ", " 1"],
"away": "Manchester City FC",
"link": "/en-us/match/crystal-palace-vs-manchester-city/2043089"
},
{
"status": "played",
"time": "1442058300",
"id": "2043087",
"home": "Everton FC",
"score": ["3 ", " 1"],
"away": "Chelsea FC",
"link": "/en-us/match/everton-vs-chelsea/2043087"
},
{
"status": "played",
"time": "1442075400",
"id": "2043088",
"home": "Manchester United FC",
"score": ["3 ", " 1"],
"away": "Liverpool FC",
"link": "/en-us/match/manchester-united-vs-liverpool/2043088"
},
{
"status": "played",
"time": "1442066400",
"id": "2043086",
"home": "Norwich City FC",
"score": ["3 ", " 1"],
"away": "AFC Bournemouth",
"link": "/en-us/match/norwich-city-vs-afc-bournemouth/2043086"
},
{
"status": "played",
"time": "1442066400",
"id": "2043093",
"home": "Watford FC",
"score": ["1 ", " 0"],
"away": "Swansea City AFC",
"link": "/en-us/match/watford-vs-swansea-city/2043093"
},
{
"status": "played",
"time": "1442066400",
"id": "2043091",
"home": "West Bromwich Albion FC",
"score": ["0 ", " 0"],
"away": "Southampton FC",
"link": "/en-us/match/west-bromwich-albion-vs-southampton/2043091"
},
{
"status": "played",
"time": "1440937800",
"id": "2043080",
"home": "Southampton FC",
"score": ["3 ", " 0"],
"away": "Norwich City FC",
"link": "/en-us/match/southampton-vs-norwich-city/2043080"
},
{
"status": "played",
"time": "1440946800",
"id": "2043079",
"home": "Swansea City AFC",
"score": ["2 ", " 1"],
"away": "Manchester United FC",
"link": "/en-us/match/swansea-city-vs-manchester-united/2043079"
},
{
"status": "played",
"time": "1440856800",
"id": "2043078",
"home": "AFC Bournemouth",
"score": ["1 ", " 1"],
"away": "Leicester City FC",
"link": "/en-us/match/afc-bournemouth-vs-leicester-city/2043078"
},
{
"status": "played",
"time": "1440856800",
"id": "2043081",
"home": "Aston Villa FC",
"score": ["2 ", " 2"],
"away": "Sunderland AFC",
"link": "/en-us/match/aston-villa-vs-sunderland/2043081"
},
{
"status": "played",
"time": "1440856800",
"id": "2043076",
"home": "Chelsea FC",
"score": ["1 ", " 2"],
"away": "Crystal Palace FC",
"link": "/en-us/match/chelsea-vs-crystal-palace/2043076"
},
{
"status": "played",
"time": "1440856800",
"id": "2043084",
"home": "Liverpool FC",
"score": ["0 ", " 3"],
"away": "West Ham United FC",
"link": "/en-us/match/liverpool-vs-west-ham-united/2043084"
},
{
"status": "played",
"time": "1440856800",
"id": "2043082",
"home": "Manchester City FC",
"score": ["2 ", " 0"],
"away": "Watford FC",
"link": "/en-us/match/manchester-city-vs-watford/2043082"
},
{
"status": "played",
"time": "1440848700",
"id": "2043075",
"home": "Newcastle United FC",
"score": ["0 ", " 1"],
"away": "Arsenal FC",
"link": "/en-us/match/newcastle-united-vs-arsenal/2043075"
},
{
"status": "played",
"time": "1440856800",
"id": "2043083",
"home": "Stoke City FC",
"score": ["0 ", " 1"],
"away": "West Bromwich Albion FC",
"link": "/en-us/match/stoke-city-vs-west-bromwich-albion/2043083"
},
{
"status": "played",
"time": "1440865800",
"id": "2043077",
"home": "Tottenham Hotspur FC",
"score": ["0 ", " 0"],
"away": "Everton FC",
"link": "/en-us/match/tottenham-hotspur-vs-everton/2043077"
},
{
"status": "played",
"time": "1440442800",
"id": "2043068",
"home": "Arsenal FC",
"score": ["0 ", " 0"],
"away": "Liverpool FC",
"link": "/en-us/match/arsenal-vs-liverpool/2043068"
},
{
"status": "played",
"time": "1440342000",
"id": "2043069",
"home": "Everton FC",
"score": ["0 ", " 2"],
"away": "Manchester City FC",
"link": "/en-us/match/everton-vs-manchester-city/2043069"
},
{
"status": "played",
"time": "1440342000",
"id": "2043071",
"home": "Watford FC",
"score": ["0 ", " 0"],
"away": "Southampton FC",
"link": "/en-us/match/watford-vs-southampton/2043071"
},
{
"status": "played",
"time": "1440333000",
"id": "2043067",
"home": "West Bromwich Albion FC",
"score": ["2 ", " 3"],
"away": "Chelsea FC",
"link": "/en-us/match/west-bromwich-albion-vs-chelsea/2043067"
},
{
"status": "played",
"time": "1440252000",
"id": "2043065",
"home": "Crystal Palace FC",
"score": ["2 ", " 1"],
"away": "Aston Villa FC",
"link": "/en-us/match/crystal-palace-vs-aston-villa/2043065"
},
{
"status": "played",
"time": "1440252000",
"id": "2043074",
"home": "Leicester City FC",
"score": ["1 ", " 1"],
"away": "Tottenham Hotspur FC",
"link": "/en-us/match/leicester-city-vs-tottenham-hotspur/2043074"
},
{
"status": "played",
"time": "1440243900",
"id": "2043070",
"home": "Manchester United FC",
"score": ["0 ", " 0"],
"away": "Newcastle United FC",
"link": "/en-us/match/manchester-united-vs-newcastle-united/2043070"
},
{
"status": "played",
"time": "1440252000",
"id": "2043072",
"home": "Norwich City FC",
"score": ["1 ", " 1"],
"away": "Stoke City FC",
"link": "/en-us/match/norwich-city-vs-stoke-city/2043072"
},
{
"status": "played",
"time": "1440252000",
"id": "2043073",
"home": "Sunderland AFC",
"score": ["1 ", " 1"],
"away": "Swansea City AFC",
"link": "/en-us/match/sunderland-vs-swansea-city/2043073"
},
{
"status": "played",
"time": "1440252000",
"id": "2043066",
"home": "West Ham United FC",
"score": ["3 ", " 4"],
"away": "AFC Bournemouth",
"link": "/en-us/match/west-ham-united-vs-afc-bournemouth/2043066"
},
{
"status": "played",
"time": "1439838000",
"id": "2043056",
"home": "Liverpool FC",
"score": ["1 ", " 0"],
"away": "AFC Bournemouth",
"link": "/en-us/match/liverpool-vs-afc-bournemouth/2043056"
},
{
"status": "played",
"time": "1439728200",
"id": "2043055",
"home": "Crystal Palace FC",
"score": ["1 ", " 2"],
"away": "Arsenal FC",
"link": "/en-us/match/crystal-palace-vs-arsenal/2043055"
},
{
"status": "played",
"time": "1439737200",
"id": "2043057",
"home": "Manchester City FC",
"score": ["3 ", " 0"],
"away": "Chelsea FC",
"link": "/en-us/match/manchester-city-vs-chelsea/2043057"
},
{
"status": "played",
"time": "1439639100",
"id": "2043058",
"home": "Southampton FC",
"score": ["0 ", " 3"],
"away": "Everton FC",
"link": "/en-us/match/southampton-vs-everton/2043058"
},
{
"status": "played",
"time": "1439647200",
"id": "2043062",
"home": "Sunderland AFC",
"score": ["1 ", " 3"],
"away": "Norwich City FC",
"link": "/en-us/match/sunderland-vs-norwich-city/2043062"
},
{
"status": "played",
"time": "1439647200",
"id": "2043061",
"home": "Swansea City AFC",
"score": ["2 ", " 0"],
"away": "Newcastle United FC",
"link": "/en-us/match/swansea-city-vs-newcastle-united/2043061"
},
{
"status": "played",
"time": "1439647200",
"id": "2043063",
"home": "Tottenham Hotspur FC",
"score": ["2 ", " 2"],
"away": "Stoke City FC",
"link": "/en-us/match/tottenham-hotspur-vs-stoke-city/2043063"
},
{
"status": "played",
"time": "1439647200",
"id": "2043064",
"home": "Watford FC",
"score": ["0 ", " 0"],
"away": "West Bromwich Albion FC",
"link": "/en-us/match/watford-vs-west-bromwich-albion/2043064"
},
{
"status": "played",
"time": "1439647200",
"id": "2043059",
"home": "West Ham United FC",
"score": ["1 ", " 2"],
"away": "Leicester City FC",
"link": "/en-us/match/west-ham-united-vs-leicester-city/2043059"
},
{
"status": "played",
"time": "1439577900",
"id": "2043060",
"home": "Aston Villa FC",
"score": ["0 ", " 1"],
"away": "Manchester United FC",
"link": "/en-us/match/aston-villa-vs-manchester-united/2043060"
},
{
"status": "played",
"time": "1439233200",
"id": "2043048",
"home": "West Bromwich Albion FC",
"score": ["0 ", " 3"],
"away": "Manchester City FC",
"link": "/en-us/match/west-bromwich-albion-vs-manchester-city/2043048"
},
{
"status": "played",
"time": "1439123400",
"id": "2043054",
"home": "Arsenal FC",
"score": ["0 ", " 2"],
"away": "West Ham United FC",
"link": "/en-us/match/arsenal-vs-west-ham-united/2043054"
},
{
"status": "played",
"time": "1439123400",
"id": "2043049",
"home": "Newcastle United FC",
"score": ["2 ", " 2"],
"away": "Southampton FC",
"link": "/en-us/match/newcastle-united-vs-southampton/2043049"
},
{
"status": "played",
"time": "1439132400",
"id": "2043047",
"home": "Stoke City FC",
"score": ["0 ", " 1"],
"away": "Liverpool FC",
"link": "/en-us/match/stoke-city-vs-liverpool/2043047"
},
{
"status": "played",
"time": "1439042400",
"id": "2043045",
"home": "AFC Bournemouth",
"score": ["0 ", " 1"],
"away": "Aston Villa FC",
"link": "/en-us/match/afc-bournemouth-vs-aston-villa/2043045"
},
{
"status": "played",
"time": "1439051400",
"id": "2043051",
"home": "Chelsea FC",
"score": ["2 ", " 2"],
"away": "Swansea City AFC",
"link": "/en-us/match/chelsea-vs-swansea-city/2043051"
},
{
"status": "played",
"time": "1439042400",
"id": "2043053",
"home": "Everton FC",
"score": ["2 ", " 2"],
"away": "Watford FC",
"link": "/en-us/match/everton-vs-watford/2043053"
},
{
"status": "played",
"time": "1439042400",
"id": "2043050",
"home": "Leicester City FC",
"score": ["4 ", " 2"],
"away": "Sunderland AFC",
"link": "/en-us/match/leicester-city-vs-sunderland/2043050"
},
{
"status": "played",
"time": "1439034300",
"id": "2043052",
"home": "Manchester United FC",
"score": ["1 ", " 0"],
"away": "Tottenham Hotspur FC",
"link": "/en-us/match/manchester-united-vs-tottenham-hotspur/2043052"
},
{
"status": "played",
"time": "1439042400",
"id": "2043046",
"home": "Norwich City FC",
"score": ["1 ", " 3"],
"away": "Crystal Palace FC",
"link": "/en-us/match/norwich-city-vs-crystal-palace/2043046"
}
] | {
"pile_set_name": "Github"
} |
#ifdef USE_CUDNN
#include <vector>
#include "caffe/layers/cudnn_lrn_layer.hpp"
namespace caffe {
template <typename Dtype>
void CuDNNLRNLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
LRNLayer<Dtype>::LayerSetUp(bottom, top);
CUDNN_CHECK(cudnnCreate(&handle_));
CUDNN_CHECK(cudnnCreateLRNDescriptor(&norm_desc_));
cudnn::createTensor4dDesc<Dtype>(&bottom_desc_);
cudnn::createTensor4dDesc<Dtype>(&top_desc_);
// create a LRN handle
handles_setup_ = true;
size_ = this->layer_param().lrn_param().local_size();
alpha_ = this->layer_param().lrn_param().alpha();
beta_ = this->layer_param().lrn_param().beta();
k_ = this->layer_param().lrn_param().k();
}
template <typename Dtype>
void CuDNNLRNLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
LRNLayer<Dtype>::Reshape(bottom, top);
cudnn::setTensor4dDesc<Dtype>(&bottom_desc_, bottom[0]->num(),
this->channels_, this->height_, this->width_);
cudnn::setTensor4dDesc<Dtype>(&top_desc_, bottom[0]->num(),
this->channels_, this->height_, this->width_);
CUDNN_CHECK(cudnnSetLRNDescriptor(norm_desc_, size_, alpha_, beta_, k_));
}
template <typename Dtype>
CuDNNLRNLayer<Dtype>::~CuDNNLRNLayer() {
// Check that handles have been setup before destroying.
if (!handles_setup_) { return; }
cudnnDestroyTensorDescriptor(bottom_desc_);
cudnnDestroyTensorDescriptor(top_desc_);
// destroy LRN handle
cudnnDestroy(handle_);
}
INSTANTIATE_CLASS(CuDNNLRNLayer);
} // namespace caffe
#endif
| {
"pile_set_name": "Github"
} |
<div class="grid-layout layout-loose layout-full"><table>
<tr>
<td><div class="grid-layout layout-tighter"><table>
<tr>
<td width="50%" id="or-import-encoding"></td>
<td><input bind="encodingInput"></input></td>
</tr>
</table></div></td>
<td><div class="grid-layout layout-tighter layout-full"><table>
<tr>
<td style="text-align: right;"> </td>
<td width="1%"><button class="button" bind="previewButton"></button></td>
</tr>
</table></div></td>
</tr>
<tr>
<td><div class="grid-layout layout-tightest"><table>
<tr><td colspan="2"><span id="or-import-parseEvery"></span> <input bind="linesPerRowInput" type="text" class="lightweight" size="2" value="0" />
<span id="or-import-linesIntoRow"></span>
</td></tr>
<tr><td width="1%"><input type="checkbox" bind="storeBlankRowsCheckbox" id="$store-blank-rows" /></td>
<td colspan="2"><label for="$store-blank-rows" id="or-import-blank"></label></td></tr>
<tr><td width="1%"><input type="checkbox" bind="storeBlankCellsAsNullsCheckbox" id="$store-blank-cells" /></td>
<td colspan="2"><label for="$store-blank-cells" id="or-import-null"></label></td></tr>
<tr><td width="1%"><input type="checkbox" bind="includeFileSourcesCheckbox" id="$include-file-sources" /></td>
<td><label for="$include-file-sources" id="or-import-source"></label></td></tr>
<tr><td width="1%"><input type="checkbox" bind="includeArchiveFileCheckbox" id="$include-archive-file" /></td>
<td><label for="$include-archive-file" id="or-import-archive"></label></td></tr>
</table></div></td>
<td><div class="grid-layout layout-tightest"><table>
<tr><td width="1%"><input type="checkbox" bind="ignoreCheckbox" id="$ignore" /></td>
<td><label for="$ignore" id="or-import-ignore"></label></td>
<td><input bind="ignoreInput" type="text" class="lightweight" size="2" value="0" />
<label for="$ignore" id="or-import-lines"></label></td></tr>
<tr><td width="1%"><input type="checkbox" bind="skipCheckbox" id="$skip" /></td>
<td><label for="$skip" id="or-import-discard"></label></td>
<td><input bind="skipInput" type="text" class="lightweight" size="2" value="0" />
<label for="$skip" id="or-import-rows"></label></td></tr>
<tr><td width="1%"><input type="checkbox" bind="limitCheckbox" id="$limit" /></td>
<td><label for="$limit" id="or-import-load"></label></td>
<td><input bind="limitInput" type="text" class="lightweight" size="2" value="0" />
<label for="$limit" id="or-import-rows2"></label></td></tr>
</table></div></td>
</tr>
</table></div> | {
"pile_set_name": "Github"
} |
Dummy::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Do not compress assets
config.assets.compress = false if config.respond_to?(:assets)
end
| {
"pile_set_name": "Github"
} |
#pragma once
#ifndef RAZ_WINDOW_HPP
#define RAZ_WINDOW_HPP
#include "RaZ/Math/Vector.hpp"
#include "RaZ/Utils/Image.hpp"
#include "RaZ/Utils/Overlay.hpp"
#include "RaZ/Utils/Input.hpp"
#include <functional>
#include <vector>
namespace Raz {
class Window;
using WindowPtr = std::unique_ptr<Window>;
using KeyboardCallbacks = std::vector<std::tuple<int, std::function<void(float)>, Input::ActionTrigger, std::function<void()>>>;
using MouseButtonCallbacks = std::vector<std::tuple<int, std::function<void(float)>, Input::ActionTrigger, std::function<void()>>>;
using MouseScrollCallback = std::function<void(double, double)>;
using MouseMoveCallback = std::tuple<double, double, std::function<void(double, double)>>;
using InputActions = std::unordered_map<int, std::pair<std::function<void(float)>, Input::ActionTrigger>>;
using InputCallbacks = std::tuple<KeyboardCallbacks, MouseButtonCallbacks, MouseScrollCallback, MouseMoveCallback, InputActions>;
/// Graphical window to render the scenes on, with input custom actions.
class Window {
public:
Window(unsigned int width, unsigned int height, const std::string& title = "", uint8_t antiAliasingSampleCount = 1);
Window(const Window&) = delete;
Window(Window&&) noexcept = default;
unsigned int getWidth() const { return m_width; }
unsigned int getHeight() const { return m_height; }
const Vec4f& getClearColor() const { return m_clearColor; }
const InputCallbacks& getCallbacks() const { return m_callbacks; }
InputCallbacks& getCallbacks() { return m_callbacks; }
void setClearColor(const Vec4f& clearColor) { m_clearColor = clearColor; }
void setClearColor(float red, float green, float blue, float alpha = 1.f) { setClearColor(Vec4f(red, green, blue, alpha)); }
void setTitle(const std::string& title) const;
void setIcon(const Image& img) const;
void setIcon(const FilePath& filePath) const { setIcon(Image(filePath, false)); }
template <typename... Args>
static WindowPtr create(Args&&... args) { return std::make_unique<Window>(std::forward<Args>(args)...); }
/// Resizes the window.
/// \param width New window width.
/// \param height New window height.
void resize(unsigned int width, unsigned int height);
/// Changes the face culling's state.
/// Enables or disables face culling according to the given parameter.
/// \param value Value to apply.
void enableFaceCulling(bool value = true) const;
/// Disables the face culling.
void disableFaceCulling() const { enableFaceCulling(false); }
/// Fetches the current vertical synchronization's state.
/// \return True if vertical sync is enabled, false otherwise.
bool recoverVerticalSyncState() const;
/// Changes the vertical synchronization's state.
/// Enables or disables vertical sync according to the given parameter.
/// \param value Value to apply.
void enableVerticalSync(bool value = true) const;
/// Disables vertical synchronization.
void disableVerticalSync() const { enableVerticalSync(false); }
/// Changes the cursor's state.
/// Defines the new behavior of the mouse's cursor, if it should be shown, hidden or disabled.
/// The functions showCursor(), hideCursor() & disableCursor() can be used instead.
/// \param state State to apply.
void changeCursorState(Cursor::State state) const;
/// Shows the mouse cursor.
/// Default behavior.
void showCursor() const { changeCursorState(Cursor::State::NORMAL); }
/// Hides the mouse cursor.
/// The cursor becomes invisible while being inside the window's frame. It can go out of the window.
void hideCursor() const { changeCursorState(Cursor::State::HIDDEN); }
/// Disables the mouse cursor.
/// The cursor always goes back to the window's center and becomes totally invisible. It can't go out of the window.
void disableCursor() const { changeCursorState(Cursor::State::DISABLED); }
/// Defines an action on keyboard's key press & release.
/// \param key Key triggering the given action(s).
/// \param actionPress Action to be executed when the given key is pressed.
/// \param frequency Frequency at which to execute the actions.
/// \param actionRelease Action to be executed when the given key is released.
void addKeyCallback(Keyboard::Key key, std::function<void(float)> actionPress,
Input::ActionTrigger frequency = Input::ALWAYS,
std::function<void()> actionRelease = nullptr);
/// Defines an action on mouse button click or release.
/// \param button Button triggering the given action(s).
/// \param actionPress Action to be executed when the given mouse button is pressed.
/// \param frequency Frequency at which to execute the actions.
/// \param actionRelease Action to be executed when the given mouse button is released.
void addMouseButtonCallback(Mouse::Button button, std::function<void(float)> actionPress,
Input::ActionTrigger frequency = Input::ALWAYS,
std::function<void()> actionRelease = nullptr);
/// Defines an action on mouse wheel scroll.
/// \param func Action to be executed when scrolling.
void addMouseScrollCallback(std::function<void(double, double)> func);
/// Defines an action on mouse move.
/// \param func Action to be executed when the mouse is moved.
void addMouseMoveCallback(std::function<void(double, double)> func);
/// Associates all of the callbacks, making them active.
void updateCallbacks() const;
#if defined(RAZ_USE_OVERLAY)
/// Enables the overlay.
void enableOverlay() { m_overlay = Overlay::create(m_window); }
/// Disables the overlay.
void disableOverlay() { m_overlay.reset(); }
/// Adds a label on the overlay.
/// \param label Text to be displayed.
void addOverlayLabel(std::string label);
/// Adds a button on the overlay.
/// \param label Text to be displayed beside the button.
/// \param action Action to be executed when clicked.
void addOverlayButton(std::string label, std::function<void()> action);
/// Adds a checkbox on the overlay.
/// \param label Text to be displayed beside the checkbox.
/// \param actionOn Action to be executed when toggled on.
/// \param actionOff Action to be executed when toggled off.
/// \param initVal Initial value, checked or not.
void addOverlayCheckbox(std::string label, std::function<void()> actionOn, std::function<void()> actionOff, bool initVal);
/// Adds a floating-point slider on the overlay.
/// \param label Text to be displayed beside the slider.
/// \param actionSlide Action to be executed on a value change.
/// \param minValue Lower value bound.
/// \param maxValue Upper value bound.
void addOverlaySlider(std::string label, std::function<void(float)> actionSlide, float minValue, float maxValue);
/// Adds a texbox on the overlay.
/// \param label Text to be displayed beside the checkbox.
/// \param callback Function to be called every time the content is modified.
void addOverlayTextbox(std::string label, std::function<void(const std::string&)> callback);
/// Adds a texture on the overlay.
/// \param texture Texture to be displayed.
/// \param maxWidth Maximum texture's width.
/// \param maxHeight Maximum texture's height.
void addOverlayTexture(const Texture& texture, unsigned int maxWidth, unsigned int maxHeight);
/// Adds a texture on the overlay. The maximum width & height will be those of the texture.
/// \param texture Texture to be displayed.
void addOverlayTexture(const Texture& texture);
/// Adds an horizontal separator on the overlay.
void addOverlaySeparator();
/// Adds a frame time display on the overlay.
/// \param formattedLabel Text with a formatting placeholder to display the frame time (%.Xf, X being the precision after the comma).
void addOverlayFrameTime(std::string formattedLabel);
/// Adds a FPS (frames per second) counter on the overlay.
/// \param formattedLabel Text with a formatting placeholder to display the FPS (%.Xf, X being the precision after the comma).
void addOverlayFpsCounter(std::string formattedLabel);
#endif
/// Runs the window, refreshing its state by displaying the rendered scene, drawing the overlay, etc.
/// \param deltaTime Amount of time elapsed since the last frame.
/// \return True if the window hasn't been required to close, false otherwise.
bool run(float deltaTime);
/// Fetches the mouse position onto the window.
/// \return 2D vector representing the mouse's position relative to the window.
Vec2f recoverMousePosition() const;
/// Tells the window that it should close.
void setShouldClose() const;
/// Closes the window.
void close();
Window& operator=(const Window&) = delete;
Window& operator=(Window&&) noexcept = default;
~Window() { close(); }
private:
unsigned int m_width {};
unsigned int m_height {};
Vec4f m_clearColor = Vec4f(0.15f, 0.15f, 0.15f, 1.f);
GLFWwindow* m_window {};
InputCallbacks m_callbacks {};
#if defined(RAZ_USE_OVERLAY)
OverlayPtr m_overlay {};
#endif
};
} // namespace Raz
#endif // RAZ_WINDOW_HPP
| {
"pile_set_name": "Github"
} |
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M6.5 2c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm9 7.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5S17.83 8 17 8s-1.5.67-1.5 1.5zm3 2.5h-2.84c-.58.01-1.14.32-1.45.86l-.92 1.32L9.72 8c-.37-.63-1.03-.99-1.71-1H5c-1.1 0-2 .9-2 2v5c0 .55.45 1 1 1h.5v6c0 .55.45 1 1 1h3c.55 0 1-.45 1-1v-9.39l2.24 3.89c.18.31.51.5.87.5h1.1c.33 0 .63-.16.82-.43l.47-.67V21c0 .55.45 1 1 1h2c.55 0 1-.45 1-1v-4c.55 0 1-.45 1-1v-2.5c0-.82-.67-1.5-1.5-1.5z" />
, 'EscalatorWarningRounded');
| {
"pile_set_name": "Github"
} |
import titleize from 'utils/titleize'
describe('Titleizes strings', () => {
it('Capitalizes first words of the sentence', () => {
const brokenCase = 'cApiTAlS hErE, LoweRcaseS There'
const brokenCaseTitleized = 'Capitals Here, Lowercases There'
expect(titleize(brokenCase)).toEqual(brokenCaseTitleized)
})
it('Converts underscores into spaces', () => {
const underscoreString = 'Pending_Run_Success'
const underscoreStringTitleized = 'Pending Run Success'
expect(titleize(underscoreString)).toEqual(underscoreStringTitleized)
})
it('Capitalizes first words and converts underscores into spaces', () => {
const brokenCaseWithUnderscores = 'job_error_now'
const brokenCaseWithUnderscoresCorrect = 'Job Error Now'
expect(titleize(brokenCaseWithUnderscores)).toEqual(
brokenCaseWithUnderscoresCorrect,
)
})
})
| {
"pile_set_name": "Github"
} |
#!/bin/sh
exec %%LOCALBASE%%/lib/erlang/lib/%%PORTNAME%%-%%PORTVERSION%%/bin/protoc-erl "$@"
| {
"pile_set_name": "Github"
} |
extern crate pushrod;
extern crate sdl2;
use pushrod::render::engine::Engine;
use pushrod::render::widget::{BaseWidget, Widget};
use pushrod::render::widget_config::{CONFIG_BORDER_WIDTH, CONFIG_COLOR_BASE, CONFIG_COLOR_BORDER};
use pushrod::render::{make_points, make_size};
use sdl2::messagebox::*;
use sdl2::pixels::Color;
/*
* This demo just tests the rendering functionality of the `BaseWidget`. It only tests the
* render portion of the library, nothing else.
*/
pub fn main() {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem
.window("pushrod-render exit demo", 800, 600)
.position_centered()
.opengl()
.build()
.unwrap();
let mut engine = Engine::new(800, 600, 30);
let mut new_base_widget = BaseWidget::new(make_points(100, 100), make_size(600, 400));
new_base_widget
.get_config()
.set_color(CONFIG_COLOR_BORDER, Color::RGB(0, 0, 0));
new_base_widget
.get_config()
.set_numeric(CONFIG_BORDER_WIDTH, 2);
new_base_widget
.get_callbacks()
.on_mouse_entered(|x, _widgets, _layouts| {
x.get_config()
.set_color(CONFIG_COLOR_BASE, Color::RGB(255, 0, 0));
x.get_config().set_invalidated(true);
_widgets[0]
.widget
.borrow_mut()
.get_config()
.set_invalidated(true);
eprintln!("Mouse Entered");
});
new_base_widget
.get_callbacks()
.on_mouse_exited(|x, _widgets, _layouts| {
x.get_config()
.set_color(CONFIG_COLOR_BASE, Color::RGB(255, 255, 255));
x.get_config().set_invalidated(true);
_widgets[0]
.widget
.borrow_mut()
.get_config()
.set_invalidated(true);
eprintln!("Mouse Exited");
});
new_base_widget
.get_callbacks()
.on_mouse_moved(|_widget, _widgets, _layouts, points| {
eprintln!("Mouse Moved: {:?}", points);
});
new_base_widget
.get_callbacks()
.on_mouse_scrolled(|_widget, _widgets, _layouts, points| {
eprintln!("Mouse Scrolled: {:?}", points);
});
new_base_widget.get_callbacks().on_mouse_clicked(
|_widget, _widgets, _layouts, button, clicks, state| {
eprintln!(
"Mouse Clicked: button={} clicks={} state={}",
button, clicks, state
);
},
);
engine.add_widget(Box::new(new_base_widget), String::from("widget1"));
engine.on_exit(|engine| {
let buttons: Vec<_> = vec![
ButtonData {
flags: MessageBoxButtonFlag::RETURNKEY_DEFAULT,
button_id: 1,
text: "Yes",
},
ButtonData {
flags: MessageBoxButtonFlag::ESCAPEKEY_DEFAULT,
button_id: 2,
text: "No",
},
];
let res = show_message_box(
MessageBoxFlag::WARNING,
buttons.as_slice(),
"Quit",
"Are you sure?",
None,
None,
)
.unwrap();
if let ClickedButton::CustomButton(x) = res {
if x.button_id == 1 {
return true;
}
}
false
});
engine.run(sdl_context, window);
}
| {
"pile_set_name": "Github"
} |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pinot.common.metrics;
import org.apache.pinot.common.Utils;
/**
* Enumeration containing all the timers exposed by the Pinot controller.
*
*/
public enum ControllerTimer implements AbstractMetrics.Timer {
;
private final String timerName;
private final boolean global;
ControllerTimer(String unit, boolean global) {
this.global = global;
this.timerName = Utils.toCamelCase(name().toLowerCase());
}
@Override
public String getTimerName() {
return timerName;
}
/**
* Returns true if the timer is global (not attached to a particular resource)
*
* @return true if the timer is global
*/
@Override
public boolean isGlobal() {
return global;
}
}
| {
"pile_set_name": "Github"
} |
// Package : omnithread
// omnithread/nt.cc Created : 6/95 tjr
//
// Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
//
// This file is part of the omnithread library
//
// The omnithread library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free
// Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA
//
//
// Implementation of OMNI thread abstraction for NT threads
//
#include <stdlib.h>
#include <errno.h>
#include "omnithread.h"
#include <process.h>
#define DB(x) // x
//#include <iostream.h> or #include <iostream> if DB is on.
static void get_time_now(unsigned long* abs_sec, unsigned long* abs_nsec);
///////////////////////////////////////////////////////////////////////////
//
// Mutex
//
///////////////////////////////////////////////////////////////////////////
omni_mutex::omni_mutex(void)
{
InitializeCriticalSection(&crit);
}
omni_mutex::~omni_mutex(void)
{
DeleteCriticalSection(&crit);
}
void
omni_mutex::lock(void)
{
EnterCriticalSection(&crit);
}
void
omni_mutex::unlock(void)
{
LeaveCriticalSection(&crit);
}
///////////////////////////////////////////////////////////////////////////
//
// Condition variable
//
///////////////////////////////////////////////////////////////////////////
//
// Condition variables are tricky to implement using NT synchronisation
// primitives, since none of them have the atomic "release mutex and wait to be
// signalled" which is central to the idea of a condition variable. To get
// around this the solution is to record which threads are waiting and
// explicitly wake up those threads.
//
// Here we implement a condition variable using a list of waiting threads
// (protected by a critical section), and a per-thread semaphore (which
// actually only needs to be a binary semaphore).
//
// To wait on the cv, a thread puts itself on the list of waiting threads for
// that cv, then releases the mutex and waits on its own personal semaphore. A
// signalling thread simply takes a thread from the head of the list and kicks
// that thread's semaphore. Broadcast is simply implemented by kicking the
// semaphore of each waiting thread.
//
// The only other tricky part comes when a thread gets a timeout from a timed
// wait on its semaphore. Between returning with a timeout from the wait and
// entering the critical section, a signalling thread could get in, kick the
// waiting thread's semaphore and remove it from the list. If this happens,
// the waiting thread's semaphore is now out of step so it needs resetting, and
// the thread should indicate that it was signalled rather than that it timed
// out.
//
// It is possible that the thread calling wait or timedwait is not a
// omni_thread. In this case we have to provide a temporary data structure,
// i.e. for the duration of the call, for the thread to link itself on the
// list of waiting threads. _internal_omni_thread_dummy provides such
// a data structure and _internal_omni_thread_helper is a helper class to
// deal with this special case for wait() and timedwait(). Once created,
// the _internal_omni_thread_dummy is cached for use by the next wait() or
// timedwait() call from a non-omni_thread. This is probably worth doing
// because creating a Semaphore is quite heavy weight.
class _internal_omni_thread_helper;
class _internal_omni_thread_dummy : public omni_thread {
public:
inline _internal_omni_thread_dummy() : next(0) { }
inline ~_internal_omni_thread_dummy() { }
friend class _internal_omni_thread_helper;
private:
_internal_omni_thread_dummy* next;
};
class _internal_omni_thread_helper {
public:
inline _internal_omni_thread_helper() {
d = 0;
t = omni_thread::self();
if (!t) {
omni_mutex_lock sync(cachelock);
if (cache) {
d = cache;
cache = cache->next;
}
else {
d = new _internal_omni_thread_dummy;
}
t = d;
}
}
inline ~_internal_omni_thread_helper() {
if (d) {
omni_mutex_lock sync(cachelock);
d->next = cache;
cache = d;
}
}
inline operator omni_thread* () { return t; }
inline omni_thread* operator->() { return t; }
static _internal_omni_thread_dummy* cache;
static omni_mutex cachelock;
private:
_internal_omni_thread_dummy* d;
omni_thread* t;
};
_internal_omni_thread_dummy* _internal_omni_thread_helper::cache = 0;
omni_mutex _internal_omni_thread_helper::cachelock;
omni_condition::omni_condition(omni_mutex* m) : mutex(m)
{
InitializeCriticalSection(&crit);
waiting_head = waiting_tail = NULL;
}
omni_condition::~omni_condition(void)
{
DeleteCriticalSection(&crit);
DB( if (waiting_head != NULL) {
cerr << "omni_condition::~omni_condition: list of waiting threads "
<< "is not empty\n";
} )
}
void
omni_condition::wait(void)
{
_internal_omni_thread_helper me;
EnterCriticalSection(&crit);
me->cond_next = NULL;
me->cond_prev = waiting_tail;
if (waiting_head == NULL)
waiting_head = me;
else
waiting_tail->cond_next = me;
waiting_tail = me;
me->cond_waiting = TRUE;
LeaveCriticalSection(&crit);
mutex->unlock();
DWORD result = WaitForSingleObject(me->cond_semaphore, INFINITE);
mutex->lock();
if (result != WAIT_OBJECT_0)
throw omni_thread_fatal(GetLastError());
}
int
omni_condition::timedwait(unsigned long abs_sec, unsigned long abs_nsec)
{
_internal_omni_thread_helper me;
EnterCriticalSection(&crit);
me->cond_next = NULL;
me->cond_prev = waiting_tail;
if (waiting_head == NULL)
waiting_head = me;
else
waiting_tail->cond_next = me;
waiting_tail = me;
me->cond_waiting = TRUE;
LeaveCriticalSection(&crit);
mutex->unlock();
unsigned long now_sec, now_nsec;
get_time_now(&now_sec, &now_nsec);
DWORD timeout = (abs_sec-now_sec) * 1000 + (abs_nsec-now_nsec) / 1000000;
if ((abs_sec <= now_sec) && ((abs_sec < now_sec) || (abs_nsec < abs_nsec)))
timeout = 0;
DWORD result = WaitForSingleObject(me->cond_semaphore, timeout);
if (result == WAIT_TIMEOUT) {
EnterCriticalSection(&crit);
if (me->cond_waiting) {
if (me->cond_prev != NULL)
me->cond_prev->cond_next = me->cond_next;
else
waiting_head = me->cond_next;
if (me->cond_next != NULL)
me->cond_next->cond_prev = me->cond_prev;
else
waiting_tail = me->cond_prev;
me->cond_waiting = FALSE;
LeaveCriticalSection(&crit);
mutex->lock();
return 0;
}
//
// We timed out but another thread still signalled us. Wait for
// the semaphore (it _must_ have been signalled) to decrement it
// again. Return that we were signalled, not that we timed out.
//
LeaveCriticalSection(&crit);
result = WaitForSingleObject(me->cond_semaphore, INFINITE);
}
if (result != WAIT_OBJECT_0)
throw omni_thread_fatal(GetLastError());
mutex->lock();
return 1;
}
void
omni_condition::signal(void)
{
EnterCriticalSection(&crit);
if (waiting_head != NULL) {
omni_thread* t = waiting_head;
waiting_head = t->cond_next;
if (waiting_head == NULL)
waiting_tail = NULL;
else
waiting_head->cond_prev = NULL;
t->cond_waiting = FALSE;
if (!ReleaseSemaphore(t->cond_semaphore, 1, NULL)) {
int rc = GetLastError();
LeaveCriticalSection(&crit);
throw omni_thread_fatal(rc);
}
}
LeaveCriticalSection(&crit);
}
void
omni_condition::broadcast(void)
{
EnterCriticalSection(&crit);
while (waiting_head != NULL) {
omni_thread* t = waiting_head;
waiting_head = t->cond_next;
if (waiting_head == NULL)
waiting_tail = NULL;
else
waiting_head->cond_prev = NULL;
t->cond_waiting = FALSE;
if (!ReleaseSemaphore(t->cond_semaphore, 1, NULL)) {
int rc = GetLastError();
LeaveCriticalSection(&crit);
throw omni_thread_fatal(rc);
}
}
LeaveCriticalSection(&crit);
}
///////////////////////////////////////////////////////////////////////////
//
// Counting semaphore
//
///////////////////////////////////////////////////////////////////////////
#define SEMAPHORE_MAX 0x7fffffff
omni_semaphore::omni_semaphore(unsigned int initial)
{
nt_sem = CreateSemaphore(NULL, initial, SEMAPHORE_MAX, NULL);
if (nt_sem == NULL) {
DB( cerr << "omni_semaphore::omni_semaphore: CreateSemaphore error "
<< GetLastError() << endl );
throw omni_thread_fatal(GetLastError());
}
}
omni_semaphore::~omni_semaphore(void)
{
if (!CloseHandle(nt_sem)) {
DB( cerr << "omni_semaphore::~omni_semaphore: CloseHandle error "
<< GetLastError() << endl );
throw omni_thread_fatal(GetLastError());
}
}
void
omni_semaphore::wait(void)
{
if (WaitForSingleObject(nt_sem, INFINITE) != WAIT_OBJECT_0)
throw omni_thread_fatal(GetLastError());
}
int
omni_semaphore::trywait(void)
{
switch (WaitForSingleObject(nt_sem, 0)) {
case WAIT_OBJECT_0:
return 1;
case WAIT_TIMEOUT:
return 0;
}
throw omni_thread_fatal(GetLastError());
return 0; /* keep msvc++ happy */
}
void
omni_semaphore::post(void)
{
if (!ReleaseSemaphore(nt_sem, 1, NULL))
throw omni_thread_fatal(GetLastError());
}
///////////////////////////////////////////////////////////////////////////
//
// Thread
//
///////////////////////////////////////////////////////////////////////////
//
// Static variables
//
int omni_thread::init_t::count = 0;
omni_mutex* omni_thread::next_id_mutex;
int omni_thread::next_id = 0;
static DWORD self_tls_index;
//
// Initialisation function (gets called before any user code).
//
omni_thread::init_t::init_t(void)
{
if (count++ != 0) // only do it once however many objects get created.
return;
DB(cerr << "omni_thread::init: NT implementation initialising\n");
self_tls_index = TlsAlloc();
if (self_tls_index == 0xffffffff)
throw omni_thread_fatal(GetLastError());
next_id_mutex = new omni_mutex;
//
// Create object for this (i.e. initial) thread.
//
omni_thread* t = new omni_thread;
t->_state = STATE_RUNNING;
if (!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
GetCurrentProcess(), &t->handle,
0, FALSE, DUPLICATE_SAME_ACCESS))
throw omni_thread_fatal(GetLastError());
t->nt_id = GetCurrentThreadId();
DB(cerr << "initial thread " << t->id() << " NT thread id " << t->nt_id
<< endl);
if (!TlsSetValue(self_tls_index, (LPVOID)t))
throw omni_thread_fatal(GetLastError());
if (!SetThreadPriority(t->handle, nt_priority(PRIORITY_NORMAL)))
throw omni_thread_fatal(GetLastError());
}
//
// Wrapper for thread creation.
//
extern "C"
unsigned __stdcall
omni_thread_wrapper(void* ptr)
{
omni_thread* me = (omni_thread*)ptr;
DB(cerr << "omni_thread_wrapper: thread " << me->id()
<< " started\n");
TlsSetValue(self_tls_index, (LPVOID)me);
//if (!TlsSetValue(self_tls_index, (LPVOID)me))
// throw omni_thread_fatal(GetLastError());
//
// Now invoke the thread function with the given argument.
//
if (me->fn_void != NULL) {
(*me->fn_void)(me->thread_arg);
omni_thread::exit();
}
if (me->fn_ret != NULL) {
void* return_value = (*me->fn_ret)(me->thread_arg);
omni_thread::exit(return_value);
}
if (me->detached) {
me->run(me->thread_arg);
omni_thread::exit();
} else {
void* return_value = me->run_undetached(me->thread_arg);
omni_thread::exit(return_value);
}
// should never get here.
return 0;
}
//
// Constructors for omni_thread - set up the thread object but don't
// start it running.
//
// construct a detached thread running a given function.
omni_thread::omni_thread(void (*fn)(void*), void* arg, priority_t pri)
{
common_constructor(arg, pri, 1);
fn_void = fn;
fn_ret = NULL;
}
// construct an undetached thread running a given function.
omni_thread::omni_thread(void* (*fn)(void*), void* arg, priority_t pri)
{
common_constructor(arg, pri, 0);
fn_void = NULL;
fn_ret = fn;
}
// construct a thread which will run either run() or run_undetached().
omni_thread::omni_thread(void* arg, priority_t pri)
{
common_constructor(arg, pri, 1);
fn_void = NULL;
fn_ret = NULL;
}
// common part of all constructors.
void
omni_thread::common_constructor(void* arg, priority_t pri, int det)
{
_state = STATE_NEW;
_priority = pri;
next_id_mutex->lock();
_id = next_id++;
next_id_mutex->unlock();
thread_arg = arg;
detached = det; // may be altered in start_undetached()
cond_semaphore = CreateSemaphore(NULL, 0, SEMAPHORE_MAX, NULL);
if (cond_semaphore == NULL)
throw omni_thread_fatal(GetLastError());
cond_next = cond_prev = NULL;
cond_waiting = FALSE;
handle = NULL;
}
//
// Destructor for omni_thread.
//
omni_thread::~omni_thread(void)
{
DB(cerr << "destructor called for thread " << id() << endl);
if ((handle != NULL) && !CloseHandle(handle))
throw omni_thread_fatal(GetLastError());
if (!CloseHandle(cond_semaphore))
throw omni_thread_fatal(GetLastError());
}
//
// Start the thread
//
void
omni_thread::start(void)
{
omni_mutex_lock l(mutex);
if (_state != STATE_NEW)
throw omni_thread_invalid();
unsigned int t;
handle = (HANDLE)_beginthreadex(
NULL,
0,
omni_thread_wrapper,
(LPVOID)this,
CREATE_SUSPENDED,
&t);
nt_id = t;
if (handle == NULL)
throw omni_thread_fatal(GetLastError());
if (!SetThreadPriority(handle, _priority))
throw omni_thread_fatal(GetLastError());
if (ResumeThread(handle) == 0xffffffff)
throw omni_thread_fatal(GetLastError());
_state = STATE_RUNNING;
}
//
// Start a thread which will run the member function run_undetached().
//
void
omni_thread::start_undetached(void)
{
if ((fn_void != NULL) || (fn_ret != NULL))
throw omni_thread_invalid();
detached = 0;
start();
}
//
// join - simply check error conditions & call WaitForSingleObject.
//
void
omni_thread::join(void** status)
{
mutex.lock();
if ((_state != STATE_RUNNING) && (_state != STATE_TERMINATED)) {
mutex.unlock();
throw omni_thread_invalid();
}
mutex.unlock();
if (this == self())
throw omni_thread_invalid();
if (detached)
throw omni_thread_invalid();
DB(cerr << "omni_thread::join: doing WaitForSingleObject\n");
if (WaitForSingleObject(handle, INFINITE) != WAIT_OBJECT_0)
throw omni_thread_fatal(GetLastError());
DB(cerr << "omni_thread::join: WaitForSingleObject succeeded\n");
if (status)
*status = return_val;
delete this;
}
//
// Change this thread's priority.
//
void
omni_thread::set_priority(priority_t pri)
{
omni_mutex_lock l(mutex);
if (_state != STATE_RUNNING)
throw omni_thread_invalid();
_priority = pri;
if (!SetThreadPriority(handle, nt_priority(pri)))
throw omni_thread_fatal(GetLastError());
}
//
// create - construct a new thread object and start it running. Returns thread
// object if successful, null pointer if not.
//
// detached version
omni_thread*
omni_thread::create(void (*fn)(void*), void* arg, priority_t pri)
{
omni_thread* t = new omni_thread(fn, arg, pri);
t->start();
return t;
}
// undetached version
omni_thread*
omni_thread::create(void* (*fn)(void*), void* arg, priority_t pri)
{
omni_thread* t = new omni_thread(fn, arg, pri);
t->start();
return t;
}
//
// exit() _must_ lock the mutex even in the case of a detached thread. This is
// because a thread may run to completion before the thread that created it has
// had a chance to get out of start(). By locking the mutex we ensure that the
// creating thread must have reached the end of start() before we delete the
// thread object. Of course, once the call to start() returns, the user can
// still incorrectly refer to the thread object, but that's their problem.
//
void
omni_thread::exit(void* return_value)
{
omni_thread* me = self();
if (me)
{
me->mutex.lock();
me->_state = STATE_TERMINATED;
me->mutex.unlock();
DB(cerr << "omni_thread::exit: thread " << me->id() << " detached "
<< me->detached << " return value " << return_value << endl);
if (me->detached) {
delete me;
} else {
me->return_val = return_value;
}
}
else
{
DB(cerr << "omni_thread::exit: called with a non-omnithread. Exit quietly." << endl);
}
// _endthreadex() does not automatically closes the thread handle.
// The omni_thread dtor closes the thread handle.
_endthreadex(0);
}
omni_thread*
omni_thread::self(void)
{
LPVOID me;
me = TlsGetValue(self_tls_index);
if (me == NULL) {
DB(cerr << "omni_thread::self: called with a non-ominthread. NULL is returned." << endl);
}
return (omni_thread*)me;
}
void
omni_thread::yield(void)
{
Sleep(0);
}
#define MAX_SLEEP_SECONDS (DWORD)4294966 // (2**32-2)/1000
void
omni_thread::sleep(unsigned long secs, unsigned long nanosecs)
{
if (secs <= MAX_SLEEP_SECONDS) {
Sleep(secs * 1000 + nanosecs / 1000000);
return;
}
DWORD no_of_max_sleeps = secs / MAX_SLEEP_SECONDS;
for (DWORD i = 0; i < no_of_max_sleeps; i++)
Sleep(MAX_SLEEP_SECONDS * 1000);
Sleep((secs % MAX_SLEEP_SECONDS) * 1000 + nanosecs / 1000000);
}
void
omni_thread::get_time(unsigned long* abs_sec, unsigned long* abs_nsec,
unsigned long rel_sec, unsigned long rel_nsec)
{
get_time_now(abs_sec, abs_nsec);
*abs_nsec += rel_nsec;
*abs_sec += rel_sec + *abs_nsec / 1000000000;
*abs_nsec = *abs_nsec % 1000000000;
}
int
omni_thread::nt_priority(priority_t pri)
{
switch (pri) {
case PRIORITY_LOW:
return THREAD_PRIORITY_LOWEST;
case PRIORITY_NORMAL:
return THREAD_PRIORITY_NORMAL;
case PRIORITY_HIGH:
return THREAD_PRIORITY_HIGHEST;
}
throw omni_thread_invalid();
return 0; /* keep msvc++ happy */
}
static void
get_time_now(unsigned long* abs_sec, unsigned long* abs_nsec)
{
static int days_in_preceding_months[12]
= { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
static int days_in_preceding_months_leap[12]
= { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 };
SYSTEMTIME st;
GetSystemTime(&st);
*abs_nsec = st.wMilliseconds * 1000000;
// this formula should work until 1st March 2100
DWORD days = ((st.wYear - 1970) * 365 + (st.wYear - 1969) / 4
+ ((st.wYear % 4)
? days_in_preceding_months[st.wMonth - 1]
: days_in_preceding_months_leap[st.wMonth - 1])
+ st.wDay - 1);
*abs_sec = st.wSecond + 60 * (st.wMinute + 60 * (st.wHour + 24 * days));
}
| {
"pile_set_name": "Github"
} |
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#-------------------------------------------------------------------------
#
# Standard Python modules
#
#-------------------------------------------------------------------------
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from .._regexpidbase import RegExpIdBase
#-------------------------------------------------------------------------
#
# HasIdOf
#
#-------------------------------------------------------------------------
class RegExpIdOf(RegExpIdBase):
"""Rule that checks for a person whose Gramps ID
matches regular expression.
"""
name = _('People with Id containing <text>')
description = _("Matches people whose Gramps ID matches "
"the regular expression")
| {
"pile_set_name": "Github"
} |
// Copyright 2015 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
// Program aebundler turns a Go app into a fully self-contained tar file.
// The app and its subdirectories (if any) are placed under "."
// and the dependencies from $GOPATH are placed under ./_gopath/src.
// A main func is synthesized if one does not exist.
//
// A sample Dockerfile to be used with this bundler could look like this:
// FROM gcr.io/google-appengine/go-compat
// ADD . /app
// RUN GOPATH=/app/_gopath go build -tags appenginevm -o /app/_ah/exe
package main
import (
"archive/tar"
"flag"
"fmt"
"go/ast"
"go/build"
"go/parser"
"go/token"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
var (
output = flag.String("o", "", "name of output tar file or '-' for stdout")
rootDir = flag.String("root", ".", "directory name of application root")
vm = flag.Bool("vm", true, `bundle an app for App Engine "flexible environment"`)
skipFiles = map[string]bool{
".git": true,
".gitconfig": true,
".hg": true,
".travis.yml": true,
}
)
const (
newMain = `package main
import "google.golang.org/appengine"
func main() {
appengine.Main()
}
`
)
func usage() {
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
fmt.Fprintf(os.Stderr, "\t%s -o <file.tar|->\tBundle app to named tar file or stdout\n", os.Args[0])
fmt.Fprintf(os.Stderr, "\noptional arguments:\n")
flag.PrintDefaults()
}
func main() {
flag.Usage = usage
flag.Parse()
var tags []string
if *vm {
tags = append(tags, "appenginevm")
} else {
tags = append(tags, "appengine")
}
tarFile := *output
if tarFile == "" {
usage()
errorf("Required -o flag not specified.")
}
app, err := analyze(tags)
if err != nil {
errorf("Error analyzing app: %v", err)
}
if err := app.bundle(tarFile); err != nil {
errorf("Unable to bundle app: %v", err)
}
}
// errorf prints the error message and exits.
func errorf(format string, a ...interface{}) {
fmt.Fprintf(os.Stderr, "aebundler: "+format+"\n", a...)
os.Exit(1)
}
type app struct {
hasMain bool
appFiles []string
imports map[string]string
}
// analyze checks the app for building with the given build tags and returns hasMain,
// app files, and a map of full directory import names to original import names.
func analyze(tags []string) (*app, error) {
ctxt := buildContext(tags)
hasMain, appFiles, err := checkMain(ctxt)
if err != nil {
return nil, err
}
gopath := filepath.SplitList(ctxt.GOPATH)
im, err := imports(ctxt, *rootDir, gopath)
return &app{
hasMain: hasMain,
appFiles: appFiles,
imports: im,
}, err
}
// buildContext returns the context for building the source.
func buildContext(tags []string) *build.Context {
return &build.Context{
GOARCH: build.Default.GOARCH,
GOOS: build.Default.GOOS,
GOROOT: build.Default.GOROOT,
GOPATH: build.Default.GOPATH,
Compiler: build.Default.Compiler,
BuildTags: append(build.Default.BuildTags, tags...),
}
}
// bundle bundles the app into the named tarFile ("-"==stdout).
func (s *app) bundle(tarFile string) (err error) {
var out io.Writer
if tarFile == "-" {
out = os.Stdout
} else {
f, err := os.Create(tarFile)
if err != nil {
return err
}
defer func() {
if cerr := f.Close(); err == nil {
err = cerr
}
}()
out = f
}
tw := tar.NewWriter(out)
for srcDir, importName := range s.imports {
dstDir := "_gopath/src/" + importName
if err = copyTree(tw, dstDir, srcDir); err != nil {
return fmt.Errorf("unable to copy directory %v to %v: %v", srcDir, dstDir, err)
}
}
if err := copyTree(tw, ".", *rootDir); err != nil {
return fmt.Errorf("unable to copy root directory to /app: %v", err)
}
if !s.hasMain {
if err := synthesizeMain(tw, s.appFiles); err != nil {
return fmt.Errorf("unable to synthesize new main func: %v", err)
}
}
if err := tw.Close(); err != nil {
return fmt.Errorf("unable to close tar file %v: %v", tarFile, err)
}
return nil
}
// synthesizeMain generates a new main func and writes it to the tarball.
func synthesizeMain(tw *tar.Writer, appFiles []string) error {
appMap := make(map[string]bool)
for _, f := range appFiles {
appMap[f] = true
}
var f string
for i := 0; i < 100; i++ {
f = fmt.Sprintf("app_main%d.go", i)
if !appMap[filepath.Join(*rootDir, f)] {
break
}
}
if appMap[filepath.Join(*rootDir, f)] {
return fmt.Errorf("unable to find unique name for %v", f)
}
hdr := &tar.Header{
Name: f,
Mode: 0644,
Size: int64(len(newMain)),
}
if err := tw.WriteHeader(hdr); err != nil {
return fmt.Errorf("unable to write header for %v: %v", f, err)
}
if _, err := tw.Write([]byte(newMain)); err != nil {
return fmt.Errorf("unable to write %v to tar file: %v", f, err)
}
return nil
}
// imports returns a map of all import directories (recursively) used by the app.
// The return value maps full directory names to original import names.
func imports(ctxt *build.Context, srcDir string, gopath []string) (map[string]string, error) {
pkg, err := ctxt.ImportDir(srcDir, 0)
if err != nil {
return nil, fmt.Errorf("unable to analyze source: %v", err)
}
// Resolve all non-standard-library imports
result := make(map[string]string)
for _, v := range pkg.Imports {
if !strings.Contains(v, ".") {
continue
}
src, err := findInGopath(v, gopath)
if err != nil {
return nil, fmt.Errorf("unable to find import %v in gopath %v: %v", v, gopath, err)
}
result[src] = v
im, err := imports(ctxt, src, gopath)
if err != nil {
return nil, fmt.Errorf("unable to parse package %v: %v", src, err)
}
for k, v := range im {
result[k] = v
}
}
return result, nil
}
// findInGopath searches the gopath for the named import directory.
func findInGopath(dir string, gopath []string) (string, error) {
for _, v := range gopath {
dst := filepath.Join(v, "src", dir)
if _, err := os.Stat(dst); err == nil {
return dst, nil
}
}
return "", fmt.Errorf("unable to find package %v in gopath %v", dir, gopath)
}
// copyTree copies srcDir to tar file dstDir, ignoring skipFiles.
func copyTree(tw *tar.Writer, dstDir, srcDir string) error {
entries, err := ioutil.ReadDir(srcDir)
if err != nil {
return fmt.Errorf("unable to read dir %v: %v", srcDir, err)
}
for _, entry := range entries {
n := entry.Name()
if skipFiles[n] {
continue
}
s := filepath.Join(srcDir, n)
d := filepath.Join(dstDir, n)
if entry.IsDir() {
if err := copyTree(tw, d, s); err != nil {
return fmt.Errorf("unable to copy dir %v to %v: %v", s, d, err)
}
continue
}
if err := copyFile(tw, d, s); err != nil {
return fmt.Errorf("unable to copy dir %v to %v: %v", s, d, err)
}
}
return nil
}
// copyFile copies src to tar file dst.
func copyFile(tw *tar.Writer, dst, src string) error {
s, err := os.Open(src)
if err != nil {
return fmt.Errorf("unable to open %v: %v", src, err)
}
defer s.Close()
fi, err := s.Stat()
if err != nil {
return fmt.Errorf("unable to stat %v: %v", src, err)
}
hdr, err := tar.FileInfoHeader(fi, dst)
if err != nil {
return fmt.Errorf("unable to create tar header for %v: %v", dst, err)
}
hdr.Name = dst
if err := tw.WriteHeader(hdr); err != nil {
return fmt.Errorf("unable to write header for %v: %v", dst, err)
}
_, err = io.Copy(tw, s)
if err != nil {
return fmt.Errorf("unable to copy %v to %v: %v", src, dst, err)
}
return nil
}
// checkMain verifies that there is a single "main" function.
// It also returns a list of all Go source files in the app.
func checkMain(ctxt *build.Context) (bool, []string, error) {
pkg, err := ctxt.ImportDir(*rootDir, 0)
if err != nil {
return false, nil, fmt.Errorf("unable to analyze source: %v", err)
}
if !pkg.IsCommand() {
errorf("Your app's package needs to be changed from %q to \"main\".\n", pkg.Name)
}
// Search for a "func main"
var hasMain bool
var appFiles []string
for _, f := range pkg.GoFiles {
n := filepath.Join(*rootDir, f)
appFiles = append(appFiles, n)
if hasMain, err = readFile(n); err != nil {
return false, nil, fmt.Errorf("error parsing %q: %v", n, err)
}
}
return hasMain, appFiles, nil
}
// isMain returns whether the given function declaration is a main function.
// Such a function must be called "main", not have a receiver, and have no arguments or return types.
func isMain(f *ast.FuncDecl) bool {
ft := f.Type
return f.Name.Name == "main" && f.Recv == nil && ft.Params.NumFields() == 0 && ft.Results.NumFields() == 0
}
// readFile reads and parses the Go source code file and returns whether it has a main function.
func readFile(filename string) (hasMain bool, err error) {
var src []byte
src, err = ioutil.ReadFile(filename)
if err != nil {
return
}
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, filename, src, 0)
for _, decl := range file.Decls {
funcDecl, ok := decl.(*ast.FuncDecl)
if !ok {
continue
}
if !isMain(funcDecl) {
continue
}
hasMain = true
break
}
return
}
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 25 2017 03:49:04).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <AppKit/NSView.h>
@interface _TtC12ControlStrip10SliderView : NSView
{
// Error parsing type: , name: suppressTouches
// Error parsing type: , name: touchEventInterceptor
}
- (void).cxx_destruct;
- (id)initWithCoder:(id)arg1;
- (id)initWithFrame:(struct CGRect)arg1;
- (void)touchesCancelledWithEvent:(id)arg1;
- (void)touchesEndedWithEvent:(id)arg1;
- (void)touchesMovedWithEvent:(id)arg1;
- (void)touchesBeganWithEvent:(id)arg1;
- (id)hitTest:(struct CGPoint)arg1;
@end
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Label="PropertySheets" />
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_PropertySheetDisplayName>Optimize For Speed</_PropertySheetDisplayName>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<Optimization>MaxSpeed</Optimization>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup>
<ClCompile>
<InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup>
<ClCompile>
<IntrinsicFunctions>true</IntrinsicFunctions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup>
<ClCompile>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup>
<ClCompile>
<OmitFramePointers>false</OmitFramePointers>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup />
</Project> | {
"pile_set_name": "Github"
} |
class A {
def x(i: Int) = i+"3"
} | {
"pile_set_name": "Github"
} |
/**
* This component acts as a simple AI that will reverse the movement direction of an object when it collides with something.
*
* @namespace platypus.components
* @class AIPacer
* @uses platypus.Component
*/
/*global platypus */
(function () {
'use strict';
return platypus.createComponentClass({
id: "AIPacer",
properties: {
/**
* This determines the direction of movement. Can be "horizontal", "vertical", or "both".
*
* @property movement
* @type String
* @default "both"
*/
movement: 'both',
/**
* This sets the initial direction of movement. Defaults to "up", or "left" if movement is horizontal.
*
* @property direction
* @type String
* @default "up"
*/
direction: null
},
initialize: function () {
this.lastDirection = '';
this.currentDirection = this.direction || ((this.movement === 'horizontal') ? 'left' : 'up');
},
events: {
/**
* This AI listens for a step message triggered by its entity parent in order to perform its logic on each tick.
*
* @method 'handle-ai'
*/
"handle-ai": function () {
if (this.currentDirection !== this.lastDirection) {
this.lastDirection = this.currentDirection;
/**
* Triggers this event prior to changing direction.
*
* @event 'stop'
*/
this.owner.triggerEvent('stop');
/**
* Triggers this event when the entity is moving right and collides with something.
*
* @event 'go-left'
*/
/**
* Triggers this event when the entity is moving left and collides with something.
*
* @event 'go-right'
*/
/**
* Triggers this event when the entity is moving up and collides with something.
*
* @event 'go-down'
*/
/**
* Triggers this event when the entity is moving down and collides with something.
*
* @event 'go-up'
*/
this.owner.triggerEvent('go-' + this.currentDirection);
}
},
/**
* On receiving this message, the component will check the collision side and re-orient itself accordingly.
*
* @method 'turn-around'
* @param collisionInfo {platypus.CollisionData} Uses direction of collision to determine whether to turn around.
*/
"turn-around": function (collisionInfo) {
if ((this.movement === 'both') || (this.movement === 'horizontal')) {
if (collisionInfo.x > 0) {
this.currentDirection = 'left';
} else if (collisionInfo.x < 0) {
this.currentDirection = 'right';
}
}
if ((this.movement === 'both') || (this.movement === 'vertical')) {
if (collisionInfo.y > 0) {
this.currentDirection = 'up';
} else if (collisionInfo.y < 0) {
this.currentDirection = 'down';
}
}
}
}
});
}());
| {
"pile_set_name": "Github"
} |
[console_scripts]
srt = pysrt.commands:main
| {
"pile_set_name": "Github"
} |
:mod:`tracopt.ticket.clone`
===========================
.. automodule :: tracopt.ticket.clone
:members:
| {
"pile_set_name": "Github"
} |
using Uno;
namespace Fuse.Scripting
{
public class ScriptException: Uno.Exception
{
public string Name { get; private set;}
public string FileName { get; private set;}
public int LineNumber { get; private set;}
public string ScriptStackTrace { get; private set; }
[Obsolete("Use ScriptException.Message instead")]
public string ErrorMessage { get { return Message; } }
[Obsolete("Use ScriptException.ScriptStackTrace instead")]
public string JSStackTrace { get { return ScriptStackTrace; } }
[Obsolete]
public string SourceLine { get { return null; } }
public ScriptException(
string name,
string message,
string fileName,
int lineNumber,
string stackTrace) : base(message)
{
Name = name;
FileName = fileName;
LineNumber = lineNumber;
ScriptStackTrace = stackTrace;
}
public override string ToString()
{
var stringBuilder = new Uno.Text.StringBuilder();
if (!string.IsNullOrEmpty(Name))
{
stringBuilder.Append("Name: ");
stringBuilder.AppendLine(Name);
}
if (!string.IsNullOrEmpty(FileName))
{
stringBuilder.Append("File name: ");
stringBuilder.AppendLine(FileName);
}
if (LineNumber >= 0)
{
stringBuilder.Append("Line number: ");
stringBuilder.AppendLine(LineNumber.ToString());
}
if (!string.IsNullOrEmpty(ScriptStackTrace))
{
stringBuilder.Append("Script stack trace: ");
stringBuilder.AppendLine(ScriptStackTrace);
}
return base.ToString() + "\n" + stringBuilder.ToString();
}
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!-- Reviewed: no -->
<sect2 id="zend.application.core-functionality.application">
<title>Zend_Application</title>
<para>
<classname>Zend_Application</classname> provides the base functionality of the
component, and the entry point to your Zend Framework application. It's
purpose is two-fold: to setup the <acronym>PHP</acronym> environment (including
autoloading), and to execute your application bootstrap.
</para>
<para>
Typically, you will pass all configuration to the
<classname>Zend_Application</classname> constructor, but you can also configure
the object entirely using its own methods. This reference is intended to
illustrate both use cases.
</para>
<table id="zend.application.core-functionality.application.api.options">
<title>Zend_Application options</title>
<tgroup cols="2">
<thead>
<row>
<entry>Option</entry>
<entry>Description</entry>
</row>
</thead>
<tbody>
<row>
<entry><emphasis><property>phpSettings</property></emphasis></entry>
<entry>
<para>
Array of <filename>php.ini</filename> settings to use. Keys should be
the <filename>php.ini</filename> keys.
</para>
</entry>
</row>
<row>
<entry><emphasis><property>includePaths</property></emphasis></entry>
<entry>
<para>
Additional paths to prepend to the <emphasis>include_path</emphasis>.
Should be an array of paths.
</para>
</entry>
</row>
<row>
<entry><emphasis><property>autoloaderNamespaces</property></emphasis></entry>
<entry>
<para>
Array of additional namespaces to register with the
<classname>Zend_Loader_Autoloader</classname> instance.
</para>
</entry>
</row>
<row>
<entry><emphasis><property>bootstrap</property></emphasis></entry>
<entry>
<para>
Either the string path to the bootstrap class, or an array
with elements for the 'path' and 'class' for the application
bootstrap.
</para>
</entry>
</row>
</tbody>
</tgroup>
</table>
<note>
<title>Option names</title>
<para>
Please note that option names are case insensitive.
</para>
</note>
<table id="zend.application.core-functionality.application.api.table">
<title>Zend_Application Methods</title>
<tgroup cols="4">
<thead>
<row>
<entry>Method</entry>
<entry>Return Value</entry>
<entry>Parameters</entry>
<entry>Description</entry>
</row>
</thead>
<tbody>
<row>
<entry>
<methodname>__construct($environment, $options = null)</methodname>
</entry>
<entry><type>Void</type></entry>
<entry>
<itemizedlist>
<listitem>
<para>
<varname>$environment</varname>: <emphasis>required</emphasis>,.
String representing the current application
environment. Typical strings might include
"development", "testing", "qa", or
"production", but will be defined by your
organizational requirements.
</para>
</listitem>
<listitem>
<para>
<varname>$options</varname>: <emphasis>optional</emphasis>.
Argument may be one of the following values:
</para>
<itemizedlist>
<listitem>
<para>
<emphasis><type>String</type></emphasis>: path to
a <classname>Zend_Config</classname> file to load
as configuration for your application.
<varname>$environment</varname> will be used
to determine what section of the
configuration to pull.
</para>
<para>
As of 1.10, you may also pass multiple paths containing
config files to be merged into a single configuration.
This assists in reducing config duplication across many
contexts which share common settings (e.g. configs for
<acronym>HTTP</acronym>, or <acronym>CLI</acronym>, each
sharing some characteristics but with their own
conflicting values for others) or merely splitting a
long configuration across many smaller categorised
files. The parameter in this case is an array with a
single key "config" whose value is an array of the
files to merge. Note: this means you either pass a
literal path, or
<command>array("config"=>array("/path1","/path2"[,...]));</command>.
</para>
</listitem>
<listitem>
<para>
<emphasis><type>Array</type></emphasis>: associative
array of configuration data for your application.
</para>
</listitem>
<listitem>
<para>
<emphasis><classname>Zend_Config</classname></emphasis>:
configuration object instance.
</para>
</listitem>
</itemizedlist>
</listitem>
</itemizedlist>
</entry>
<entry>
<para>
Constructor. Arguments are as described, and will be
used to set initial object state. An instance of
<classname>Zend_Loader_Autoloader</classname> is registered
during instantiation. Options passed to the
constructor are passed to <methodname>setOptions()</methodname>.
</para>
</entry>
</row>
<row>
<entry><methodname>getEnvironment()</methodname></entry>
<entry><type>String</type></entry>
<entry>N/A</entry>
<entry>
<para>Retrieve the environment string passed to the constructor.</para>
</entry>
</row>
<row>
<entry><methodname>getAutoloader()</methodname></entry>
<entry><classname>Zend_Loader_Autoloader</classname></entry>
<entry>N/A</entry>
<entry>
<para>
Retrieve the <classname>Zend_Loader_Autoloader</classname>
instance registered during instantiation.
</para>
</entry>
</row>
<row>
<entry><methodname>setOptions(array $options)</methodname></entry>
<entry><classname>Zend_Application</classname></entry>
<entry>
<itemizedlist>
<listitem>
<para>
<varname>$options</varname>: <emphasis>required</emphasis>.
An array of application options.
</para>
</listitem>
</itemizedlist>
</entry>
<entry>
<para>
All options are stored internally, and calling the
method multiple times will merge options. Options
matching the various setter methods will be passed
to those methods. As an example, the option
"phpSettings" will then be passed to
<methodname>setPhpSettings()</methodname>. (Option names are
case insensitive.)
</para>
</entry>
</row>
<row>
<entry><methodname>getOptions()</methodname></entry>
<entry><type>Array</type></entry>
<entry>N/A</entry>
<entry>
<para>
Retrieve all options used to initialize the object;
could be used to cache <classname>Zend_Config</classname>
options to a serialized format between requests.
</para>
</entry>
</row>
<row>
<entry><methodname>hasOption($key)</methodname></entry>
<entry><type>Boolean</type></entry>
<entry>
<itemizedlist>
<listitem>
<para>
<varname>$key</varname>: String option key to lookup
</para>
</listitem>
</itemizedlist>
</entry>
<entry>
<para>
Determine whether or not an option with the
specified key has been registered. Keys are case insensitive.
</para>
</entry>
</row>
<row>
<entry><methodname>getOption($key)</methodname></entry>
<entry><type>Mixed</type></entry>
<entry>
<itemizedlist>
<listitem>
<para><varname>$key</varname>: String option key to lookup</para>
</listitem>
</itemizedlist>
</entry>
<entry>
<para>
Retrieve the option value of a given key. Returns
<constant>NULL</constant> if the key does not exist.
</para>
</entry>
</row>
<row>
<entry>
<methodname>setPhpSettings(array $settings, $prefix = '')</methodname>
</entry>
<entry><classname>Zend_Application</classname></entry>
<entry>
<itemizedlist>
<listitem>
<para>
<varname>$settings</varname>: <emphasis>required</emphasis>.
Associative array of <acronym>PHP</acronym>
<acronym>INI</acronym> settings.
</para>
</listitem>
<listitem>
<para>
<varname>$prefix</varname>: <emphasis>optional</emphasis>.
String prefix with which to prepend option keys. Used
internally to allow mapping nested arrays to dot-separated
<filename>php.ini</filename> keys. In normal usage, this
argument should never be passed by a user.
</para>
</listitem>
</itemizedlist>
</entry>
<entry>
<para>
Set run-time <filename>php.ini</filename> settings. Dot-separated
settings may be nested hierarchically (which may occur
with <acronym>INI</acronym> <classname>Zend_Config</classname> files)
via an array-of-arrays, and will still resolve correctly.
</para>
</entry>
</row>
<row>
<entry>
<methodname>setAutoloaderNamespaces(array $namespaces)</methodname>
</entry>
<entry><classname>Zend_Application</classname></entry>
<entry>
<itemizedlist>
<listitem>
<para>
<varname>$namespaces</varname>: <emphasis>required</emphasis>.
Array of strings representing the namespaces to
register with the <classname>Zend_Loader_Autoloader</classname>
instance.
</para>
</listitem>
</itemizedlist>
</entry>
<entry>
<para>
Register namespaces with the
<classname>Zend_Loader_Autoloader</classname> instance.
</para>
</entry>
</row>
<row>
<entry><methodname>setBootstrap($path, $class = null)</methodname></entry>
<entry><classname>Zend_Application</classname></entry>
<entry>
<itemizedlist>
<listitem>
<para>
<varname>$path</varname>: <emphasis>required</emphasis>. May be
either a
<classname>Zend_Application_Bootstrap_Bootstrapper</classname>
instance, a string path to the bootstrap class, an
associative array of classname => filename, or an associative
array with the keys 'class' and 'path'.
</para>
</listitem>
<listitem>
<para>
<varname>$class</varname>: <emphasis>optional</emphasis>.
If <varname>$path</varname> is a string,
<varname>$class</varname> may be specified, and should
be a string class name of the class contained in
the file represented by path.
</para>
</listitem>
</itemizedlist>
</entry>
</row>
<row>
<entry><methodname>getBootstrap()</methodname></entry>
<entry>
<constant>NULL</constant> |
<classname>Zend_Application_Bootstrap_Bootstrapper</classname>
</entry>
<entry>N/A</entry>
<entry><para>Retrieve the registered bootstrap instance.</para></entry>
</row>
<row>
<entry><methodname>bootstrap()</methodname></entry>
<entry><type>Void</type></entry>
<entry>N/A</entry>
<entry>
<para>
Call the bootstrap's <methodname>bootstrap()</methodname>
method to bootstrap the application.
</para>
</entry>
</row>
<row>
<entry><methodname>run()</methodname></entry>
<entry><type>Void</type></entry>
<entry>N/A</entry>
<entry>
<para>
Call the bootstrap's <methodname>run()</methodname>
method to dispatch the application.
</para>
</entry>
</row>
</tbody>
</tgroup>
</table>
</sect2>
| {
"pile_set_name": "Github"
} |
/*
* ******************************************************************************
* Copyright (c) 2014-2015 Gabriele Mariotti.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* *****************************************************************************
*/
package com.dalingge.gankio.common.widgets.recyclerview.anim.itemanimator;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPropertyAnimatorCompat;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* @author Gabriele Mariotti ([email protected])
*/
public class SlideScaleInOutRightItemAnimator extends BaseItemAnimator {
private float DEFAULT_SCALE_INITIAL = 0.6f;
private float mInitialScaleX = DEFAULT_SCALE_INITIAL;
private float mInitialScaleY = DEFAULT_SCALE_INITIAL;
private float mEndScaleX = DEFAULT_SCALE_INITIAL;
private float mEndScaleY = DEFAULT_SCALE_INITIAL;
private float mOriginalScaleX;
private float mOriginalScaleY;
public SlideScaleInOutRightItemAnimator(RecyclerView recyclerView) {
super(recyclerView);
setAddDuration(750);
setRemoveDuration(750);
}
protected void animateRemoveImpl(final RecyclerView.ViewHolder holder) {
final View view = holder.itemView;
final ViewPropertyAnimatorCompat animation = ViewCompat.animate(view);
mRemoveAnimations.add(holder);
animation.setDuration(getRemoveDuration())
.scaleX(0)
.scaleY(0)
.alpha(0)
.translationX(+mRecyclerView.getLayoutManager().getWidth())
.setListener(new VpaListenerAdapter() {
@Override
public void onAnimationStart(View view) {
dispatchRemoveStarting(holder);
}
@Override
public void onAnimationEnd(View view) {
animation.setListener(null);
ViewCompat.setAlpha(view, 1);
ViewCompat.setScaleX(view, 0);
ViewCompat.setScaleY(view, 0);
ViewCompat.setTranslationX(view, +mRecyclerView.getLayoutManager().getWidth());
dispatchRemoveFinished(holder);
mRemoveAnimations.remove(holder);
dispatchFinishedWhenDone();
}
}).start();
}
@Override
protected void prepareAnimateAdd(RecyclerView.ViewHolder holder) {
retrieveOriginalScale(holder);
ViewCompat.setScaleX(holder.itemView, 0);
ViewCompat.setScaleY(holder.itemView,0);
ViewCompat.setTranslationX(holder.itemView, +mRecyclerView.getLayoutManager().getWidth());
}
protected void animateAddImpl(final RecyclerView.ViewHolder holder) {
final View view = holder.itemView;
final ViewPropertyAnimatorCompat animation = ViewCompat.animate(view);
mAddAnimations.add(holder);
animation.scaleX(1)
.scaleY(1)
.translationX(0)
.alpha(1)
.setDuration(getAddDuration())
.setListener(new VpaListenerAdapter() {
@Override
public void onAnimationStart(View view) {
dispatchAddStarting(holder);
}
@Override
public void onAnimationCancel(View view) {
ViewCompat.setAlpha(view, 1);
ViewCompat.setTranslationX(view, 0);
ViewCompat.setScaleX(view, 1);
ViewCompat.setScaleY(view, 1);
}
@Override
public void onAnimationEnd(View view) {
animation.setListener(null);
ViewCompat.setAlpha(view, 1);
ViewCompat.setTranslationX(view, 0);
ViewCompat.setScaleX(view, 1);
ViewCompat.setScaleY(view, 1);
dispatchAddFinished(holder);
mAddAnimations.remove(holder);
dispatchFinishedWhenDone();
}
}).start();
}
private void retrieveOriginalScale(RecyclerView.ViewHolder holder) {
mOriginalScaleX = ViewCompat.getScaleX(holder.itemView);
mOriginalScaleY = ViewCompat.getScaleY(holder.itemView);
}
}
| {
"pile_set_name": "Github"
} |
/* Copyright (c) 2010-2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/delay.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/pm_qos.h>
#include <linux/regulator/consumer.h>
#include <mach/gpio.h>
#include <mach/board.h>
#include <mach/camera.h>
#include <mach/vreg.h>
#include <mach/clk.h>
#define CAMIF_CFG_RMSK 0x1fffff
#define CAM_SEL_BMSK 0x2
#define CAM_PCLK_SRC_SEL_BMSK 0x60000
#define CAM_PCLK_INVERT_BMSK 0x80000
#define CAM_PAD_REG_SW_RESET_BMSK 0x100000
#define EXT_CAM_HSYNC_POL_SEL_BMSK 0x10000
#define EXT_CAM_VSYNC_POL_SEL_BMSK 0x8000
#define MDDI_CLK_CHICKEN_BIT_BMSK 0x80
#define CAM_SEL_SHFT 0x1
#define CAM_PCLK_SRC_SEL_SHFT 0x11
#define CAM_PCLK_INVERT_SHFT 0x13
#define CAM_PAD_REG_SW_RESET_SHFT 0x14
#define EXT_CAM_HSYNC_POL_SEL_SHFT 0x10
#define EXT_CAM_VSYNC_POL_SEL_SHFT 0xF
#define MDDI_CLK_CHICKEN_BIT_SHFT 0x7
/* MIPI CSI controller registers */
#define MIPI_PHY_CONTROL 0x00000000
#define MIPI_PROTOCOL_CONTROL 0x00000004
#define MIPI_INTERRUPT_STATUS 0x00000008
#define MIPI_INTERRUPT_MASK 0x0000000C
#define MIPI_CAMERA_CNTL 0x00000024
#define MIPI_CALIBRATION_CONTROL 0x00000018
#define MIPI_PHY_D0_CONTROL2 0x00000038
#define MIPI_PHY_D1_CONTROL2 0x0000003C
#define MIPI_PHY_D2_CONTROL2 0x00000040
#define MIPI_PHY_D3_CONTROL2 0x00000044
#define MIPI_PHY_CL_CONTROL 0x00000048
#define MIPI_PHY_D0_CONTROL 0x00000034
#define MIPI_PHY_D1_CONTROL 0x00000020
#define MIPI_PHY_D2_CONTROL 0x0000002C
#define MIPI_PHY_D3_CONTROL 0x00000030
#define MIPI_PROTOCOL_CONTROL_SW_RST_BMSK 0x8000000
#define MIPI_PROTOCOL_CONTROL_LONG_PACKET_HEADER_CAPTURE_BMSK 0x200000
#define MIPI_PROTOCOL_CONTROL_DATA_FORMAT_BMSK 0x180000
#define MIPI_PROTOCOL_CONTROL_DECODE_ID_BMSK 0x40000
#define MIPI_PROTOCOL_CONTROL_ECC_EN_BMSK 0x20000
#define MIPI_CALIBRATION_CONTROL_SWCAL_CAL_EN_SHFT 0x16
#define MIPI_CALIBRATION_CONTROL_SWCAL_STRENGTH_OVERRIDE_EN_SHFT 0x15
#define MIPI_CALIBRATION_CONTROL_CAL_SW_HW_MODE_SHFT 0x14
#define MIPI_CALIBRATION_CONTROL_MANUAL_OVERRIDE_EN_SHFT 0x7
#define MIPI_PROTOCOL_CONTROL_DATA_FORMAT_SHFT 0x13
#define MIPI_PROTOCOL_CONTROL_DPCM_SCHEME_SHFT 0x1e
#define MIPI_PHY_D0_CONTROL2_SETTLE_COUNT_SHFT 0x18
#define MIPI_PHY_D0_CONTROL2_HS_TERM_IMP_SHFT 0x10
#define MIPI_PHY_D0_CONTROL2_LP_REC_EN_SHFT 0x4
#define MIPI_PHY_D0_CONTROL2_ERR_SOT_HS_EN_SHFT 0x3
#define MIPI_PHY_D1_CONTROL2_SETTLE_COUNT_SHFT 0x18
#define MIPI_PHY_D1_CONTROL2_HS_TERM_IMP_SHFT 0x10
#define MIPI_PHY_D1_CONTROL2_LP_REC_EN_SHFT 0x4
#define MIPI_PHY_D1_CONTROL2_ERR_SOT_HS_EN_SHFT 0x3
#define MIPI_PHY_D2_CONTROL2_SETTLE_COUNT_SHFT 0x18
#define MIPI_PHY_D2_CONTROL2_HS_TERM_IMP_SHFT 0x10
#define MIPI_PHY_D2_CONTROL2_LP_REC_EN_SHFT 0x4
#define MIPI_PHY_D2_CONTROL2_ERR_SOT_HS_EN_SHFT 0x3
#define MIPI_PHY_D3_CONTROL2_SETTLE_COUNT_SHFT 0x18
#define MIPI_PHY_D3_CONTROL2_HS_TERM_IMP_SHFT 0x10
#define MIPI_PHY_D3_CONTROL2_LP_REC_EN_SHFT 0x4
#define MIPI_PHY_D3_CONTROL2_ERR_SOT_HS_EN_SHFT 0x3
#define MIPI_PHY_CL_CONTROL_HS_TERM_IMP_SHFT 0x18
#define MIPI_PHY_CL_CONTROL_LP_REC_EN_SHFT 0x2
#define MIPI_PHY_D0_CONTROL_HS_REC_EQ_SHFT 0x1c
#define MIPI_PHY_D1_CONTROL_MIPI_CLK_PHY_SHUTDOWNB_SHFT 0x9
#define MIPI_PHY_D1_CONTROL_MIPI_DATA_PHY_SHUTDOWNB_SHFT 0x8
#define CAMIO_VFE_CLK_SNAP 122880000
#define CAMIO_VFE_CLK_PREV 122880000
/* AXI rates in KHz */
#define MSM_AXI_QOS_PREVIEW 192000
#define MSM_AXI_QOS_SNAPSHOT 192000
#define MSM_AXI_QOS_RECORDING 192000
static struct clk *camio_vfe_mdc_clk;
static struct clk *camio_mdc_clk;
static struct clk *camio_vfe_clk;
static struct clk *camio_vfe_camif_clk;
static struct clk *camio_vfe_pbdg_clk;
static struct clk *camio_cam_m_clk;
static struct clk *camio_camif_pad_pbdg_clk;
static struct clk *camio_csi_clk;
static struct clk *camio_csi_pclk;
static struct clk *camio_csi_vfe_clk;
static struct clk *camio_vpe_clk;
static struct regulator *fs_vpe;
static struct msm_camera_io_ext camio_ext;
static struct msm_camera_io_clk camio_clk;
static struct resource *camifpadio, *csiio;
void __iomem *camifpadbase, *csibase;
static uint32_t vpe_clk_rate;
static struct regulator_bulk_data regs[] = {
{ .supply = "gp2", .min_uV = 2600000, .max_uV = 2600000 },
{ .supply = "lvsw1" },
{ .supply = "fs_vfe" },
/* sn12m0pz regulators */
{ .supply = "gp6", .min_uV = 3050000, .max_uV = 3100000 },
{ .supply = "gp16", .min_uV = 1200000, .max_uV = 1200000 },
};
static int reg_count;
static void msm_camera_vreg_enable(struct platform_device *pdev)
{
int count, rc;
struct device *dev = &pdev->dev;
/* Use gp6 and gp16 if and only if dev name matches. */
if (!strncmp(pdev->name, "msm_camera_sn12m0pz", 20))
count = ARRAY_SIZE(regs);
else
count = ARRAY_SIZE(regs) - 2;
rc = regulator_bulk_get(dev, count, regs);
if (rc) {
dev_err(dev, "%s: could not get regulators: %d\n",
__func__, rc);
return;
}
rc = regulator_bulk_set_voltage(count, regs);
if (rc) {
dev_err(dev, "%s: could not set voltages: %d\n",
__func__, rc);
goto reg_free;
}
rc = regulator_bulk_enable(count, regs);
if (rc) {
dev_err(dev, "%s: could not enable regulators: %d\n",
__func__, rc);
goto reg_free;
}
reg_count = count;
return;
reg_free:
regulator_bulk_free(count, regs);
return;
}
static void msm_camera_vreg_disable(void)
{
regulator_bulk_disable(reg_count, regs);
regulator_bulk_free(reg_count, regs);
reg_count = 0;
}
int msm_camio_clk_enable(enum msm_camio_clk_type clktype)
{
int rc = 0;
struct clk *clk = NULL;
switch (clktype) {
case CAMIO_VFE_MDC_CLK:
camio_vfe_mdc_clk =
clk = clk_get(NULL, "vfe_mdc_clk");
break;
case CAMIO_MDC_CLK:
camio_mdc_clk =
clk = clk_get(NULL, "mdc_clk");
break;
case CAMIO_VFE_CLK:
camio_vfe_clk =
clk = clk_get(NULL, "vfe_clk");
msm_camio_clk_rate_set_2(clk, camio_clk.vfe_clk_rate);
break;
case CAMIO_VFE_CAMIF_CLK:
camio_vfe_camif_clk =
clk = clk_get(NULL, "vfe_camif_clk");
break;
case CAMIO_VFE_PBDG_CLK:
camio_vfe_pbdg_clk =
clk = clk_get(NULL, "vfe_pclk");
break;
case CAMIO_CAM_MCLK_CLK:
camio_cam_m_clk =
clk = clk_get(NULL, "cam_m_clk");
msm_camio_clk_rate_set_2(clk, camio_clk.mclk_clk_rate);
break;
case CAMIO_CAMIF_PAD_PBDG_CLK:
camio_camif_pad_pbdg_clk =
clk = clk_get(NULL, "camif_pad_pclk");
break;
case CAMIO_CSI0_CLK:
camio_csi_clk =
clk = clk_get(NULL, "csi_clk");
msm_camio_clk_rate_set_2(clk, 153600000);
break;
case CAMIO_CSI0_VFE_CLK:
camio_csi_vfe_clk =
clk = clk_get(NULL, "csi_vfe_clk");
break;
case CAMIO_CSI0_PCLK:
camio_csi_pclk =
clk = clk_get(NULL, "csi_pclk");
break;
case CAMIO_VPE_CLK:
camio_vpe_clk =
clk = clk_get(NULL, "vpe_clk");
vpe_clk_rate = clk_round_rate(clk, vpe_clk_rate);
clk_set_rate(clk, vpe_clk_rate);
break;
default:
break;
}
if (!IS_ERR(clk))
clk_prepare_enable(clk);
else
rc = -1;
return rc;
}
int msm_camio_clk_disable(enum msm_camio_clk_type clktype)
{
int rc = 0;
struct clk *clk = NULL;
switch (clktype) {
case CAMIO_VFE_MDC_CLK:
clk = camio_vfe_mdc_clk;
break;
case CAMIO_MDC_CLK:
clk = camio_mdc_clk;
break;
case CAMIO_VFE_CLK:
clk = camio_vfe_clk;
break;
case CAMIO_VFE_CAMIF_CLK:
clk = camio_vfe_camif_clk;
break;
case CAMIO_VFE_PBDG_CLK:
clk = camio_vfe_pbdg_clk;
break;
case CAMIO_CAM_MCLK_CLK:
clk = camio_cam_m_clk;
break;
case CAMIO_CAMIF_PAD_PBDG_CLK:
clk = camio_camif_pad_pbdg_clk;
break;
case CAMIO_CSI0_CLK:
clk = camio_csi_clk;
break;
case CAMIO_CSI0_VFE_CLK:
clk = camio_csi_vfe_clk;
break;
case CAMIO_CSI0_PCLK:
clk = camio_csi_pclk;
break;
case CAMIO_VPE_CLK:
clk = camio_vpe_clk;
break;
default:
break;
}
if (!IS_ERR(clk)) {
clk_disable_unprepare(clk);
clk_put(clk);
} else {
rc = -1;
}
return rc;
}
void msm_camio_clk_rate_set(int rate)
{
struct clk *clk = camio_cam_m_clk;
clk_set_rate(clk, rate);
}
int msm_camio_vfe_clk_rate_set(int rate)
{
struct clk *clk = camio_vfe_clk;
return clk_set_rate(clk, rate);
}
void msm_camio_clk_rate_set_2(struct clk *clk, int rate)
{
clk_set_rate(clk, rate);
}
static irqreturn_t msm_io_csi_irq(int irq_num, void *data)
{
uint32_t irq;
irq = msm_camera_io_r(csibase + MIPI_INTERRUPT_STATUS);
CDBG("%s MIPI_INTERRUPT_STATUS = 0x%x\n", __func__, irq);
msm_camera_io_w(irq, csibase + MIPI_INTERRUPT_STATUS);
return IRQ_HANDLED;
}
int msm_camio_vpe_clk_disable(void)
{
msm_camio_clk_disable(CAMIO_VPE_CLK);
if (fs_vpe) {
regulator_disable(fs_vpe);
regulator_put(fs_vpe);
}
return 0;
}
int msm_camio_vpe_clk_enable(uint32_t clk_rate)
{
fs_vpe = regulator_get(NULL, "fs_vpe");
if (IS_ERR(fs_vpe)) {
pr_err("%s: Regulator FS_VPE get failed %ld\n", __func__,
PTR_ERR(fs_vpe));
fs_vpe = NULL;
} else if (regulator_enable(fs_vpe)) {
pr_err("%s: Regulator FS_VPE enable failed\n", __func__);
regulator_put(fs_vpe);
}
vpe_clk_rate = clk_rate;
msm_camio_clk_enable(CAMIO_VPE_CLK);
return 0;
}
int msm_camio_enable(struct platform_device *pdev)
{
int rc = 0;
struct msm_camera_sensor_info *sinfo = pdev->dev.platform_data;
msm_camio_clk_enable(CAMIO_VFE_PBDG_CLK);
if (!sinfo->csi_if)
msm_camio_clk_enable(CAMIO_VFE_CAMIF_CLK);
else {
msm_camio_clk_enable(CAMIO_VFE_CLK);
csiio = request_mem_region(camio_ext.csiphy,
camio_ext.csisz, pdev->name);
if (!csiio) {
rc = -EBUSY;
goto common_fail;
}
csibase = ioremap(camio_ext.csiphy,
camio_ext.csisz);
if (!csibase) {
rc = -ENOMEM;
goto csi_busy;
}
rc = request_irq(camio_ext.csiirq, msm_io_csi_irq,
IRQF_TRIGGER_RISING, "csi", 0);
if (rc < 0)
goto csi_irq_fail;
/* enable required clocks for CSI */
msm_camio_clk_enable(CAMIO_CSI0_PCLK);
msm_camio_clk_enable(CAMIO_CSI0_VFE_CLK);
msm_camio_clk_enable(CAMIO_CSI0_CLK);
}
return 0;
csi_irq_fail:
iounmap(csibase);
csi_busy:
release_mem_region(camio_ext.csiphy, camio_ext.csisz);
common_fail:
msm_camio_clk_disable(CAMIO_VFE_PBDG_CLK);
msm_camio_clk_disable(CAMIO_VFE_CLK);
return rc;
}
static void msm_camio_csi_disable(void)
{
uint32_t val;
val = 0x0;
CDBG("%s MIPI_PHY_D0_CONTROL2 val=0x%x\n", __func__, val);
msm_camera_io_w(val, csibase + MIPI_PHY_D0_CONTROL2);
msm_camera_io_w(val, csibase + MIPI_PHY_D1_CONTROL2);
msm_camera_io_w(val, csibase + MIPI_PHY_D2_CONTROL2);
msm_camera_io_w(val, csibase + MIPI_PHY_D3_CONTROL2);
CDBG("%s MIPI_PHY_CL_CONTROL val=0x%x\n", __func__, val);
msm_camera_io_w(val, csibase + MIPI_PHY_CL_CONTROL);
usleep_range(9000, 10000);
free_irq(camio_ext.csiirq, 0);
iounmap(csibase);
release_mem_region(camio_ext.csiphy, camio_ext.csisz);
}
void msm_camio_disable(struct platform_device *pdev)
{
struct msm_camera_sensor_info *sinfo = pdev->dev.platform_data;
if (!sinfo->csi_if) {
msm_camio_clk_disable(CAMIO_VFE_CAMIF_CLK);
} else {
CDBG("disable mipi\n");
msm_camio_csi_disable();
CDBG("disable clocks\n");
msm_camio_clk_disable(CAMIO_CSI0_PCLK);
msm_camio_clk_disable(CAMIO_CSI0_VFE_CLK);
msm_camio_clk_disable(CAMIO_CSI0_CLK);
msm_camio_clk_disable(CAMIO_VFE_CLK);
}
msm_camio_clk_disable(CAMIO_VFE_PBDG_CLK);
}
void msm_camio_camif_pad_reg_reset(void)
{
uint32_t reg;
msm_camio_clk_sel(MSM_CAMIO_CLK_SRC_INTERNAL);
usleep_range(10000, 11000);
reg = (msm_camera_io_r(camifpadbase)) & CAMIF_CFG_RMSK;
reg |= 0x3;
msm_camera_io_w(reg, camifpadbase);
usleep_range(10000, 11000);
reg = (msm_camera_io_r(camifpadbase)) & CAMIF_CFG_RMSK;
reg |= 0x10;
msm_camera_io_w(reg, camifpadbase);
usleep_range(10000, 11000);
reg = (msm_camera_io_r(camifpadbase)) & CAMIF_CFG_RMSK;
/* Need to be uninverted*/
reg &= 0x03;
msm_camera_io_w(reg, camifpadbase);
usleep_range(10000, 11000);
}
void msm_camio_vfe_blk_reset(void)
{
return;
}
void msm_camio_camif_pad_reg_reset_2(void)
{
uint32_t reg;
uint32_t mask, value;
reg = (msm_camera_io_r(camifpadbase)) & CAMIF_CFG_RMSK;
mask = CAM_PAD_REG_SW_RESET_BMSK;
value = 1 << CAM_PAD_REG_SW_RESET_SHFT;
msm_camera_io_w((reg & (~mask)) | (value & mask), camifpadbase);
usleep_range(10000, 11000);
reg = (msm_camera_io_r(camifpadbase)) & CAMIF_CFG_RMSK;
mask = CAM_PAD_REG_SW_RESET_BMSK;
value = 0 << CAM_PAD_REG_SW_RESET_SHFT;
msm_camera_io_w((reg & (~mask)) | (value & mask), camifpadbase);
usleep_range(10000, 11000);
}
void msm_camio_clk_sel(enum msm_camio_clk_src_type srctype)
{
struct clk *clk = NULL;
clk = camio_vfe_clk;
if (clk != NULL) {
switch (srctype) {
case MSM_CAMIO_CLK_SRC_INTERNAL:
clk_set_flags(clk, 0x00000100 << 1);
break;
case MSM_CAMIO_CLK_SRC_EXTERNAL:
clk_set_flags(clk, 0x00000100);
break;
default:
break;
}
}
}
int msm_camio_probe_on(struct platform_device *pdev)
{
struct msm_camera_sensor_info *sinfo = pdev->dev.platform_data;
struct msm_camera_device_platform_data *camdev = sinfo->pdata;
camio_clk = camdev->ioclk;
camio_ext = camdev->ioext;
camdev->camera_gpio_on();
msm_camera_vreg_enable(pdev);
return msm_camio_clk_enable(CAMIO_CAM_MCLK_CLK);
}
int msm_camio_probe_off(struct platform_device *pdev)
{
struct msm_camera_sensor_info *sinfo = pdev->dev.platform_data;
struct msm_camera_device_platform_data *camdev = sinfo->pdata;
msm_camera_vreg_disable();
camdev->camera_gpio_off();
return msm_camio_clk_disable(CAMIO_CAM_MCLK_CLK);
}
int msm_camio_sensor_clk_on(struct platform_device *pdev)
{
int rc = 0;
struct msm_camera_sensor_info *sinfo = pdev->dev.platform_data;
struct msm_camera_device_platform_data *camdev = sinfo->pdata;
camio_clk = camdev->ioclk;
camio_ext = camdev->ioext;
camdev->camera_gpio_on();
msm_camera_vreg_enable(pdev);
msm_camio_clk_enable(CAMIO_CAM_MCLK_CLK);
msm_camio_clk_enable(CAMIO_CAMIF_PAD_PBDG_CLK);
if (!sinfo->csi_if) {
camifpadio = request_mem_region(camio_ext.camifpadphy,
camio_ext.camifpadsz, pdev->name);
msm_camio_clk_enable(CAMIO_VFE_CLK);
if (!camifpadio) {
rc = -EBUSY;
goto common_fail;
}
camifpadbase = ioremap(camio_ext.camifpadphy,
camio_ext.camifpadsz);
if (!camifpadbase) {
CDBG("msm_camio_sensor_clk_on fail\n");
rc = -ENOMEM;
goto parallel_busy;
}
}
return rc;
parallel_busy:
release_mem_region(camio_ext.camifpadphy, camio_ext.camifpadsz);
goto common_fail;
common_fail:
msm_camio_clk_disable(CAMIO_CAM_MCLK_CLK);
msm_camio_clk_disable(CAMIO_VFE_CLK);
msm_camio_clk_disable(CAMIO_CAMIF_PAD_PBDG_CLK);
msm_camera_vreg_disable();
camdev->camera_gpio_off();
return rc;
}
int msm_camio_sensor_clk_off(struct platform_device *pdev)
{
uint32_t rc = 0;
struct msm_camera_sensor_info *sinfo = pdev->dev.platform_data;
struct msm_camera_device_platform_data *camdev = sinfo->pdata;
camdev->camera_gpio_off();
msm_camera_vreg_disable();
rc = msm_camio_clk_disable(CAMIO_CAM_MCLK_CLK);
rc = msm_camio_clk_disable(CAMIO_CAMIF_PAD_PBDG_CLK);
if (!sinfo->csi_if) {
iounmap(camifpadbase);
release_mem_region(camio_ext.camifpadphy, camio_ext.camifpadsz);
rc = msm_camio_clk_disable(CAMIO_VFE_CLK);
}
return rc;
}
int msm_camio_csi_config(struct msm_camera_csi_params *csi_params)
{
int rc = 0;
uint32_t val = 0;
int i;
CDBG("msm_camio_csi_config\n");
/* SOT_ECC_EN enable error correction for SYNC (data-lane) */
msm_camera_io_w(0x4, csibase + MIPI_PHY_CONTROL);
/* SW_RST to the CSI core */
msm_camera_io_w(MIPI_PROTOCOL_CONTROL_SW_RST_BMSK,
csibase + MIPI_PROTOCOL_CONTROL);
/* PROTOCOL CONTROL */
val = MIPI_PROTOCOL_CONTROL_LONG_PACKET_HEADER_CAPTURE_BMSK |
MIPI_PROTOCOL_CONTROL_DECODE_ID_BMSK |
MIPI_PROTOCOL_CONTROL_ECC_EN_BMSK;
val |= (uint32_t)(csi_params->data_format) <<
MIPI_PROTOCOL_CONTROL_DATA_FORMAT_SHFT;
val |= csi_params->dpcm_scheme <<
MIPI_PROTOCOL_CONTROL_DPCM_SCHEME_SHFT;
CDBG("%s MIPI_PROTOCOL_CONTROL val=0x%x\n", __func__, val);
msm_camera_io_w(val, csibase + MIPI_PROTOCOL_CONTROL);
/* SW CAL EN */
val = (0x1 << MIPI_CALIBRATION_CONTROL_SWCAL_CAL_EN_SHFT) |
(0x1 <<
MIPI_CALIBRATION_CONTROL_SWCAL_STRENGTH_OVERRIDE_EN_SHFT) |
(0x1 << MIPI_CALIBRATION_CONTROL_CAL_SW_HW_MODE_SHFT) |
(0x1 << MIPI_CALIBRATION_CONTROL_MANUAL_OVERRIDE_EN_SHFT);
CDBG("%s MIPI_CALIBRATION_CONTROL val=0x%x\n", __func__, val);
msm_camera_io_w(val, csibase + MIPI_CALIBRATION_CONTROL);
/* settle_cnt is very sensitive to speed!
increase this value to run at higher speeds */
val = (csi_params->settle_cnt <<
MIPI_PHY_D0_CONTROL2_SETTLE_COUNT_SHFT) |
(0x0F << MIPI_PHY_D0_CONTROL2_HS_TERM_IMP_SHFT) |
(0x1 << MIPI_PHY_D0_CONTROL2_LP_REC_EN_SHFT) |
(0x1 << MIPI_PHY_D0_CONTROL2_ERR_SOT_HS_EN_SHFT);
CDBG("%s MIPI_PHY_D0_CONTROL2 val=0x%x\n", __func__, val);
for (i = 0; i < csi_params->lane_cnt; i++)
msm_camera_io_w(val, csibase + MIPI_PHY_D0_CONTROL2 + i * 4);
val = (0x0F << MIPI_PHY_CL_CONTROL_HS_TERM_IMP_SHFT) |
(0x1 << MIPI_PHY_CL_CONTROL_LP_REC_EN_SHFT);
CDBG("%s MIPI_PHY_CL_CONTROL val=0x%x\n", __func__, val);
msm_camera_io_w(val, csibase + MIPI_PHY_CL_CONTROL);
val = 0 << MIPI_PHY_D0_CONTROL_HS_REC_EQ_SHFT;
msm_camera_io_w(val, csibase + MIPI_PHY_D0_CONTROL);
val = (0x1 << MIPI_PHY_D1_CONTROL_MIPI_CLK_PHY_SHUTDOWNB_SHFT) |
(0x1 << MIPI_PHY_D1_CONTROL_MIPI_DATA_PHY_SHUTDOWNB_SHFT);
CDBG("%s MIPI_PHY_D1_CONTROL val=0x%x\n", __func__, val);
msm_camera_io_w(val, csibase + MIPI_PHY_D1_CONTROL);
msm_camera_io_w(0x00000000, csibase + MIPI_PHY_D2_CONTROL);
msm_camera_io_w(0x00000000, csibase + MIPI_PHY_D3_CONTROL);
/* halcyon only supports 1 or 2 lane */
switch (csi_params->lane_cnt) {
case 1:
msm_camera_io_w(csi_params->lane_assign << 8 | 0x4,
csibase + MIPI_CAMERA_CNTL);
break;
case 2:
msm_camera_io_w(csi_params->lane_assign << 8 | 0x5,
csibase + MIPI_CAMERA_CNTL);
break;
case 3:
msm_camera_io_w(csi_params->lane_assign << 8 | 0x6,
csibase + MIPI_CAMERA_CNTL);
break;
case 4:
msm_camera_io_w(csi_params->lane_assign << 8 | 0x7,
csibase + MIPI_CAMERA_CNTL);
break;
}
/* mask out ID_ERROR[19], DATA_CMM_ERR[11]
and CLK_CMM_ERR[10] - de-featured */
msm_camera_io_w(0xFFF7F3FF, csibase + MIPI_INTERRUPT_MASK);
/*clear IRQ bits*/
msm_camera_io_w(0xFFF7F3FF, csibase + MIPI_INTERRUPT_STATUS);
return rc;
}
void msm_camio_set_perf_lvl(enum msm_bus_perf_setting perf_setting)
{
switch (perf_setting) {
case S_INIT:
add_axi_qos();
break;
case S_PREVIEW:
update_axi_qos(MSM_AXI_QOS_PREVIEW);
break;
case S_VIDEO:
update_axi_qos(MSM_AXI_QOS_RECORDING);
break;
case S_CAPTURE:
update_axi_qos(MSM_AXI_QOS_SNAPSHOT);
break;
case S_DEFAULT:
update_axi_qos(PM_QOS_DEFAULT_VALUE);
break;
case S_EXIT:
release_axi_qos();
break;
default:
CDBG("%s: INVALID CASE\n", __func__);
}
}
int msm_cam_core_reset(void)
{
struct clk *clk1;
int rc = 0;
clk1 = clk_get(NULL, "csi_vfe_clk");
if (IS_ERR(clk1)) {
pr_err("%s: did not get csi_vfe_clk\n", __func__);
return PTR_ERR(clk1);
}
rc = clk_reset(clk1, CLK_RESET_ASSERT);
if (rc) {
pr_err("%s:csi_vfe_clk assert failed\n", __func__);
clk_put(clk1);
return rc;
}
usleep_range(1000, 1200);
rc = clk_reset(clk1, CLK_RESET_DEASSERT);
if (rc) {
pr_err("%s:csi_vfe_clk deassert failed\n", __func__);
clk_put(clk1);
return rc;
}
clk_put(clk1);
clk1 = clk_get(NULL, "csi_clk");
if (IS_ERR(clk1)) {
pr_err("%s: did not get csi_clk\n", __func__);
return PTR_ERR(clk1);
}
rc = clk_reset(clk1, CLK_RESET_ASSERT);
if (rc) {
pr_err("%s:csi_clk assert failed\n", __func__);
clk_put(clk1);
return rc;
}
usleep_range(1000, 1200);
rc = clk_reset(clk1, CLK_RESET_DEASSERT);
if (rc) {
pr_err("%s:csi_clk deassert failed\n", __func__);
clk_put(clk1);
return rc;
}
clk_put(clk1);
clk1 = clk_get(NULL, "csi_pclk");
if (IS_ERR(clk1)) {
pr_err("%s: did not get csi_pclk\n", __func__);
return PTR_ERR(clk1);
}
rc = clk_reset(clk1, CLK_RESET_ASSERT);
if (rc) {
pr_err("%s:csi_pclk assert failed\n", __func__);
clk_put(clk1);
return rc;
}
usleep_range(1000, 1200);
rc = clk_reset(clk1, CLK_RESET_DEASSERT);
if (rc) {
pr_err("%s:csi_pclk deassert failed\n", __func__);
clk_put(clk1);
return rc;
}
clk_put(clk1);
return rc;
}
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <ScreenReaderOutput/SCROIOElement.h>
@interface SCROIOUSBElement : SCROIOElement
{
}
- (int)transport;
- (id)initWithIOObject:(unsigned int)arg1;
@end
| {
"pile_set_name": "Github"
} |
/* -*- c++ -*- */
/*
* @file
* @author (C) 2015 by Roman Khassraf <[email protected]>
* @section LICENSE
*
* Gr-gsm is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* Gr-gsm is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with gr-gsm; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef INCLUDED_GSM_BURST_FNR_FILTER_H
#define INCLUDED_GSM_BURST_FNR_FILTER_H
#include <grgsm/api.h>
#include <gnuradio/block.h>
#include <grgsm/flow_control/common.h>
namespace gr {
namespace gsm {
enum filter_mode
{
FILTER_LESS_OR_EQUAL,
FILTER_GREATER_OR_EQUAL
};
/*!
* \brief <+description of block+>
* \ingroup gsm
*
*/
class GRGSM_API burst_fnr_filter : virtual public gr::block
{
public:
typedef boost::shared_ptr<burst_fnr_filter> sptr;
/*!
* \brief Return a shared_ptr to a new instance of gsm::burst_fnr_filter.
*
* To avoid accidental use of raw pointers, gsm::burst_fnr_filter's
* constructor is in a private implementation
* class. gsm::burst_fnr_filter::make is the public interface for
* creating new instances.
*/
static sptr make(filter_mode mode, unsigned int fnr);
/* External API */
virtual unsigned int get_fn(void) = 0;
virtual unsigned int set_fn(unsigned int fn) = 0;
virtual filter_mode get_mode(void) = 0;
virtual filter_mode set_mode(filter_mode mode) = 0;
/* Filtering policy */
virtual filter_policy get_policy(void) = 0;
virtual filter_policy set_policy(filter_policy policy) = 0;
};
} // namespace gsm
} // namespace gr
#endif /* INCLUDED_GSM_BURST_FNR_FILTER_H */
| {
"pile_set_name": "Github"
} |
//===- KaleidoscopeJIT.h - A simple JIT for Kaleidoscope --------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Contains a simple JIT definition for use in the kaleidoscope tutorials.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_EXECUTIONENGINE_ORC_KALEIDOSCOPEJIT_H
#define LLVM_EXECUTIONENGINE_ORC_KALEIDOSCOPEJIT_H
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/ExecutionEngine/JITSymbol.h"
#include "llvm/ExecutionEngine/Orc/CompileUtils.h"
#include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
#include "llvm/ExecutionEngine/Orc/LambdaResolver.h"
#include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
#include "llvm/ExecutionEngine/SectionMemoryManager.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Mangler.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include <algorithm>
#include <map>
#include <memory>
#include <string>
#include <vector>
namespace llvm {
namespace orc {
class KaleidoscopeJIT {
public:
using ObjLayerT = LegacyRTDyldObjectLinkingLayer;
using CompileLayerT = LegacyIRCompileLayer<ObjLayerT, SimpleCompiler>;
KaleidoscopeJIT()
: Resolver(createLegacyLookupResolver(
ES,
[this](const std::string &Name) {
return ObjectLayer.findSymbol(Name, true);
},
[](Error Err) { cantFail(std::move(Err), "lookupFlags failed"); })),
TM(EngineBuilder().selectTarget()), DL(TM->createDataLayout()),
ObjectLayer(ES,
[this](VModuleKey) {
return ObjLayerT::Resources{
std::make_shared<SectionMemoryManager>(), Resolver};
}),
CompileLayer(ObjectLayer, SimpleCompiler(*TM)) {
llvm::sys::DynamicLibrary::LoadLibraryPermanently(nullptr);
}
TargetMachine &getTargetMachine() { return *TM; }
VModuleKey addModule(std::unique_ptr<Module> M) {
auto K = ES.allocateVModule();
cantFail(CompileLayer.addModule(K, std::move(M)));
ModuleKeys.push_back(K);
return K;
}
void removeModule(VModuleKey K) {
ModuleKeys.erase(find(ModuleKeys, K));
cantFail(CompileLayer.removeModule(K));
}
JITSymbol findSymbol(const std::string Name) {
return findMangledSymbol(mangle(Name));
}
private:
std::string mangle(const std::string &Name) {
std::string MangledName;
{
raw_string_ostream MangledNameStream(MangledName);
Mangler::getNameWithPrefix(MangledNameStream, Name, DL);
}
return MangledName;
}
JITSymbol findMangledSymbol(const std::string &Name) {
#ifdef _WIN32
// The symbol lookup of ObjectLinkingLayer uses the SymbolRef::SF_Exported
// flag to decide whether a symbol will be visible or not, when we call
// IRCompileLayer::findSymbolIn with ExportedSymbolsOnly set to true.
//
// But for Windows COFF objects, this flag is currently never set.
// For a potential solution see: https://reviews.llvm.org/rL258665
// For now, we allow non-exported symbols on Windows as a workaround.
const bool ExportedSymbolsOnly = false;
#else
const bool ExportedSymbolsOnly = true;
#endif
// Search modules in reverse order: from last added to first added.
// This is the opposite of the usual search order for dlsym, but makes more
// sense in a REPL where we want to bind to the newest available definition.
for (auto H : make_range(ModuleKeys.rbegin(), ModuleKeys.rend()))
if (auto Sym = CompileLayer.findSymbolIn(H, Name, ExportedSymbolsOnly))
return Sym;
// If we can't find the symbol in the JIT, try looking in the host process.
if (auto SymAddr = RTDyldMemoryManager::getSymbolAddressInProcess(Name))
return JITSymbol(SymAddr, JITSymbolFlags::Exported);
#ifdef _WIN32
// For Windows retry without "_" at beginning, as RTDyldMemoryManager uses
// GetProcAddress and standard libraries like msvcrt.dll use names
// with and without "_" (for example "_itoa" but "sin").
if (Name.length() > 2 && Name[0] == '_')
if (auto SymAddr =
RTDyldMemoryManager::getSymbolAddressInProcess(Name.substr(1)))
return JITSymbol(SymAddr, JITSymbolFlags::Exported);
#endif
return nullptr;
}
ExecutionSession ES;
std::shared_ptr<SymbolResolver> Resolver;
std::unique_ptr<TargetMachine> TM;
const DataLayout DL;
ObjLayerT ObjectLayer;
CompileLayerT CompileLayer;
std::vector<VModuleKey> ModuleKeys;
};
} // end namespace orc
} // end namespace llvm
#endif // LLVM_EXECUTIONENGINE_ORC_KALEIDOSCOPEJIT_H
| {
"pile_set_name": "Github"
} |
-- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
{:max, :min, :abs} = math
{:define_class} = require 'aullar.util'
flair = require 'aullar.flair'
flair.define 'selection', {
type: flair.RECTANGLE,
background: '#a3d5da',
background_alpha: 0.6,
min_width: 'letter'
}
flair.define 'selection-overlay', {
type: flair.RECTANGLE,
background: '#c3e5ea',
background_alpha: 0.4,
min_width: 'letter'
}
Selection = {
new: (@view) =>
@_anchor = nil
@_end_pos = nil
@persistent = false
properties: {
is_empty: => (@_anchor == nil) or (@_anchor == @_end_pos)
size: =>
return 0 if @is_empty
abs @_anchor - @_end_pos
anchor: {
get: => @_anchor
set: (anchor) =>
return if anchor == @_anchor
error "Can't set anchor when selection is empty", 2 if @is_empty
@_anchor = anchor
@_refresh_display!
@_notify_change!
}
end_pos: {
get: => @_end_pos
set: (end_pos) =>
return if end_pos == @_end_pos
error "Can't set end_pos when selection is empty", 2 if @is_empty
@_end_pos = end_pos
@_refresh_display!
@_notify_change!
}
}
set: (anchor, end_pos) =>
return if anchor == @_anchor and end_pos == @_end_pos
@clear! unless @is_empty
@_anchor = anchor
@_end_pos = end_pos
@_refresh_display!
@_notify_change!
extend: (from_pos, to_pos) =>
if @is_empty
@set from_pos, to_pos
else
@view\refresh_display from_offset: min(to_pos, @_end_pos), to_offset: max(to_pos, @_end_pos)
@_end_pos = to_pos
@_notify_change!
clear: =>
return unless @_anchor and @_end_pos
@_refresh_display!
@_anchor, @_end_pos = nil, nil
@_notify_change!
range: =>
return nil, nil if @is_empty
min(@_anchor, @_end_pos), max(@_anchor, @_end_pos)
affects_line: (line) =>
return false if @is_empty
start, stop = @range!
if start >= line.start_offset
return start <= line.end_offset
stop >= line.start_offset
draw: (x, y, cr, display_line, line) =>
start, stop = @range!
start_col, end_col = 1, line.size + 1
sel_start, sel_end = false, false
if start > line.start_offset -- sel starts on line
start_col = (start - line.start_offset) + 1
sel_start = true
if stop <= line.end_offset -- sel ends on line
end_col = (stop - line.start_offset) + 1
sel_end = true
return if start_col == end_col and (sel_start or sel_end)
flair.draw 'selection', display_line, start_col, end_col, x, y, cr
draw_overlay: (x, y, cr, display_line, line) =>
bg_ranges = display_line.background_ranges
return unless #bg_ranges > 0
start, stop = @range!
start_col = (start - line.start_offset) + 1
end_col = (stop - line.start_offset) + 1
sel_start = start > line.start_offset
sel_end = stop <= line.end_offset
for range in *bg_ranges
break if range.start_offset > end_col
if range.end_offset > start_col
start_o = max start_col, range.start_offset
end_o = min end_col, range.end_offset
continue if start_o == end_o and (sel_start or sel_end)
flair.draw 'selection-overlay', display_line, start_o, end_o, x, y, cr
_notify_change: =>
if @listener and @listener.on_selection_changed
@listener.on_selection_changed @listener, self
_refresh_display: =>
start_offset, end_offset = @range!
@view\refresh_display from_offset: start_offset or 1, to_offset: end_offset
}
define_class Selection
| {
"pile_set_name": "Github"
} |
; RUN: opt -S -wholeprogramdevirt %s | FileCheck %s
target datalayout = "e-p:64:64"
target triple = "x86_64-unknown-linux-gnu"
@vt1 = constant [1 x i8*] [i8* bitcast (i1 (i8*)* @vf0 to i8*)], !type !0
@vt2 = constant [1 x i8*] [i8* bitcast (i1 (i8*)* @vf0 to i8*)], !type !0, !type !1
@vt3 = constant [1 x i8*] [i8* bitcast (i1 (i8*)* @vf1 to i8*)], !type !0, !type !1
@vt4 = constant [1 x i8*] [i8* bitcast (i1 (i8*)* @vf1 to i8*)], !type !1
define i1 @vf0(i8* %this) readnone {
ret i1 0
}
define i1 @vf1(i8* %this) readnone {
ret i1 1
}
; CHECK: define i1 @call1
define i1 @call1(i8* %obj) {
%vtableptr = bitcast i8* %obj to [1 x i8*]**
%vtable = load [1 x i8*]*, [1 x i8*]** %vtableptr
; CHECK: [[VT1:%[^ ]*]] = bitcast [1 x i8*]* {{.*}} to i8*
%vtablei8 = bitcast [1 x i8*]* %vtable to i8*
%p = call i1 @llvm.type.test(i8* %vtablei8, metadata !"typeid1")
call void @llvm.assume(i1 %p)
%fptrptr = getelementptr [1 x i8*], [1 x i8*]* %vtable, i32 0, i32 0
%fptr = load i8*, i8** %fptrptr
%fptr_casted = bitcast i8* %fptr to i1 (i8*)*
; CHECK: [[RES1:%[^ ]*]] = icmp eq i8* [[VT1]], bitcast ([1 x i8*]* @vt3 to i8*)
%result = call i1 %fptr_casted(i8* %obj)
; CHECK: ret i1 [[RES1]]
ret i1 %result
}
; CHECK: define i1 @call2
define i1 @call2(i8* %obj) {
%vtableptr = bitcast i8* %obj to [1 x i8*]**
%vtable = load [1 x i8*]*, [1 x i8*]** %vtableptr
; CHECK: [[VT2:%[^ ]*]] = bitcast [1 x i8*]* {{.*}} to i8*
%vtablei8 = bitcast [1 x i8*]* %vtable to i8*
%p = call i1 @llvm.type.test(i8* %vtablei8, metadata !"typeid2")
call void @llvm.assume(i1 %p)
%fptrptr = getelementptr [1 x i8*], [1 x i8*]* %vtable, i32 0, i32 0
%fptr = load i8*, i8** %fptrptr
%fptr_casted = bitcast i8* %fptr to i1 (i8*)*
; CHECK: [[RES1:%[^ ]*]] = icmp ne i8* [[VT1]], bitcast ([1 x i8*]* @vt2 to i8*)
%result = call i1 %fptr_casted(i8* %obj)
ret i1 %result
}
declare i1 @llvm.type.test(i8*, metadata)
declare void @llvm.assume(i1)
!0 = !{i32 0, !"typeid1"}
!1 = !{i32 0, !"typeid2"}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<title>equals</title>
<link rel="stylesheet" href="prism.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="header">
<div class="doc-title"><a href="folktale.html"><span class="doc-title"><span class="product-name">Folktale</span><span class="version">v2.1.0</span></span></a><ul class="navigation"><li class="navigation-item"><a href="https://github.com/origamitower/folktale" title="">GitHub</a></li><li class="navigation-item"><a href="/docs/support/" title="">Support</a></li><li class="navigation-item"><a href="/docs/v2.1.0/contributing/" title="">Contributing</a></li></ul></div>
</div>
<div id="content-wrapper"><div id="content-panel"><h1 class="entity-title">equals</h1><div class="highlight-summary"><div></div></div><div class="deprecation-section"><strong class="deprecation-title">This feature is experimental!</strong><p>This API is still experimental, so it may change or be removed in future versions. You should not rely on it for production applications.</p></div><div class="definition"><h2 class="section-title" id="signature">Signature</h2><div class="signature">equals(value)</div><div class="type-definition"><div class="type-definition-container"><div class="type-title-container"><strong class="type-title">Type</strong><a class="info" href="/docs/v2.1.0/misc/type-notation/">(what is this?)</a></div><pre class="type"><code class="language-haskell">forall S, a:
(S a).(S a) => Boolean
where S is Setoid</code></pre></div></div></div><h2 class="section-title">Documentation</h2><div class="documentation"><div></div></div><div class="members"><h2 class="section-title" id="properties">Properties</h2></div><div class="source-code"><h2 class="section-title" id="source-code">Source Code</h2><div class="source-location"></div><pre class="source-code"><code class="language-javascript">function(value) {
assertType(adt)(`${this[tagSymbol]}#equals`, value);
return sameType(this, value) && compositesEqual(this, value, Object.keys(this));
}</code></pre></div></div><div id="meta-panel"><div class="meta-section"><div class="meta-field"><strong class="meta-field-title">Stability</strong><div class="meta-field-value">experimental</div></div><div class="meta-field"><strong class="meta-field-title">Licence</strong><div class="meta-field-value">MIT</div></div></div><div class="table-of-contents"><div class="meta-section-title">On This Page</div><ul class="toc-list level-1"><li class="toc-item"><a href="#signature">Signature</a></li><li class="toc-item"><span class="no-anchor">Documentation</span><ul class="toc-list level-2"></ul></li><li class="toc-item"><a href="#properties">Properties</a><ul class="toc-list level-2"></ul></li><li class="toc-item"><a href="#source-code">Source Code</a></li></ul></div><div class="meta-section"><strong class="meta-section-title">Authors</strong><div class="meta-field"><strong class="meta-field-title">Copyright</strong><div class="meta-field-value">(c) 2013-2017 Quildreen Motta, and CONTRIBUTORS</div></div><div class="meta-field"><strong class="meta-field-title">Authors</strong><div class="meta-field-value"><ul class="meta-list"><li>@boris-marinov</li><li>Quildreen Motta</li></ul></div></div><div class="meta-field"><strong class="meta-field-title">Maintainers</strong><div class="meta-field-value"><ul class="meta-list"><li>Quildreen Motta <[email protected]> (http://robotlolita.me/)</li></ul></div></div></div></div></div>
<script>
void function() {
var xs = document.querySelectorAll('.documentation pre code');
for (var i = 0; i < xs.length; ++i) {
xs[i].className = 'language-javascript code-block';
}
}()
</script>
<script src="prism.js"></script>
</body>
</html> | {
"pile_set_name": "Github"
} |
// Boost Lambda Library - is_instance_of.hpp ---------------------
// Copyright (C) 2001 Jaakko Jarvi ([email protected])
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.lslboost.org/LICENSE_1_0.txt)
//
// For more information, see www.lslboost.org
// ---------------------------------------------------------------
#ifndef BOOST_LAMBDA_IS_INSTANCE_OF
#define BOOST_LAMBDA_IS_INSTANCE_OF
#include "lslboost/config.hpp" // for BOOST_STATIC_CONSTANT
#include "lslboost/type_traits/conversion_traits.hpp" // for is_convertible
#include "lslboost/preprocessor/enum_shifted_params.hpp"
#include "lslboost/preprocessor/repeat_2nd.hpp"
// is_instance_of --------------------------------
//
// is_instance_of_n<A, B>::value is true, if type A is
// an instantiation of a template B, or A derives from an instantiation
// of template B
//
// n is the number of template arguments for B
//
// Example:
// is_instance_of_2<std::istream, basic_stream>::value == true
// The original implementation was somewhat different, with different versions
// for different compilers. However, there was still a problem
// with gcc.3.0.2 and 3.0.3 compilers, which didn't think regard
// is_instance_of_N<...>::value was a constant.
// John Maddock suggested the way around this problem by building
// is_instance_of templates using lslboost::is_convertible.
// Now we only have one version of is_instance_of templates, which delagate
// all the nasty compiler tricks to is_convertible.
#define BOOST_LAMBDA_CLASS(z, N,A) BOOST_PP_COMMA_IF(N) class
#define BOOST_LAMBDA_CLASS_ARG(z, N,A) BOOST_PP_COMMA_IF(N) class A##N
#define BOOST_LAMBDA_ARG(z, N,A) BOOST_PP_COMMA_IF(N) A##N
#define BOOST_LAMBDA_CLASS_LIST(n, NAME) BOOST_PP_REPEAT(n, BOOST_LAMBDA_CLASS, NAME)
#define BOOST_LAMBDA_CLASS_ARG_LIST(n, NAME) BOOST_PP_REPEAT(n, BOOST_LAMBDA_CLASS_ARG, NAME)
#define BOOST_LAMBDA_ARG_LIST(n, NAME) BOOST_PP_REPEAT(n, BOOST_LAMBDA_ARG, NAME)
namespace lslboost {
namespace lambda {
#define BOOST_LAMBDA_IS_INSTANCE_OF_TEMPLATE(INDEX) \
\
namespace detail { \
\
template <template<BOOST_LAMBDA_CLASS_LIST(INDEX,T)> class F> \
struct BOOST_PP_CAT(conversion_tester_,INDEX) { \
template<BOOST_LAMBDA_CLASS_ARG_LIST(INDEX,A)> \
BOOST_PP_CAT(conversion_tester_,INDEX) \
(const F<BOOST_LAMBDA_ARG_LIST(INDEX,A)>&); \
}; \
\
} /* end detail */ \
\
template <class From, template <BOOST_LAMBDA_CLASS_LIST(INDEX,T)> class To> \
struct BOOST_PP_CAT(is_instance_of_,INDEX) \
{ \
private: \
typedef ::lslboost::is_convertible< \
From, \
BOOST_PP_CAT(detail::conversion_tester_,INDEX)<To> \
> helper_type; \
\
public: \
BOOST_STATIC_CONSTANT(bool, value = helper_type::value); \
};
#define BOOST_LAMBDA_HELPER(z, N, A) BOOST_LAMBDA_IS_INSTANCE_OF_TEMPLATE( BOOST_PP_INC(N) )
// Generate the traits for 1-4 argument templates
BOOST_PP_REPEAT_2ND(4,BOOST_LAMBDA_HELPER,FOO)
#undef BOOST_LAMBDA_HELPER
#undef BOOST_LAMBDA_IS_INSTANCE_OF_TEMPLATE
#undef BOOST_LAMBDA_CLASS
#undef BOOST_LAMBDA_ARG
#undef BOOST_LAMBDA_CLASS_ARG
#undef BOOST_LAMBDA_CLASS_LIST
#undef BOOST_LAMBDA_ARG_LIST
#undef BOOST_LAMBDA_CLASS_ARG_LIST
} // lambda
} // lslboost
#endif
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: f39af9085dab46278471d207ca5d0a61
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
import GridFitType from "openfl/text/GridFitType";
import * as assert from "assert";
describe ("TypeScript | GridFitType", function () {
it ("test", function () {
switch (""+GridFitType.NONE) {
case GridFitType.NONE:
case GridFitType.PIXEL:
case GridFitType.SUBPIXEL:
break;
}
});
}); | {
"pile_set_name": "Github"
} |
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef __NVKM_OPROXY_H__
#define __NVKM_OPROXY_H__
#define nvkm_oproxy(p) container_of((p), struct nvkm_oproxy, base)
#include <core/object.h>
struct nvkm_oproxy {
const struct nvkm_oproxy_func *func;
struct nvkm_object base;
struct nvkm_object *object;
};
struct nvkm_oproxy_func {
void (*dtor[2])(struct nvkm_oproxy *);
int (*init[2])(struct nvkm_oproxy *);
int (*fini[2])(struct nvkm_oproxy *, bool suspend);
};
void nvkm_oproxy_ctor(const struct nvkm_oproxy_func *,
const struct nvkm_oclass *, struct nvkm_oproxy *);
int nvkm_oproxy_new_(const struct nvkm_oproxy_func *,
const struct nvkm_oclass *, struct nvkm_oproxy **);
#endif
| {
"pile_set_name": "Github"
} |
# ---------------------------------------------------------------------------------------------------------------------
# ENVIRONMENT VARIABLES
# Define these secrets as environment variables
# ---------------------------------------------------------------------------------------------------------------------
# AWS_ACCESS_KEY_ID
# AWS_SECRET_ACCESS_KEY
# ---------------------------------------------------------------------------------------------------------------------
# OPTIONAL PARAMETERS
# ---------------------------------------------------------------------------------------------------------------------
variable "server_port" {
description = "The port the server will use for HTTP requests"
type = number
default = 8080
} | {
"pile_set_name": "Github"
} |
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.caching.internal.controller;
import org.gradle.caching.BuildCacheService;
import java.io.Closeable;
import java.util.Optional;
/**
* Internal coordinator of build cache operations.
*
* Wraps user {@link BuildCacheService} implementations.
*/
public interface BuildCacheController extends Closeable {
boolean isEnabled();
boolean isEmitDebugLogging();
<T> Optional<T> load(BuildCacheLoadCommand<T> command);
void store(BuildCacheStoreCommand command);
}
| {
"pile_set_name": "Github"
} |
<component name="libraryTable">
<library name="regular">
<CLASSES />
<JAVADOC />
<SOURCES />
</library>
</component> | {
"pile_set_name": "Github"
} |
/**
* Copyright 2014 XCL-Charts
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @Project XCL-Charts
* @Description Android图表基类库
* @author XiongChuanLiang<br/>([email protected])
* @Copyright Copyright (c) 2014 XCL-Charts (www.xclcharts.com)
* @license http://www.apache.org/licenses/ Apache v2 License
* @version 1.0
*/
package com.demo.xclcharts.view;
import java.text.DecimalFormat;
import java.util.LinkedList;
import java.util.List;
import org.xclcharts.chart.BarData;
import org.xclcharts.chart.StackBarChart;
import org.xclcharts.common.DensityUtil;
import org.xclcharts.common.IFormatterDoubleCallBack;
import org.xclcharts.common.IFormatterTextCallBack;
import org.xclcharts.event.click.BarPosition;
import org.xclcharts.renderer.XEnum;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
/**
* @ClassName StackBarChart02View
* @Description 堆叠图 的例子(横向)
* @author XiongChuanLiang<br/>([email protected])
*/
public class StackBarChart02View extends DemoView {
private String TAG = "StackBarChart02View";
private StackBarChart chart = new StackBarChart();
//标签轴
List<String> chartLabels = new LinkedList<String>();
List<BarData> BarDataSet = new LinkedList<BarData>();
Paint pToolTip = new Paint(Paint.ANTI_ALIAS_FLAG);
public StackBarChart02View(Context context) {
super(context);
// TODO Auto-generated constructor stub
initView();
}
public StackBarChart02View(Context context, AttributeSet attrs){
super(context, attrs);
initView();
}
public StackBarChart02View(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView();
}
private void initView()
{
chartLabels();
chartDataSet();
chartRender();
//綁定手势滑动事件
this.bindTouch(this,chart);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
//图所占范围大小
chart.setChartRange(w,h);
}
private void chartRender()
{
try {
//设置绘图区默认缩进px值,留置空间显示Axis,Axistitle....
int [] ltrb = getBarLnDefaultSpadding();
chart.setPadding(DensityUtil.dip2px(getContext(), 50),ltrb[1], ltrb[2], ltrb[3]);
//显示边框
chart.showRoundBorder();
//指定显示为横向柱形
chart.setChartDirection(XEnum.Direction.HORIZONTAL);
//数据源
chart.setCategories(chartLabels);
chart.setDataSource(BarDataSet);
//坐标系
chart.getDataAxis().setAxisMax(1200);
chart.getDataAxis().setAxisMin(100);
chart.getDataAxis().setAxisSteps(100);
//指定数据轴标签旋转-45度显示
chart.getCategoryAxis().setTickLabelRotateAngle(-45f);
//标题
chart.setTitle("费用预算与实际发生对比");
chart.addSubtitle("(XCL-Charts Demo)");
chart.setTitleAlign(XEnum.HorizontalAlign.CENTER);
//图例
chart.getAxisTitle().setLowerTitle("单位为(W)");
//背景网格
chart.getPlotGrid().showVerticalLines();
chart.getPlotGrid().setVerticalLineStyle(XEnum.LineStyle.DOT);
//chart.getPlotGrid().setVerticalLinesVisible(true);
//chart.getPlotGrid().setEvenRowsFillVisible(true);
//chart.getPlotGrid().getEvenFillPaint().setColor((int)Color.rgb(225, 230, 246));
//定义数据轴标签显示格式
chart.getDataAxis().setLabelFormatter(new IFormatterTextCallBack(){
@Override
public String textFormatter(String value) {
// TODO Auto-generated method stub
DecimalFormat df=new DecimalFormat("#0");
Double tmp = Double.parseDouble(value);
String label = df.format(tmp).toString();
return label;
}
});
//定义标签轴标签显示颜色
chart.getCategoryAxis().getTickLabelPaint().
setColor(Color.rgb(1, 188, 242));
//定义柱形上标签显示格式
chart.getBar().setItemLabelVisible(true);
chart.setItemLabelFormatter(new IFormatterDoubleCallBack() {
@Override
public String doubleFormatter(Double value) {
// TODO Auto-generated method stub
DecimalFormat df=new DecimalFormat("#0.00");
String label = df.format(value).toString();
return label;
}});
//定义柱形上标签显示颜色
chart.getBar().getItemLabelPaint().setColor(Color.rgb(225, 43, 44));
//柱形形标签字体大小
chart.getBar().getItemLabelPaint().setTextSize(18);
//激活点击监听
chart.ActiveListenItemClick();
chart.showClikedFocus();
chart.setPlotPanMode(XEnum.PanMode.VERTICAL);
//设置柱子的最大高度范围,不然有些数据太少时,柱子太高不太好看。
chart.getBar().setBarMaxPxHeight(100.f);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e(TAG, e.toString());
}
}
private void chartDataSet()
{
//标签对应的柱形数据集
List<Double> dataSeriesA= new LinkedList<Double>();
dataSeriesA.add(200d);
dataSeriesA.add(550d);
dataSeriesA.add(400d);
List<Double> dataSeriesB= new LinkedList<Double>();
dataSeriesB.add(380d);
dataSeriesB.add(452.57d);
dataSeriesB.add(657.65d);
BarDataSet.add(new BarData("预算(Budget)",dataSeriesA,Color.rgb(64, 175, 240)));
BarDataSet.add(new BarData("实际(Actual)",dataSeriesB,Color.rgb(247, 156, 27)));
}
private void chartLabels()
{
chartLabels.add("一季度(Q1)");
chartLabels.add("二季度(Q2)");
chartLabels.add("三季度(Q3)");
}
@Override
public void render(Canvas canvas) {
try{
//chart.setChartRange(this.getMeasuredWidth(), this.getMeasuredHeight());
//chart.setChartRange(this.getWidth(), this.getHeight());
chart.render(canvas);
} catch (Exception e){
Log.e(TAG, e.toString());
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
super.onTouchEvent(event);
if(event.getAction() == MotionEvent.ACTION_UP)
{
triggerClick(event.getX(),event.getY());
}
return true;
}
//触发监听
private void triggerClick(float x,float y)
{
BarPosition record = chart.getPositionRecord(x,y);
if( null == record) return;
if(record.getDataID() >= BarDataSet.size()) return;
BarData bData = BarDataSet.get(record.getDataID());
Double bValue = bData.getDataSet().get(record.getDataChildID());
chart.showFocusRectF(record.getRectF());
chart.getFocusPaint().setStyle(Style.FILL);
chart.getFocusPaint().setStrokeWidth(3);
chart.getFocusPaint().setColor(Color.GRAY);
chart.getFocusPaint().setAlpha(100);
//在点击处显示tooltip
pToolTip.setColor(Color.WHITE);
chart.getToolTip().setAlign(Align.CENTER);
chart.getToolTip().getBackgroundPaint().setColor(Color.BLUE);
chart.getToolTip().setInfoStyle(XEnum.DyInfoStyle.CAPROUNDRECT);
//chart.getToolTip().setCurrentXY(x,y);
chart.getToolTip().setCurrentXY(record.getRectF().centerX(),record.getRectF().top);
chart.getToolTip().addToolTip(" Current Value:" +Double.toString(bValue),pToolTip);
this.invalidate();
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2015 Red Hat, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include "../src/common-config.h"
#include "../src/config-ports.c"
#include "../src/ipc.pb-c.h"
#define reset(x,y) { \
talloc_free(x); \
x = NULL; \
y = 0; }
void fw_port_st__init(FwPortSt *message)
{
return;
}
void check_vals(FwPortSt **fw_ports, size_t n_fw_ports) {
if (n_fw_ports != 7) {
fprintf(stderr, "error in %d (detected %d)\n", __LINE__, (int)n_fw_ports);
exit(1);
}
if (fw_ports[0]->proto != PROTO_ICMP || fw_ports[1]->proto != PROTO_TCP || fw_ports[2]->proto != PROTO_UDP ||
fw_ports[3]->proto != PROTO_SCTP || fw_ports[4]->proto != PROTO_TCP ||
fw_ports[5]->proto != PROTO_UDP || fw_ports[6]->proto != PROTO_ICMPv6) {
fprintf(stderr, "error in %d\n", __LINE__);
exit(1);
}
if (fw_ports[1]->port != 88 || fw_ports[2]->port != 90 ||
fw_ports[3]->port != 70 || fw_ports[4]->port != 443 ||
fw_ports[5]->port != 80) {
fprintf(stderr, "error in %d\n", __LINE__);
exit(1);
}
}
int main()
{
char p[256];
int ret;
FwPortSt **fw_ports = NULL;
size_t n_fw_ports = 0;
void *pool = talloc_new(NULL);
strcpy(p, "icmp(), tcp(88), udp(90), sctp(70), tcp(443), udp(80), icmpv6()");
ret = cfg_parse_ports(pool, &fw_ports, &n_fw_ports, p);
if (ret < 0) {
fprintf(stderr, "error in %d\n", __LINE__);
exit(1);
}
check_vals(fw_ports, n_fw_ports);
/* check spacing tolerance */
reset(fw_ports, n_fw_ports);
strcpy(p, "icmp ( ), tcp ( 88 ), udp ( 90 ), sctp ( 70 ) , tcp ( 443 ) , udp(80) , icmpv6 ( ) ");
ret = cfg_parse_ports(pool, &fw_ports, &n_fw_ports, p);
if (ret < 0) {
fprintf(stderr, "error in %d\n", __LINE__);
exit(1);
}
check_vals(fw_ports, n_fw_ports);
/* test error 1 */
reset(fw_ports, n_fw_ports);
strcpy(p, "tcp(88), tcp(90),");
ret = cfg_parse_ports(pool, &fw_ports, &n_fw_ports, p);
if (ret >= 0) {
fprintf(stderr, "error in %d\n", __LINE__);
exit(1);
}
/* test error 2 */
reset(fw_ports, n_fw_ports);
strcpy(p, "tcp(88), tcp");
ret = cfg_parse_ports(pool, &fw_ports, &n_fw_ports, p);
if (ret >= 0) {
fprintf(stderr, "error in %d\n", __LINE__);
exit(1);
}
reset(fw_ports, n_fw_ports);
strcpy(p, "!(icmp(), tcp(88), udp(90), sctp(70), tcp(443), udp(80), icmpv6())");
ret = cfg_parse_ports(pool, &fw_ports, &n_fw_ports, p);
if (ret < 0) {
fprintf(stderr, "error in %d\n", __LINE__);
exit(1);
}
check_vals(fw_ports, n_fw_ports);
if (fw_ports[0]->negate == 0) {
fprintf(stderr, "error in %d\n", __LINE__);
exit(1);
}
talloc_free(pool);
return 0;
}
| {
"pile_set_name": "Github"
} |
/*
* /MathJax/jax/output/HTML-CSS/fonts/STIX/General/Bold/NumberForms.js
*
* Copyright (c) 2012 Design Science, Inc.
*
* Part of the MathJax library.
* See http://www.mathjax.org for details.
*
* Licensed under the Apache License, Version 2.0;
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS["STIXGeneral-bold"],{8531:[688,12,750,-7,763],8532:[688,12,750,28,763],8533:[688,12,750,-7,775],8534:[688,12,750,28,775],8535:[688,12,750,23,775],8536:[688,12,750,22,775],8537:[688,12,750,-7,758],8538:[688,12,750,49,758],8539:[688,12,750,-7,775],8540:[688,12,750,23,775],8541:[688,12,750,49,775],8542:[688,12,750,30,775]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/General/Bold/NumberForms.js");
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2016 Crown Copyright
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package stroom.statistics.impl.sql.client.gin;
import stroom.core.client.gin.PluginModule;
import stroom.statistics.impl.sql.client.StatisticsPlugin;
import stroom.statistics.impl.sql.client.presenter.StatisticsDataSourcePresenter;
import stroom.statistics.impl.sql.client.presenter.StatisticsDataSourceSettingsPresenter;
import stroom.statistics.impl.sql.client.presenter.StatisticsDataSourceSettingsPresenter.StatisticsDataSourceSettingsView;
import stroom.statistics.impl.sql.client.presenter.StatisticsFieldEditPresenter;
import stroom.statistics.impl.sql.client.presenter.StatisticsFieldEditPresenter.StatisticsFieldEditView;
import stroom.statistics.impl.sql.client.view.StatisticsDataSourceSettingsViewImpl;
import stroom.statistics.impl.sql.client.view.StatisticsFieldEditViewImpl;
public class StatisticsModule extends PluginModule {
@Override
protected void configure() {
// Statistics
bindPlugin(StatisticsPlugin.class);
bind(StatisticsDataSourcePresenter.class);
bindPresenterWidget(StatisticsDataSourceSettingsPresenter.class, StatisticsDataSourceSettingsView.class,
StatisticsDataSourceSettingsViewImpl.class);
bindPresenterWidget(StatisticsFieldEditPresenter.class, StatisticsFieldEditView.class,
StatisticsFieldEditViewImpl.class);
}
}
| {
"pile_set_name": "Github"
} |
{
"sdk": {
"version": "3.1.100",
"rollForward": "latestMajor"
}
}
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 7f3c732744db97d46ab800a0e52650db
timeCreated: 1474883423
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
drop table if exists `T1`;
drop table if exists `T2`;
drop table if exists `T3`;
drop table if exists `T4`;
drop table if exists `T5`;
drop table if exists `T6`;
drop table if exists `T7`;
drop table if exists `T8`;
drop table if exists `T9`;
SET NAMES ujis;
SET character_set_database = ucs2;
SET collation_connection = ucs2_general_ci;
CREATE TABLE `T1` (`C1` char(20), INDEX(`C1`)) DEFAULT CHARSET = ucs2 engine = innodb;
CREATE TABLE `T2` (`C1` char(20), INDEX(`C1`)) DEFAULT CHARSET = ucs2 engine = innodb;
CREATE TABLE `T3` (`C1` char(20), INDEX(`C1`)) DEFAULT CHARSET = ucs2 engine = innodb;
CREATE TABLE `T4` (`C1` char(20), INDEX(`C1`)) DEFAULT CHARSET = ucs2 engine = myisam;
CREATE TABLE `T5` (`C1` char(20), INDEX(`C1`)) DEFAULT CHARSET = ucs2 engine = myisam;
CREATE TABLE `T6` (`C1` char(20), INDEX(`C1`)) DEFAULT CHARSET = ucs2 engine = myisam;
CREATE TABLE `T7` (`C1` char(20), INDEX(`C1`)) DEFAULT CHARSET = ucs2 engine = MEMORY;
CREATE TABLE `T8` (`C1` char(20), INDEX(`C1`)) DEFAULT CHARSET = ucs2 engine = MEMORY;
CREATE TABLE `T9` (`C1` char(20), INDEX(`C1`)) DEFAULT CHARSET = ucs2 engine = MEMORY;
INSERT INTO `T1` VALUES
('PQRSTUVWXYZ[\\]^_')
,(' 。「」、・ヲァィゥェォャュョッ')
,('ーアイウエオカキクケコサシスセソ')
,('タチツテトナニヌネノハヒフヘホマ')
,('ミムメモヤユヨラリルレロワン゙゚');
INSERT INTO `T2` VALUES
(' 、。,.・:;?!゛゜´`¨^ ̄_ヽ')
,('ヾゝゞ〃仝々〆〇ー―‐/\〜‖|…‥‘’')
,('“”()〔〕[]{}〈〉《》「」『』【】')
,('・ぁあぃいぅうぇえぉおかがきぎくぐけげこ')
,('とどなにぬねのはばぱひびぴふぶぷへべぺほ')
,('ぼぽまみむめもゃやゅゆょよらりるれろゎわ')
,('・ァアィイゥウェエォオカガキギクグケゲコ')
,('・亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵')
,('・弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞')
,('・鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻');
INSERT INTO `T3` VALUES
('・˛˚~΄΅・・・・・・・・¡¦¿・・・')
,('乚乜乣乨乩乴乵乹乿亍亖亗亝亯亹仃仐仚仛仠')
,('仡仢仨仯仱仳仵份仾仿伀伂伃伈伋伌伒伕伖众')
,('伙伮伱你伳伵伷伹伻伾佀佂佈佉佋佌佒佔佖佘')
,('・黸黿鼂鼃鼉鼏鼐鼑鼒鼔鼖鼗鼙鼚鼛鼟鼢鼦鼪')
,('鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖')
,('齗齘齚齝齞齨齩齭齮齯齰齱齳齵齺齽龏龐龑龒');
INSERT INTO `T4` VALUES
('PQRSTUVWXYZ[\\]^_')
,(' 。「」、・ヲァィゥェォャュョッ')
,('ーアイウエオカキクケコサシスセソ')
,('タチツテトナニヌネノハヒフヘホマ')
,('ミムメモヤユヨラリルレロワン゙゚');
INSERT INTO `T5` VALUES
(' 、。,.・:;?!゛゜´`¨^ ̄_ヽ')
,('ヾゝゞ〃仝々〆〇ー―‐/\〜‖|…‥‘’')
,('“”()〔〕[]{}〈〉《》「」『』【】')
,('・ぁあぃいぅうぇえぉおかがきぎくぐけげこ')
,('とどなにぬねのはばぱひびぴふぶぷへべぺほ')
,('ぼぽまみむめもゃやゅゆょよらりるれろゎわ')
,('・ァアィイゥウェエォオカガキギクグケゲコ')
,('・亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵')
,('・弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞')
,('・鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻');
INSERT INTO `T6` VALUES
('・˛˚~΄΅・・・・・・・・¡¦¿・・・')
,('乚乜乣乨乩乴乵乹乿亍亖亗亝亯亹仃仐仚仛仠')
,('仡仢仨仯仱仳仵份仾仿伀伂伃伈伋伌伒伕伖众')
,('伙伮伱你伳伵伷伹伻伾佀佂佈佉佋佌佒佔佖佘')
,('・黸黿鼂鼃鼉鼏鼐鼑鼒鼔鼖鼗鼙鼚鼛鼟鼢鼦鼪')
,('鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖')
,('齗齘齚齝齞齨齩齭齮齯齰齱齳齵齺齽龏龐龑龒');
INSERT INTO `T7` VALUES
('PQRSTUVWXYZ[\\]^_')
,(' 。「」、・ヲァィゥェォャュョッ')
,('ーアイウエオカキクケコサシスセソ')
,('タチツテトナニヌネノハヒフヘホマ')
,('ミムメモヤユヨラリルレロワン゙゚');
INSERT INTO `T8` VALUES
(' 、。,.・:;?!゛゜´`¨^ ̄_ヽ')
,('ヾゝゞ〃仝々〆〇ー―‐/\〜‖|…‥‘’')
,('“”()〔〕[]{}〈〉《》「」『』【】')
,('・ぁあぃいぅうぇえぉおかがきぎくぐけげこ')
,('とどなにぬねのはばぱひびぴふぶぷへべぺほ')
,('ぼぽまみむめもゃやゅゆょよらりるれろゎわ')
,('・ァアィイゥウェエォオカガキギクグケゲコ')
,('・亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵')
,('・弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞')
,('・鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻');
INSERT INTO `T9` VALUES
('・˛˚~΄΅・・・・・・・・¡¦¿・・・')
,('乚乜乣乨乩乴乵乹乿亍亖亗亝亯亹仃仐仚仛仠')
,('仡仢仨仯仱仳仵份仾仿伀伂伃伈伋伌伒伕伖众')
,('伙伮伱你伳伵伷伹伻伾佀佂佈佉佋佌佒佔佖佘')
,('・黸黿鼂鼃鼉鼏鼐鼑鼒鼔鼖鼗鼙鼚鼛鼟鼢鼦鼪')
,('鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖')
,('齗齘齚齝齞齨齩齭齮齯齰齱齳齵齺齽龏龐龑龒');
SELECT * FROM `T1` WHERE `C1` LIKE ' %';
C1
。「」、・ヲァィゥェォャュョッ
SELECT * FROM `T1` WHERE `C1` LIKE '% %';
C1
。「」、・ヲァィゥェォャュョッ
SELECT * FROM `T1` WHERE `C1` LIKE '% ';
C1
SELECT * FROM `T1` WHERE `C1` LIKE 'タ%';
C1
タチツテトナニヌネノハヒフヘホマ
SELECT * FROM `T1` WHERE `C1` LIKE '%ラリ%';
C1
ミムメモヤユヨラリルレロワン゙゚
SELECT * FROM `T1` WHERE `C1` LIKE '%ソ';
C1
ーアイウエオカキクケコサシスセソ
SELECT * FROM `T1` WHERE `C1` LIKE 'ーアイウエオカキクケコサシスセソ%';
C1
ーアイウエオカキクケコサシスセソ
SELECT * FROM `T1` WHERE `C1` LIKE '%ーアイウエオカキクケコサシスセソ%';
C1
ーアイウエオカキクケコサシスセソ
SELECT * FROM `T1` WHERE `C1` LIKE '%ーアイウエオカキクケコサシスセソ';
C1
ーアイウエオカキクケコサシスセソ
SELECT * FROM `T2` WHERE `C1` LIKE ' %';
C1
、。,.・:;?!゛゜´`¨^ ̄_ヽ
SELECT * FROM `T2` WHERE `C1` LIKE '% %';
C1
、。,.・:;?!゛゜´`¨^ ̄_ヽ
SELECT * FROM `T2` WHERE `C1` LIKE '% ';
C1
SELECT * FROM `T2` WHERE `C1` LIKE 'と%';
C1
とどなにぬねのはばぱひびぴふぶぷへべぺほ
SELECT * FROM `T2` WHERE `C1` LIKE '%あ%';
C1
・ぁあぃいぅうぇえぉおかがきぎくぐけげこ
SELECT * FROM `T2` WHERE `C1` LIKE '%わ';
C1
ぼぽまみむめもゃやゅゆょよらりるれろゎわ
SELECT * FROM `T2` WHERE `C1` LIKE '・ぁあぃいぅうぇえぉおかがきぎくぐけげこ%';
C1
・ぁあぃいぅうぇえぉおかがきぎくぐけげこ
SELECT * FROM `T2` WHERE `C1` LIKE '%・ぁあぃいぅうぇえぉおかがきぎくぐけげこ%';
C1
・ぁあぃいぅうぇえぉおかがきぎくぐけげこ
SELECT * FROM `T2` WHERE `C1` LIKE '%・ぁあぃいぅうぇえぉおかがきぎくぐけげこ';
C1
・ぁあぃいぅうぇえぉおかがきぎくぐけげこ
SELECT * FROM `T3` WHERE `C1` LIKE '鼫%';
C1
鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖
SELECT * FROM `T3` WHERE `C1` LIKE '%鼺%';
C1
鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖
SELECT * FROM `T3` WHERE `C1` LIKE '%齖';
C1
鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖
SELECT * FROM `T3` WHERE `C1` LIKE '鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖%';
C1
鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖
SELECT * FROM `T3` WHERE `C1` LIKE '%鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖%';
C1
鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖
SELECT * FROM `T3` WHERE `C1` LIKE '%鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖';
C1
鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖
SELECT * FROM `T4` WHERE `C1` LIKE ' %';
C1
。「」、・ヲァィゥェォャュョッ
SELECT * FROM `T4` WHERE `C1` LIKE '% %';
C1
。「」、・ヲァィゥェォャュョッ
SELECT * FROM `T4` WHERE `C1` LIKE '% ';
C1
SELECT * FROM `T4` WHERE `C1` LIKE 'タ%';
C1
タチツテトナニヌネノハヒフヘホマ
SELECT * FROM `T4` WHERE `C1` LIKE '%ラリ%';
C1
ミムメモヤユヨラリルレロワン゙゚
SELECT * FROM `T4` WHERE `C1` LIKE '%ソ';
C1
ーアイウエオカキクケコサシスセソ
SELECT * FROM `T4` WHERE `C1` LIKE 'ーアイウエオカキクケコサシスセソ%';
C1
ーアイウエオカキクケコサシスセソ
SELECT * FROM `T4` WHERE `C1` LIKE '%ーアイウエオカキクケコサシスセソ%';
C1
ーアイウエオカキクケコサシスセソ
SELECT * FROM `T4` WHERE `C1` LIKE '%ーアイウエオカキクケコサシスセソ';
C1
ーアイウエオカキクケコサシスセソ
SELECT * FROM `T5` WHERE `C1` LIKE ' %';
C1
、。,.・:;?!゛゜´`¨^ ̄_ヽ
SELECT * FROM `T5` WHERE `C1` LIKE '% %';
C1
、。,.・:;?!゛゜´`¨^ ̄_ヽ
SELECT * FROM `T5` WHERE `C1` LIKE '% ';
C1
SELECT * FROM `T5` WHERE `C1` LIKE 'と%';
C1
とどなにぬねのはばぱひびぴふぶぷへべぺほ
SELECT * FROM `T5` WHERE `C1` LIKE '%あ%';
C1
・ぁあぃいぅうぇえぉおかがきぎくぐけげこ
SELECT * FROM `T5` WHERE `C1` LIKE '%わ';
C1
ぼぽまみむめもゃやゅゆょよらりるれろゎわ
SELECT * FROM `T5` WHERE `C1` LIKE '・ぁあぃいぅうぇえぉおかがきぎくぐけげこ%';
C1
・ぁあぃいぅうぇえぉおかがきぎくぐけげこ
SELECT * FROM `T5` WHERE `C1` LIKE '%・ぁあぃいぅうぇえぉおかがきぎくぐけげこ%';
C1
・ぁあぃいぅうぇえぉおかがきぎくぐけげこ
SELECT * FROM `T5` WHERE `C1` LIKE '%・ぁあぃいぅうぇえぉおかがきぎくぐけげこ';
C1
・ぁあぃいぅうぇえぉおかがきぎくぐけげこ
SELECT * FROM `T6` WHERE `C1` LIKE '鼫%';
C1
鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖
SELECT * FROM `T6` WHERE `C1` LIKE '%鼺%';
C1
鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖
SELECT * FROM `T6` WHERE `C1` LIKE '%齖';
C1
鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖
SELECT * FROM `T6` WHERE `C1` LIKE '鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖%';
C1
鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖
SELECT * FROM `T6` WHERE `C1` LIKE '%鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖%';
C1
鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖
SELECT * FROM `T6` WHERE `C1` LIKE '%鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖';
C1
鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖
SELECT * FROM `T7` WHERE `C1` LIKE ' %';
C1
。「」、・ヲァィゥェォャュョッ
SELECT * FROM `T7` WHERE `C1` LIKE '% %';
C1
。「」、・ヲァィゥェォャュョッ
SELECT * FROM `T7` WHERE `C1` LIKE '% ';
C1
SELECT * FROM `T7` WHERE `C1` LIKE 'タ%';
C1
タチツテトナニヌネノハヒフヘホマ
SELECT * FROM `T7` WHERE `C1` LIKE '%ラリ%';
C1
ミムメモヤユヨラリルレロワン゙゚
SELECT * FROM `T7` WHERE `C1` LIKE '%ソ';
C1
ーアイウエオカキクケコサシスセソ
SELECT * FROM `T7` WHERE `C1` LIKE 'ーアイウエオカキクケコサシスセソ%';
C1
ーアイウエオカキクケコサシスセソ
SELECT * FROM `T7` WHERE `C1` LIKE '%ーアイウエオカキクケコサシスセソ%';
C1
ーアイウエオカキクケコサシスセソ
SELECT * FROM `T7` WHERE `C1` LIKE '%ーアイウエオカキクケコサシスセソ';
C1
ーアイウエオカキクケコサシスセソ
SELECT * FROM `T8` WHERE `C1` LIKE ' %';
C1
、。,.・:;?!゛゜´`¨^ ̄_ヽ
SELECT * FROM `T8` WHERE `C1` LIKE '% %';
C1
、。,.・:;?!゛゜´`¨^ ̄_ヽ
SELECT * FROM `T8` WHERE `C1` LIKE '% ';
C1
SELECT * FROM `T8` WHERE `C1` LIKE 'と%';
C1
とどなにぬねのはばぱひびぴふぶぷへべぺほ
SELECT * FROM `T8` WHERE `C1` LIKE '%あ%';
C1
・ぁあぃいぅうぇえぉおかがきぎくぐけげこ
SELECT * FROM `T8` WHERE `C1` LIKE '%わ';
C1
ぼぽまみむめもゃやゅゆょよらりるれろゎわ
SELECT * FROM `T8` WHERE `C1` LIKE '・ぁあぃいぅうぇえぉおかがきぎくぐけげこ%';
C1
・ぁあぃいぅうぇえぉおかがきぎくぐけげこ
SELECT * FROM `T8` WHERE `C1` LIKE '%・ぁあぃいぅうぇえぉおかがきぎくぐけげこ%';
C1
・ぁあぃいぅうぇえぉおかがきぎくぐけげこ
SELECT * FROM `T8` WHERE `C1` LIKE '%・ぁあぃいぅうぇえぉおかがきぎくぐけげこ';
C1
・ぁあぃいぅうぇえぉおかがきぎくぐけげこ
SELECT * FROM `T9` WHERE `C1` LIKE '鼫%';
C1
鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖
SELECT * FROM `T9` WHERE `C1` LIKE '%鼺%';
C1
鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖
SELECT * FROM `T9` WHERE `C1` LIKE '%齖';
C1
鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖
SELECT * FROM `T9` WHERE `C1` LIKE '鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖%';
C1
鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖
SELECT * FROM `T9` WHERE `C1` LIKE '%鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖%';
C1
鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖
SELECT * FROM `T9` WHERE `C1` LIKE '%鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖';
C1
鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃齄齅齆齇齓齕齖
DROP TABLE `T1`;
DROP TABLE `T2`;
DROP TABLE `T3`;
DROP TABLE `T4`;
DROP TABLE `T5`;
DROP TABLE `T6`;
DROP TABLE `T7`;
DROP TABLE `T8`;
DROP TABLE `T9`;
| {
"pile_set_name": "Github"
} |
package ecs
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DescribeClassicLinkInstances invokes the ecs.DescribeClassicLinkInstances API synchronously
// api document: https://help.aliyun.com/api/ecs/describeclassiclinkinstances.html
func (client *Client) DescribeClassicLinkInstances(request *DescribeClassicLinkInstancesRequest) (response *DescribeClassicLinkInstancesResponse, err error) {
response = CreateDescribeClassicLinkInstancesResponse()
err = client.DoAction(request, response)
return
}
// DescribeClassicLinkInstancesWithChan invokes the ecs.DescribeClassicLinkInstances API asynchronously
// api document: https://help.aliyun.com/api/ecs/describeclassiclinkinstances.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeClassicLinkInstancesWithChan(request *DescribeClassicLinkInstancesRequest) (<-chan *DescribeClassicLinkInstancesResponse, <-chan error) {
responseChan := make(chan *DescribeClassicLinkInstancesResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DescribeClassicLinkInstances(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DescribeClassicLinkInstancesWithCallback invokes the ecs.DescribeClassicLinkInstances API asynchronously
// api document: https://help.aliyun.com/api/ecs/describeclassiclinkinstances.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeClassicLinkInstancesWithCallback(request *DescribeClassicLinkInstancesRequest, callback func(response *DescribeClassicLinkInstancesResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DescribeClassicLinkInstancesResponse
var err error
defer close(result)
response, err = client.DescribeClassicLinkInstances(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DescribeClassicLinkInstancesRequest is the request struct for api DescribeClassicLinkInstances
type DescribeClassicLinkInstancesRequest struct {
*requests.RpcRequest
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
PageNumber string `position:"Query" name:"PageNumber"`
PageSize string `position:"Query" name:"PageSize"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
InstanceId string `position:"Query" name:"InstanceId"`
VpcId string `position:"Query" name:"VpcId"`
}
// DescribeClassicLinkInstancesResponse is the response struct for api DescribeClassicLinkInstances
type DescribeClassicLinkInstancesResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
TotalCount int `json:"TotalCount" xml:"TotalCount"`
PageNumber int `json:"PageNumber" xml:"PageNumber"`
PageSize int `json:"PageSize" xml:"PageSize"`
Links Links `json:"Links" xml:"Links"`
}
// CreateDescribeClassicLinkInstancesRequest creates a request to invoke DescribeClassicLinkInstances API
func CreateDescribeClassicLinkInstancesRequest() (request *DescribeClassicLinkInstancesRequest) {
request = &DescribeClassicLinkInstancesRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Ecs", "2014-05-26", "DescribeClassicLinkInstances", "ecs", "openAPI")
return
}
// CreateDescribeClassicLinkInstancesResponse creates a response to parse from DescribeClassicLinkInstances response
func CreateDescribeClassicLinkInstancesResponse() (response *DescribeClassicLinkInstancesResponse) {
response = &DescribeClassicLinkInstancesResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}
| {
"pile_set_name": "Github"
} |
[](https://gitter.im/opentracing/public) [](https://travis-ci.org/opentracing/opentracing-go) [](http://godoc.org/github.com/opentracing/opentracing-go)
# OpenTracing API for Go
This package is a Go platform API for OpenTracing.
## Required Reading
In order to understand the Go platform API, one must first be familiar with the
[OpenTracing project](http://opentracing.io) and
[terminology](http://opentracing.io/documentation/pages/spec.html) more specifically.
## API overview for those adding instrumentation
Everyday consumers of this `opentracing` package really only need to worry
about a couple of key abstractions: the `StartSpan` function, the `Span`
interface, and binding a `Tracer` at `main()`-time. Here are code snippets
demonstrating some important use cases.
#### Singleton initialization
The simplest starting point is `./default_tracer.go`. As early as possible, call
```go
import "github.com/opentracing/opentracing-go"
import ".../some_tracing_impl"
func main() {
opentracing.InitGlobalTracer(
// tracing impl specific:
some_tracing_impl.New(...),
)
...
}
```
##### Non-Singleton initialization
If you prefer direct control to singletons, manage ownership of the
`opentracing.Tracer` implementation explicitly.
#### Creating a Span given an existing Go `context.Context`
If you use `context.Context` in your application, OpenTracing's Go library will
happily rely on it for `Span` propagation. To start a new (blocking child)
`Span`, you can use `StartSpanFromContext`.
```go
func xyz(ctx context.Context, ...) {
...
span, ctx := opentracing.StartSpanFromContext(ctx, "operation_name")
defer span.Finish()
span.LogFields(
log.String("event", "soft error"),
log.String("type", "cache timeout"),
log.Int("waited.millis", 1500))
...
}
```
#### Starting an empty trace by creating a "root span"
It's always possible to create a "root" `Span` with no parent or other causal
reference.
```go
func xyz() {
...
sp := opentracing.StartSpan("operation_name")
defer sp.Finish()
...
}
```
#### Creating a (child) Span given an existing (parent) Span
```go
func xyz(parentSpan opentracing.Span, ...) {
...
sp := opentracing.StartSpan(
"operation_name",
opentracing.ChildOf(parentSpan.Context()))
defer sp.Finish()
...
}
```
#### Serializing to the wire
```go
func makeSomeRequest(ctx context.Context) ... {
if span := opentracing.SpanFromContext(ctx); span != nil {
httpClient := &http.Client{}
httpReq, _ := http.NewRequest("GET", "http://myservice/", nil)
// Transmit the span's TraceContext as HTTP headers on our
// outbound request.
opentracing.GlobalTracer().Inject(
span.Context(),
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(httpReq.Header))
resp, err := httpClient.Do(httpReq)
...
}
...
}
```
#### Deserializing from the wire
```go
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
var serverSpan opentracing.Span
appSpecificOperationName := ...
wireContext, err := opentracing.GlobalTracer().Extract(
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(req.Header))
if err != nil {
// Optionally record something about err here
}
// Create the span referring to the RPC client if available.
// If wireContext == nil, a root span will be created.
serverSpan = opentracing.StartSpan(
appSpecificOperationName,
ext.RPCServerOption(wireContext))
defer serverSpan.Finish()
ctx := opentracing.ContextWithSpan(context.Background(), serverSpan)
...
}
```
#### Goroutine-safety
The entire public API is goroutine-safe and does not require external
synchronization.
## API pointers for those implementing a tracing system
Tracing system implementors may be able to reuse or copy-paste-modify the `basictracer` package, found [here](https://github.com/opentracing/basictracer-go). In particular, see `basictracer.New(...)`.
## API compatibility
For the time being, "mild" backwards-incompatible changes may be made without changing the major version number. As OpenTracing and `opentracing-go` mature, backwards compatibility will become more of a priority.
| {
"pile_set_name": "Github"
} |
2
2
!2
!100
| {
"pile_set_name": "Github"
} |
package com.neo.remote;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* Created by summer on 2017/5/11.
*/
@FeignClient(name= "spring-cloud-producer2", fallback = HelloRemoteHystrix.class)
public interface HelloRemote {
@RequestMapping(value = "/hello")
public String hello2(@RequestParam(value = "name") String name);
}
| {
"pile_set_name": "Github"
} |
graphs
======
Description
-----------
A database of graphs. Created by Emily Kirkman based on the work of
Jason Grout. Since April 2012 it also contains the ISGCI graph database.
Upstream Contact
----------------
- For ISGCI:
H.N. de Ridder ([email protected])
- For Andries Brouwer's database:
The data is taken from from Andries E. Brouwer's website
(https://www.win.tue.nl/~aeb/). Anything related to the data should
be
reported to him directly ([email protected])
The code used to parse the data and create the .json file is
available at
https://github.com/nathanncohen/strongly_regular_graphs_database.
Dependencies
------------
N/A
| {
"pile_set_name": "Github"
} |
<linker>
<assembly fullname="Ceras" preserve="all"/>
</linker>
| {
"pile_set_name": "Github"
} |
/dts-v1/;
/ {
compatible = "test_string_escapes";
escape-str = "nastystring: \a\b\t\n\v\f\r\\\"";
escape-str-2 = "\xde\xad\xbe\xef";
};
| {
"pile_set_name": "Github"
} |
extension APIScope {
/// https://vk.com/dev/utils
public enum Utils: APIMethod {
case checkLink(Parameters)
case deleteFromLastShortened(Parameters)
case getLastShortenedLinks(Parameters)
case getLinkStats(Parameters)
case getServerTime(Parameters)
case getShortLink(Parameters)
case resolveScreenName(Parameters)
}
}
| {
"pile_set_name": "Github"
} |
---
fixes:
- |
[`bug 1833739 <https://bugs.launchpad.net/keystone/+bug/1833739>`_]
Fix PostgreSQL specifc issue with storing encrypted credentials. In
Python 3 the psycopg2 module treats bytes strings as binary data. This
causes issues when storing encrypted credentials in the Database.
To fix this isseu the credentials sql backend is updated to encode the
credential into a text string before handing it over to the database.
| {
"pile_set_name": "Github"
} |
require('./modules/es5');
require('./modules/es6.symbol');
require('./modules/es6.object.assign');
require('./modules/es6.object.is');
require('./modules/es6.object.set-prototype-of');
require('./modules/es6.object.to-string');
require('./modules/es6.object.freeze');
require('./modules/es6.object.seal');
require('./modules/es6.object.prevent-extensions');
require('./modules/es6.object.is-frozen');
require('./modules/es6.object.is-sealed');
require('./modules/es6.object.is-extensible');
require('./modules/es6.object.get-own-property-descriptor');
require('./modules/es6.object.get-prototype-of');
require('./modules/es6.object.keys');
require('./modules/es6.object.get-own-property-names');
require('./modules/es6.function.name');
require('./modules/es6.function.has-instance');
require('./modules/es6.number.constructor');
require('./modules/es6.number.epsilon');
require('./modules/es6.number.is-finite');
require('./modules/es6.number.is-integer');
require('./modules/es6.number.is-nan');
require('./modules/es6.number.is-safe-integer');
require('./modules/es6.number.max-safe-integer');
require('./modules/es6.number.min-safe-integer');
require('./modules/es6.number.parse-float');
require('./modules/es6.number.parse-int');
require('./modules/es6.math.acosh');
require('./modules/es6.math.asinh');
require('./modules/es6.math.atanh');
require('./modules/es6.math.cbrt');
require('./modules/es6.math.clz32');
require('./modules/es6.math.cosh');
require('./modules/es6.math.expm1');
require('./modules/es6.math.fround');
require('./modules/es6.math.hypot');
require('./modules/es6.math.imul');
require('./modules/es6.math.log10');
require('./modules/es6.math.log1p');
require('./modules/es6.math.log2');
require('./modules/es6.math.sign');
require('./modules/es6.math.sinh');
require('./modules/es6.math.tanh');
require('./modules/es6.math.trunc');
require('./modules/es6.string.from-code-point');
require('./modules/es6.string.raw');
require('./modules/es6.string.trim');
require('./modules/es6.string.iterator');
require('./modules/es6.string.code-point-at');
require('./modules/es6.string.ends-with');
require('./modules/es6.string.includes');
require('./modules/es6.string.repeat');
require('./modules/es6.string.starts-with');
require('./modules/es6.array.from');
require('./modules/es6.array.of');
require('./modules/es6.array.iterator');
require('./modules/es6.array.species');
require('./modules/es6.array.copy-within');
require('./modules/es6.array.fill');
require('./modules/es6.array.find');
require('./modules/es6.array.find-index');
require('./modules/es6.regexp.constructor');
require('./modules/es6.regexp.flags');
require('./modules/es6.regexp.match');
require('./modules/es6.regexp.replace');
require('./modules/es6.regexp.search');
require('./modules/es6.regexp.split');
require('./modules/es6.promise');
require('./modules/es6.map');
require('./modules/es6.set');
require('./modules/es6.weak-map');
require('./modules/es6.weak-set');
require('./modules/es6.reflect.apply');
require('./modules/es6.reflect.construct');
require('./modules/es6.reflect.define-property');
require('./modules/es6.reflect.delete-property');
require('./modules/es6.reflect.enumerate');
require('./modules/es6.reflect.get');
require('./modules/es6.reflect.get-own-property-descriptor');
require('./modules/es6.reflect.get-prototype-of');
require('./modules/es6.reflect.has');
require('./modules/es6.reflect.is-extensible');
require('./modules/es6.reflect.own-keys');
require('./modules/es6.reflect.prevent-extensions');
require('./modules/es6.reflect.set');
require('./modules/es6.reflect.set-prototype-of');
require('./modules/es7.array.includes');
require('./modules/es7.string.at');
require('./modules/es7.string.pad-left');
require('./modules/es7.string.pad-right');
require('./modules/es7.string.trim-left');
require('./modules/es7.string.trim-right');
require('./modules/es7.regexp.escape');
require('./modules/es7.object.get-own-property-descriptors');
require('./modules/es7.object.values');
require('./modules/es7.object.entries');
require('./modules/es7.map.to-json');
require('./modules/es7.set.to-json');
require('./modules/js.array.statics');
require('./modules/web.timers');
require('./modules/web.immediate');
require('./modules/web.dom.iterable');
module.exports = require('./modules/$.core'); | {
"pile_set_name": "Github"
} |
\section{svchost}
\begin{verbatim}
appmgr_svc是通向appmgr的通信通道。
outgoing.ServeFromStartupInfo()
Serve(zx::channel(dir_request));
vfs_.ServeDirectory(root_dir_, fbl::move(dir_request));
OpenVnode(flags, &vn)
(*vnode)->Open(flags, &redirect);
PseudoDir::Open()不做事
vn->Serve(this, fbl::move(channel), ZX_FS_RIGHT_ADMIN)
vfs->ServeConnection(fbl::make_unique<Connection>(
vfs, fbl::WrapRefPtr(this), fbl::move(channel), flags));
connection->Serve();
wait_.set_object(channel_.get());
wait_.Begin(vfs_->async());
async_begin_wait(async, &wait_);
async->ops->v1.begin_wait(async, wait);
zx_object_wait_async(wait->object, loop->port, (uintptr_t)wait, wait->trigger, ZX_WAIT_ASYNC_ONCE);
让root dir监听进来的请求
provider_load(&service_providers[i], async, outgoing.public_dir());
provider_init(instance);
init == nullptr
provider_publish(instance, async, dir)
dir->AddEntry(
service_name,
fbl::MakeRefCounted<fs::Service>([instance, async, service_name](zx::channel request) {
return instance->provider->ops->connect(instance->ctx, async, service_name, request.release());
}));
当有连接请求进来时:
new launcher::LauncherImpl(zx::channel(request));
channel_(fbl::move(channel)),
wait_(this, channel_.get(), ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED)
launcher->Begin(async);
wait_.Begin(async);
\end{verbatim} | {
"pile_set_name": "Github"
} |
import { cornerstone, cornerstoneWADOImageLoader } from '../../cornerstonejs';
import { StackManager } from '../StackManager';
import { DCMViewerManager } from '../../DCMViewerManager';
import { DCMViewerLog } from '../../DCMViewerLog';
class BaseLoadingListener {
constructor(stack, options) {
options = options || {};
this.id = BaseLoadingListener.getNewId();
this.stack = stack;
this.startListening();
this.statsItemsLimit = options.statsItemsLimit || 2;
this.stats = {
items: [],
total: 0,
elapsedTime: 0,
speed: 0
};
// Register the start point to make it possible to calculate
// bytes/s or frames/s when the first byte or frame is received
this._addStatsData(0);
// Update the progress before starting the download
// to make it possible to update the UI
this._updateProgress();
}
_addStatsData(value) {
const date = new Date();
const { stats } = this;
const { items } = stats;
const newItem = {
value,
date
};
items.push(newItem);
stats.total += newItem.value;
// Remove items until it gets below the limit
while (items.length > this.statsItemsLimit) {
const item = items.shift();
stats.total -= item.value;
}
// Update the elapsedTime (seconds) based on first and last
// elements and recalculate the speed (bytes/s or frames/s)
if (items.length > 1) {
const oldestItem = items[0];
stats.elapsedTime = (newItem.date.getTime() - oldestItem.date.getTime()) / 1000;
stats.speed = (stats.total - oldestItem.value) / stats.elapsedTime;
}
}
_getProgressSessionId() {
const { displaySetInstanceUid } = this.stack;
return `StackProgress:${displaySetInstanceUid}`;
}
_clearSession() {
const progressSessionId = this._getProgressSessionId();
DCMViewerManager.sessions[progressSessionId] = undefined;
delete DCMViewerManager.sessions[progressSessionId];
}
startListening() {
throw new Error('`startListening` must be implemented by child clases');
}
stopListening() {
throw new Error('`stopListening` must be implemented by child clases');
}
destroy() {
this.stopListening();
this._clearSession();
}
static getNewId() {
const timeSlice = (new Date()).getTime().toString().slice(-8);
const randomNumber = parseInt(Math.random() * 1000000000, 10);
return timeSlice.toString() + randomNumber.toString();
}
}
class DICOMFileLoadingListener extends BaseLoadingListener {
constructor(stack) {
super(stack);
this._dataSetUrl = this._getDataSetUrl(stack);
this._lastLoaded = 0;
// Check how many instances has already been download (cached)
this._checkCachedData();
}
_checkCachedData() {
const dataSet = cornerstoneWADOImageLoader.wadouri.dataSetCacheManager.get(this._dataSetUrl);
if (dataSet) {
const dataSetLength = dataSet.byteArray.length;
this._updateProgress({
percentComplete: 100,
loaded: dataSetLength,
total: dataSetLength
});
}
}
_getImageLoadProgressEventName() {
return `cornerstoneimageloadprogress.${this.id}`;
}
startListening() {
const imageLoadProgressEventName = this._getImageLoadProgressEventName();
const imageLoadProgressEventHandle = this._imageLoadProgressEventHandle.bind(this);
this.stopListening();
cornerstone.events.addEventListener(imageLoadProgressEventName, imageLoadProgressEventHandle);
}
stopListening() {
const imageLoadProgressEventName = this._getImageLoadProgressEventName();
cornerstone.events.removeEventListener(imageLoadProgressEventName);
}
_imageLoadProgressEventHandle(e) {
const eventData = e.detail;
const dataSetUrl = this._convertImageIdToDataSetUrl(eventData.imageId);
const bytesDiff = eventData.loaded - this._lastLoaded;
if (!this._dataSetUrl === dataSetUrl) {
return;
}
// Add the bytes downloaded to the stats
this._addStatsData(bytesDiff);
// Update the download progress
this._updateProgress(eventData);
// Cache the last eventData.loaded value
this._lastLoaded = eventData.loaded;
}
_updateProgress(eventData) {
const progressSessionId = this._getProgressSessionId();
eventData = eventData || {};
DCMViewerManager.sessions[progressSessionId] = {
multiFrame: false,
percentComplete: eventData.percentComplete,
bytesLoaded: eventData.loaded,
bytesTotal: eventData.total,
bytesPerSecond: this.stats.speed
};
}
_convertImageIdToDataSetUrl(imageId) {
// Remove the prefix ("dicomweb:" or "wadouri:"")
imageId = imageId.replace(/^(dicomweb:|wadouri:)/i, '');
// Remove "frame=999&" from the imageId
imageId = imageId.replace(/frame=\d+&?/i, '');
// Remove the last "&" like in "http://...?foo=1&bar=2&"
imageId = imageId.replace(/&$/, '');
return imageId;
}
_getDataSetUrl(stack) {
const imageId = stack.imageIds[0];
return this._convertImageIdToDataSetUrl(imageId);
}
}
class StackLoadingListener extends BaseLoadingListener {
constructor(stack) {
super(stack, { statsItemsLimit: 20 });
this.imageDataMap = this._convertImageIdsArrayToMap(stack.imageIds);
this.framesStatus = this._createArray(stack.imageIds.length, false);
this.loadedCount = 0;
// Check how many instances has already been download (cached)
this._checkCachedData();
}
_convertImageIdsArrayToMap(imageIds) {
const imageIdsMap = new Map();
for (let i = 0; i < imageIds.length; i++) {
imageIdsMap.set(imageIds[i], {
index: i,
loaded: false
});
}
return imageIdsMap;
}
_createArray(length, defaultValue) {
// `new Array(length)` is an anti-pattern in javascript because its
// funny API. Otherwise I would go for `new Array(length).fill(false)`
const array = [];
for (let i = 0; i < length; i++) {
array[i] = defaultValue;
}
return array;
}
_checkCachedData() {
// const imageIds = this.stack.imageIds;
// TODO: No way to check status of Promise.
/* for(let i = 0; i < imageIds.length; i++) {
const imageId = imageIds[i];
const imagePromise = cornerstone.imageCache.getImageLoadObject(imageId).promise;
if (imagePromise && (imagePromise.state() === 'resolved')) {
this._updateFrameStatus(imageId, true);
}
} */
}
_getImageLoadedEventName() {
return `cornerstoneimageloaded.${this.id}`;
}
_getImageCachePromiseRemoveEventName() {
return `cornerstoneimagecachepromiseremoved.${this.id}`;
}
startListening() {
const imageLoadedEventName = this._getImageLoadedEventName();
const imageCachePromiseRemovedEventName = this._getImageCachePromiseRemoveEventName();
const imageLoadedEventHandle = this._imageLoadedEventHandle.bind(this);
const imageCachePromiseRemovedEventHandle = this._imageCachePromiseRemovedEventHandle.bind(this);
this.stopListening();
cornerstone.events.addEventListener(imageLoadedEventName, imageLoadedEventHandle);
cornerstone.events.addEventListener(imageCachePromiseRemovedEventName, imageCachePromiseRemovedEventHandle);
}
stopListening() {
const imageLoadedEventName = this._getImageLoadedEventName();
const imageCachePromiseRemovedEventName = this._getImageCachePromiseRemoveEventName();
cornerstone.events.removeEventListener(imageLoadedEventName);
cornerstone.events.removeEventListener(imageCachePromiseRemovedEventName);
}
_updateFrameStatus(imageId, loaded) {
const imageData = this.imageDataMap.get(imageId);
if (!imageData || (imageData.loaded === loaded)) {
return;
}
// Add one more frame to the stats
if (loaded) {
this._addStatsData(1);
}
imageData.loaded = loaded;
this.framesStatus[imageData.index] = loaded;
this.loadedCount += loaded ? 1 : -1;
this._updateProgress();
}
_imageLoadedEventHandle(e) {
this._updateFrameStatus(e.detail.image.imageId, true);
}
_imageCachePromiseRemovedEventHandle(e) {
this._updateFrameStatus(e.detail.imageId, false);
}
_updateProgress() {
const totalFramesCount = this.stack.imageIds.length;
const loadedFramesCount = this.loadedCount;
const loadingFramesCount = totalFramesCount - loadedFramesCount;
const percentComplete = Math.round((loadedFramesCount / totalFramesCount) * 100);
const progressSessionId = this._getProgressSessionId();
DCMViewerManager.sessions[progressSessionId] = {
multiFrame: true,
totalFramesCount,
loadedFramesCount,
loadingFramesCount,
percentComplete,
framesPerSecond: this.stats.speed,
framesStatus: this.framesStatus
};
}
_logProgress() {
const totalFramesCount = this.stack.imageIds.length;
const { displaySetInstanceUid } = this.stack;
let progressBar = '[';
for (let i = 0; i < totalFramesCount; i++) {
const ch = this.framesStatus[i] ? '|' : '.';
progressBar += `${ch}`;
}
progressBar += ']';
DCMViewerLog.info(`${displaySetInstanceUid}: ${progressBar}`);
}
}
class StudyLoadingListener {
constructor() {
this.listeners = {};
}
addStack(stack, stackMetaData) {
const { displaySetInstanceUid } = stack;
if (!this.listeners[displaySetInstanceUid]) {
const listener = this._createListener(stack, stackMetaData);
if (listener) {
this.listeners[displaySetInstanceUid] = listener;
}
}
}
addStudy(study) {
study.displaySets.forEach((displaySet) => {
const stack = StackManager.findOrCreateStack(study, displaySet);
this.addStack(stack, {
isMultiFrame: displaySet.isMultiFrame
});
});
}
addStudies(studies) {
if (!studies || !studies.length) {
return;
}
for (let i = 0; i < studies.length; i++) {
this.addStudy(studies[i]);
}
}
clear() {
const displaySetInstanceUids = Object.keys(this.listeners);
const { length } = displaySetInstanceUids;
for (let i = 0; i < length; i++) {
const displaySetInstanceUid = displaySetInstanceUids[i];
const displaySet = this.listeners[displaySetInstanceUid];
displaySet.destroy();
}
this.listeners = {};
}
_createListener(stack, stackMetaData) {
const schema = this._getSchema(stack);
// A StackLoadingListener can be created if it's wadors or not a multiframe
// wadouri instance (single file) that means "N" files will have to be
// downloaded where "N" is the number of frames. DICOMFileLoadingListener
// is created only if it's a single DICOM file and there's no way to know
// how many frames has already been loaded (bytes/s instead of frames/s).
if ((schema === 'wadors') || !stackMetaData.isMultiFrame) {
return new StackLoadingListener(stack);
}
return new DICOMFileLoadingListener(stack);
}
_getSchema(stack) {
const imageId = stack.imageIds[0];
const colonIndex = imageId.indexOf(':');
return imageId.substring(0, colonIndex);
}
// Singleton
static getInstance() {
if (!StudyLoadingListener._instance) {
StudyLoadingListener._instance = new StudyLoadingListener();
}
return StudyLoadingListener._instance;
}
}
export { StudyLoadingListener, StackLoadingListener, DICOMFileLoadingListener };
| {
"pile_set_name": "Github"
} |
/////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2006-2013
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/intrusive for documentation.
//
/////////////////////////////////////////////////////////////////////////////
#if defined BOOST_MSVC
#pragma warning (pop)
#endif
| {
"pile_set_name": "Github"
} |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/native.R
\name{native_areas}
\alias{native_areas}
\title{Download an American Indian / Alaska Native / Native Hawaiian Areas shapefile into R.}
\usage{
native_areas(cb = FALSE, year = NULL, ...)
}
\arguments{
\item{cb}{If cb is set to TRUE, download a generalized (1:500k)
file. Defaults to FALSE (the most detailed TIGER/Line file)}
\item{year}{the data year (defaults to 2019).}
\item{...}{arguments to be passed to the underlying `load_tiger` function, which is not exported.
Options include \code{class}, which can be set to \code{"sf"} (the default) or \code{"sp"} to
request sf or sp class objects, and \code{refresh}, which specifies whether or
not to re-download shapefiles (defaults to \code{FALSE}).}
}
\description{
Description from the Census Bureau: "This shapefile contain both legal and statistical
American Indian, Alaska Native, and Native Hawaiian
entities for which the Census Bureau publishes data. The legal entities consist of federally recognized
American Indian reservations and off-reservation trust land areas, state-recognized American Indian
reservations, and Hawaiian home lands (HHLs)." For more information, please see the link provided.
}
\examples{
\dontrun{
library(tigris)
library(ggplot2)
library(ggthemes)
nat <- native_areas(cb = TRUE)
gg <- ggplot()
gg <- gg + geom_sf(data = nat, color="black", fill="white", size=0.25)
gg <- gg + coord_sf(xlim=c(-179.1506, -129.9795), # alaska
ylim=c(51.2097, 71.4410))
gg <- gg + theme_map()
gg
}
}
\seealso{
\url{https://www2.census.gov/geo/pdfs/reference/GARM/Ch5GARM.pdf}
Other native/tribal geometries functions:
\code{\link{alaska_native_regional_corporations}()},
\code{\link{tribal_block_groups}()},
\code{\link{tribal_census_tracts}()},
\code{\link{tribal_subdivisions_national}()}
}
\concept{native/tribal geometries functions}
| {
"pile_set_name": "Github"
} |
//
// DDMainWindowController.h
// Duoduo
//
// Created by zuoye on 13-11-28.
// Copyright (c) 2013年 zuoye. All rights reserved.
//
#import "DDWindowController.h"
#import "EGOImageView.h"
#import "FMSearchTokenField.h"
#import "DDSearchFieldEditorDelegate.h"
#import "DDLeftBarViewController.h"
#import "DDRecentContactsViewController.h"
#import "DDGroupViewController.h"
#import "DDIntranetViewController.h"
#import "DDIntranetContentViewController.h"
@class DDLeftBarViewController;
@class DDSplitView;
@class DDChattingViewController,DDMainWindowControllerModule;
@interface DDMainWindowController : DDWindowController<
NSUserNotificationCenterDelegate,
NSSplitViewDelegate,
DDLeftBarViewControllerDelegate,
DDRecentContactsViewControllerDelegate,
DDGroupViewControllerDelegate,
DDIntranetViewControllerDelegate>{
DDChattingViewController *_currentChattingViewController;
DDIntranetContentViewController* _intranetContentViewController;
NSStatusItem* _statusItem; //状态栏图标
NSMenu *onlineStateMenu;
NSInteger preOnlineMenuTag;
}
@property (nonatomic,weak) IBOutlet DDLeftBarViewController* leftBarViewController;
@property (nonatomic,strong)DDMainWindowControllerModule* module;
@property (nonatomic,weak) IBOutlet NSView *firstColumnView;
@property (nonatomic,weak) IBOutlet DDSplitView *mainSplitView;
@property (nonatomic,weak) IBOutlet NSView *chattingBackgroudView;
@property (nonatomic,weak) IBOutlet FMSearchTokenField *searchField;
@property (nonatomic,strong) IBOutlet DDSearchFieldEditorDelegate *searchFieldDelegate;
+ (instancetype)instance;
- (IBAction)showMyInfo:(id)sender;
/**
* 开始一个和用户的聊天会话,如果会话不存在会建立新的会话,并且刷新界面
*
* @param userID 用户ID
*/
- (void)openUserChatWithUser:(NSString*)userID;
/**
* 开始一个和群的聊天会话,如果会话不存在会简历新的会话,并且刷新界面
*
* @param groupID 群ID
*/
- (void)openGroupChatWithGroup:(NSString*)groupID;
/**
* 开始一个已存在的会话
*
* @param sessionID 会话ID
*/
- (void)openSessionChatWithSessionID:(NSString*)sessionID;
-(void)notifyUserNewMsg:(NSString*)sid title:(NSString*)title content:(NSString*)content;
- (void)notifyIntranetMessageWithTitle:(NSString*)title content:(NSString*)content;
-(void)renderTotalUnreadedCount:(NSUInteger)count;
- (void)recentContactsSelectObject:(NSString*)sessionID;
- (void)shakeTheWindow;
- (void)leftChangeUseravatar:(NSImage*)image;
@end
| {
"pile_set_name": "Github"
} |
/* ----------------------------------------------------------
Octree Textures on the GPU - source code - GPU Gems 2 release
2004-11-21
Updates on http://www.aracknea.net/octreetex
--
(c) 2004 Sylvain Lefebvre - all rights reserved
--
The source code is provided 'as it is', without any warranties.
Use at your own risk. The use of any part of the source code in a
commercial or non commercial product without explicit authorisation
from the author is forbidden. Use for research and educational
purposes is allowed and encouraged, provided that a short notice
acknowledges the author's work.
---------------------------------------------------------- */
// -------------------------------------------------------------------------
#include "CVertex.h"
#include <GL/gl.h>
#include <cmath>
// -------------------------------------------------------------------------
#ifndef ABS
#define ABS(x) ((x)>0?(x):(-(x)))
#endif /* ABS */
// -------------------------------------------------------------------------
inline CVertex::CVertex()
{
m_dX = m_dY = m_dZ = 0.0;
}
// -------------------------------------------------------------------------
inline CVertex::CVertex(const vertex_real &x_,
const vertex_real &y_,
const vertex_real &z_)
{
m_dX = x_;
m_dY = y_;
m_dZ = z_;
}
// -------------------------------------------------------------------------
inline CVertex::CVertex(const vertex_real &x_,
const vertex_real &y_)
{
m_dX = x_;
m_dY = y_;
m_dZ = 0.0;
}
// -------------------------------------------------------------------------
inline vertex_real CVertex::dot(const CVertex &a) const
{
return (a.m_dX * m_dX + a.m_dY * m_dY + a.m_dZ * m_dZ);
}
// -------------------------------------------------------------------------
inline CVertex operator+(const CVertex &a,const CVertex &b)
{
return CVertex(a.m_dX + b.m_dX, a.m_dY + b.m_dY, a.m_dZ + b.m_dZ);
}
// -------------------------------------------------------------------------
inline CVertex operator-(const CVertex &a,
const CVertex &b)
{
return CVertex(a.m_dX - b.m_dX, a.m_dY - b.m_dY, a.m_dZ - b.m_dZ);
}
// -------------------------------------------------------------------------
inline CVertex operator-(const CVertex &p)
{
return CVertex(-p.m_dX, -p.m_dY, -p.m_dZ);
}
// -------------------------------------------------------------------------
inline CVertex operator*(const vertex_real& d,
const CVertex &p)
{
return CVertex(d * p.m_dX, d * p.m_dY, d * p.m_dZ);
}
// -------------------------------------------------------------------------
inline CVertex operator*(const CVertex &p,
const vertex_real& d)
{
return (d * p);
}
// -------------------------------------------------------------------------
inline CVertex operator*(const vertex_real m[4][4], const CVertex& b)
{
return (CVertex(m[0][0]*b.x()+m[1][0]*b.y()+m[2][0]*b.z()+m[3][0],
m[0][1]*b.x()+m[1][1]*b.y()+m[2][1]*b.z()+m[3][1],
m[0][2]*b.x()+m[1][2]*b.y()+m[2][2]*b.z()+m[3][2]));
}
// -------------------------------------------------------------------------
inline CVertex operator*(const vertex_real *m, const CVertex& b)
{
return (CVertex(m[0]*b.x()+m[4]*b.y()+m[8]*b.z()+m[12],
m[1]*b.x()+m[5]*b.y()+m[9]*b.z()+m[13],
m[2]*b.x()+m[6]*b.y()+m[10]*b.z()+m[14]));
}
// -------------------------------------------------------------------------
inline CVertex CVertex::normMult(const vertex_real m[4][4])
{
return (CVertex(m[0][0]*x()+m[1][0]*y()+m[2][0]*z(),
m[0][1]*x()+m[1][1]*y()+m[2][1]*z(),
m[0][2]*x()+m[1][2]*y()+m[2][2]*z()));
}
// -------------------------------------------------------------------------
inline CVertex CVertex::normMult(const vertex_real *m)
{
return (CVertex(m[0]*x()+m[4]*y()+m[8]*z(),
m[1]*x()+m[5]*y()+m[9]*z(),
m[2]*x()+m[6]*y()+m[10]*z()));
}
// -------------------------------------------------------------------------
inline CVertex operator/(const CVertex &p,
const vertex_real& d)
{
return CVertex(p.m_dX / d, p.m_dY / d, p.m_dZ / d);
}
// -------------------------------------------------------------------------
inline vertex_real operator*(const CVertex &a,
const CVertex &b)
{
return (a.dot(b));
}
// -------------------------------------------------------------------------
inline int operator==(const CVertex &a, const CVertex &b)
{
return (ABS(b.m_dX-a.m_dX) < CVertex::getEpsilon()
&& ABS(b.m_dY-a.m_dY) < CVertex::getEpsilon()
&& ABS(b.m_dZ-a.m_dZ) < CVertex::getEpsilon());
}
// -------------------------------------------------------------------------
inline CVertex CVertex::vect(const CVertex &p) const
{
return CVertex(m_dY * p.m_dZ - p.m_dY * m_dZ, m_dZ * p.m_dX - p.m_dZ * m_dX, m_dX * p.m_dY - p.m_dX * m_dY);
}
// -------------------------------------------------------------------------
inline CVertex CVertex::cross(const CVertex &p) const
{
return (vect(p));
}
// -------------------------------------------------------------------------
inline vertex_real CVertex::getEpsilon()
{
return (s_dEpsilon);
}
// -------------------------------------------------------------------------
inline void CVertex::setEpsilon(const vertex_real& e)
{
if (e > 0.0)
s_dEpsilon=e;
else
throw CLibOctreeGPUException("CVertex: epsilon should be greater than 0.0 in CVertex::setEpsilon");
}
// -------------------------------------------------------------------------
inline void CVertex::gl() const
{
glVertex3d(m_dX,m_dY,m_dZ);
}
// -------------------------------------------------------------------------
inline vertex_real& CVertex::operator[](int i)
{
switch (i)
{
case 0: return (m_dX);
case 1: return (m_dY);
case 2: return (m_dZ);
default: throw CLibOctreeGPUException("CVertex: index out of range in CVertex::[]");
}
}
// -------------------------------------------------------------------------
inline const vertex_real& CVertex::operator[](int i) const
{
switch (i)
{
case 0: return (m_dX);
case 1: return (m_dY);
case 2: return (m_dZ);
default: throw CLibOctreeGPUException("CVertex: index out of range in CVertex::[]");
}
}
// -------------------------------------------------------------------------
inline void CVertex::axis(CVertex& u,CVertex& v) const
{
u.set(-y(),x(),0.0);
if (u.norme() < CVertex::getEpsilon())
{
u.set(z(),0.0,-x());
if (u.norme() < CVertex::getEpsilon())
throw CLibOctreeGPUException("CVertex: can't create axis");
}
u.unit();
v=vect(u);
v.unit();
}
// -------------------------------------------------------------------------
inline void CVertex::operator+=(const CVertex& a)
{
*this = *this + a;
}
// -------------------------------------------------------------------------
inline void CVertex::operator*=(const vertex_real& d)
{
*this = (*this) * d;
}
// -------------------------------------------------------------------------
inline void CVertex::operator/=(const vertex_real& d)
{
*this = *this / d;
}
// ---------------------------------------------------------------
inline vertex_real CVertex::normalize()
{
vertex_real tmp = (vertex_real)sqrt(m_dX * m_dX + m_dY * m_dY + m_dZ * m_dZ);
if (tmp < CVertex::s_dEpsilon)
throw CLibOctreeGPUException("CVertex: cannot normalize zero length vector in CVertex::unit");
m_dX /= tmp;
m_dY /= tmp;
m_dZ /= tmp;
return (tmp);
}
// -------------------------------------------------------------------------
inline std::ostream& operator<<(std::ostream& s,const CVertex& v)
{
return (s << "(" << v.x() << "," << v.y() << "," << v.z() << ")");
}
// -------------------------------------------------------------------------
inline std::istream& operator>>(std::istream& s,CVertex& v)
{
int i;
vertex_real d[3];
char c;
s >> c;
if (c == '(')
{
for (i=0;i<3;i++)
{
s >> d[i] >> c;
if (i < 2 && c != ',')
s.clear(std::ios::badbit);
else if (i == 2 && c != ')')
s.clear(std::ios::badbit);
}
}
else
{
s.clear(std::ios::badbit);
}
if (s)
v.set(d[0],d[1],d[2]);
else
throw CLibOctreeGPUException("CVertex::>> syntax error !");
return (s);
}
// -------------------------------------------------------------------------
| {
"pile_set_name": "Github"
} |
document {
Key => {weightRange,(weightRange,RingElement),(weightRange,List,RingElement)},
Headline => "the pair of lowest and highest weights of the monomials",
SYNOPSIS (
Usage => "(lo,hi) = weightRange(w,f)",
Inputs => {
"w" => List => "of integers, the weight of each variable",
"f" => RingElement => "in a polynomial ring"
},
Outputs => {
"lo" => ZZ => {"the least weight of the monomials of ", TT "f"},
"hi" => ZZ => {"the greatest weight of the monomials of ", TT "f"}
},
"The weight of a monomial is the dot product of w and the exponent vector.
If the weight vector has length smaller than the number of variables,
the other variables are assumed to have weight zero. If there are too many weights
given, the extras are silently ignored.",
EXAMPLE {
"R = QQ[a..g]",
"f = a^3+b^2*c+3*f^10*d-1+e-e",
"weightRange({1,1,0,0,0,0,0},f)",
},
"Use ", TO terms, " and ", TO weightRange, " together to select the terms
which have a given weight.",
EXAMPLE {
"f = a^2*b+3*a^2*c+b*c+1",
"sum select(terms f, t -> (weightRange({1,0},t))#0 == 2)"
},
"If the coefficient ring is a polynomial ring, one can use the weights
of these variables too. The order of weights is the same as the order of variables (see ", TO index, ")",
EXAMPLE {
"S = R[x,y];",
"weightRange({0,0,3,7},a*x^2+b*x*y)"
},
),
SYNOPSIS (
Usage => "(lo,hi) = weightRange f",
Inputs => {
"f" => RingElement
},
Outputs => {
"lo" => ZZ => {"the minimum value for (the first component of) the degrees
of the monomials occurring in ", TT "f" },
"hi" => ZZ => {"the corresponding maximum value" }
},
EXAMPLE lines ///
R = QQ[x,y];
weightRange (x^3+y^2)^5
///
),
SeeAlso => {degree, homogenize, part, index}
}
TEST ///
R = QQ[a..d]
f = a^3*b+c^4+d^2-d
assert((0,4) == weightRange({1,1,0,0},f))
S = R[x,y]
f = a*x+b*y
assert((1,2) == weightRange({1,2,0,0,0,0},f))
assert((1,2) == weightRange({1,2},f))
assert((1,2) == weightRange({1,2,0,0,0,0,231,12312,132,3212,2,123,12123,23},f))
(34489274,534535353) == weightRange({34489274,534535353},f)
weightRange({0,0,3,7,1},f)
///
| {
"pile_set_name": "Github"
} |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.discovery.indexobject.factory;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrInputDocument;
import org.dspace.core.Context;
import org.dspace.discovery.IndexableObject;
/**
* Basis factory interface for indexing/retrieving any IndexableObject in the search core
*
* @author Kevin Van de Velde (kevin at atmire dot com)
*/
public interface IndexFactory<T extends IndexableObject, S> {
/**
* Retrieve all instances of a certain indexable object type
* @param context DSpace context object
* @return An iterator containing all the objects to be indexed for the indexable object
* @throws SQLException If database error
*/
Iterator<T> findAll(Context context) throws SQLException;
/**
* Return the type of the indexable object
* @return a string containing the type
*/
String getType();
/**
* Create solr document with all the shared fields initialized.
* @param indexableObject the indexableObject that we want to index
* @return initialized solr document
*/
SolrInputDocument buildDocument(Context context, T indexableObject) throws SQLException, IOException;
/**
* Write the provided document to the solr core
* @param context DSpace context object
* @param indexableObject The indexable object that we want to store in the search core
* @param solrInputDocument Solr input document which will be written to our discovery search core
* @throws SQLException If database error
* @throws IOException If IO error
* @throws SolrServerException If the solr document could not be written to the search core
*/
void writeDocument(Context context, T indexableObject, SolrInputDocument solrInputDocument)
throws SQLException, IOException, SolrServerException;
/**
* Remove the provided indexable object from the solr core
* @param indexableObject The indexable object that we want to remove from the search core
* @throws IOException If IO error
* @throws SolrServerException If the solr document could not be removed to the search core
*/
void delete(T indexableObject) throws IOException, SolrServerException;
/**
* Remove the provided indexable object from the solr core
* @param indexableObjectIdentifier The identifier that we want to remove from the search core
* @throws IOException If IO error
* @throws SolrServerException If the solr document could not be removed to the search core
*/
void delete(String indexableObjectIdentifier) throws IOException, SolrServerException;
/**
* Remove all indexable objects of the implementing type from the search core
* @throws IOException If IO error
* @throws SolrServerException If the solr document could not be removed to the search core
*/
void deleteAll() throws IOException, SolrServerException;
/**
* Retrieve a single indexable object using the provided identifier
* @param context DSpace context object
* @param id The identifier for which we want to retrieve our indexable object
* @return An indexable object
* @throws SQLException If database error
*/
Optional<T> findIndexableObject(Context context, String id) throws SQLException;
/**
* Determine whether the class can handle the factory implementation
* @param object The object which we want to check
* @return True if the factory implementation can handle the given object. False if it doesn't.
*/
boolean supports(Object object);
/**
* Retrieve all the indexable objects for the provided object
* @param context DSpace context object
* @param object The object we want to retrieve our indexable objects for
* @return A list of indexable objects
* @throws SQLException If database error
*/
List getIndexableObjects(Context context, S object) throws SQLException;
} | {
"pile_set_name": "Github"
} |
// Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2008 Steven Watanabe
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_UNITS_SPECIFIC_HEAT_CAPACITY_DERIVED_DIMENSION_HPP
#define BOOST_UNITS_SPECIFIC_HEAT_CAPACITY_DERIVED_DIMENSION_HPP
#include <boost/units/derived_dimension.hpp>
#include <boost/units/physical_dimensions/length.hpp>
#include <boost/units/physical_dimensions/time.hpp>
#include <boost/units/physical_dimensions/temperature.hpp>
namespace boost {
namespace units {
/// derived dimension for specific heat capacity : L^2 T^-2 Theta^-1
typedef derived_dimension<length_base_dimension,2,
time_base_dimension,-2,
temperature_base_dimension,-1>::type specific_heat_capacity_dimension;
} // namespace units
} // namespace boost
#endif // BOOST_UNITS_SPECIFIC_HEAT_CAPACITY_DERIVED_DIMENSION_HPP
| {
"pile_set_name": "Github"
} |
// <auto-generated>
// Do not edit this file yourself!
//
// This code was generated by Stride Shader Mixin Code Generator.
// To generate it yourself, please install Stride.VisualStudio.Package .vsix
// and re-save the associated .sdfx.
// </auto-generated>
using System;
using Stride.Core;
using Stride.Rendering;
using Stride.Graphics;
using Stride.Shaders;
using Stride.Core.Mathematics;
using Buffer = Stride.Graphics.Buffer;
namespace Stride.Rendering
{
public static partial class ToGlslShaderKeys
{
public static readonly ValueParameterKey<Vector4> BaseColor = ParameterKeys.NewValue<Vector4>();
public static readonly ValueParameterKey<float> TestArray = ParameterKeys.NewValue<float>();
}
}
| {
"pile_set_name": "Github"
} |
@Manual{R-ALEPlot,
title = {ALEPlot: Accumulated Local Effects (ALE) Plots and Partial Dependence
(PD) Plots},
author = {Dan Apley},
year = {2018},
note = {R package version 1.1},
url = {https://CRAN.R-project.org/package=ALEPlot},
}
@Manual{R-AmesHousing,
title = {AmesHousing: The Ames Iowa Housing Data},
author = {Max Kuhn},
year = {2017},
note = {R package version 0.0.3},
url = {https://CRAN.R-project.org/package=AmesHousing},
}
@Manual{R-caret,
title = {caret: Classification and Regression Training},
author = {Max Kuhn},
year = {2020},
note = {R package version 6.0-85},
url = {https://CRAN.R-project.org/package=caret},
}
@Manual{R-DALEX,
title = {DALEX: Descriptive mAchine Learning EXplanations},
author = {Przemyslaw Biecek},
year = {2019},
note = {R package version 0.4.9},
url = {https://CRAN.R-project.org/package=DALEX},
}
@Manual{R-data.table,
title = {data.table: Extension of `data.frame`},
author = {Matt Dowle and Arun Srinivasan},
year = {2019},
note = {R package version 1.12.8},
url = {https://CRAN.R-project.org/package=data.table},
}
@Manual{R-doParallel,
title = {doParallel: Foreach Parallel Adaptor for the 'parallel' Package},
author = {Microsoft Corporation and Steve Weston},
year = {2019},
note = {R package version 1.0.15},
url = {https://CRAN.R-project.org/package=doParallel},
}
@Manual{R-DT,
title = {DT: A Wrapper of the JavaScript Library 'DataTables'},
author = {Yihui Xie and Joe Cheng and Xianying Tan},
year = {2019},
note = {R package version 0.11},
url = {https://CRAN.R-project.org/package=DT},
}
@Manual{R-earth,
title = {earth: Multivariate Adaptive Regression Splines},
author = {Stephen Milborrow. Derived from mda:mars by Trevor Hastie and Rob Tibshirani. Uses Alan Miller's Fortran utilities with Thomas Lumley's leaps wrapper.},
year = {2019},
note = {R package version 5.1.2},
url = {https://CRAN.R-project.org/package=earth},
}
@Manual{R-fastshap,
title = {fastshap: Fast Approximate Shapley Values},
author = {Brandon Greenwell},
note = {R package version 0.0.3.9000},
url = {https://github.com/bgreenwell/fastshap},
year = {2019},
}
@Manual{R-foreach,
title = {foreach: Provides Foreach Looping Construct},
author = {{Revolution Analytics} and Steve Weston}},
year = {2019},
note = {R package version 1.4.7},
url = {https://CRAN.R-project.org/package=foreach},
}
@Manual{R-gbm,
title = {gbm: Generalized Boosted Regression Models},
author = {Brandon Greenwell and Bradley Boehmke and Jay Cunningham and GBM Developers},
year = {2019},
note = {R package version 2.1.5},
url = {https://CRAN.R-project.org/package=gbm},
}
@Manual{R-ggplot2,
title = {ggplot2: Create Elegant Data Visualisations Using the Grammar of Graphics},
author = {Hadley Wickham and Winston Chang and Lionel Henry and Thomas Lin Pedersen and Kohske Takahashi and Claus Wilke and Kara Woo and Hiroaki Yutani},
year = {2019},
note = {R package version 3.2.1},
url = {https://CRAN.R-project.org/package=ggplot2},
}
@Manual{R-glmnet,
title = {glmnet: Lasso and Elastic-Net Regularized Generalized Linear Models},
author = {Jerome Friedman and Trevor Hastie and Rob Tibshirani and Balasubramanian Narasimhan and Noah Simon},
year = {2019},
note = {R package version 3.0-2},
url = {https://CRAN.R-project.org/package=glmnet},
}
@Manual{R-iBreakDown,
title = {iBreakDown: Model Agnostic Instance Level Variable Attributions},
author = {Przemyslaw Biecek and Alicja Gosiewska and Hubert Baniecki and Adam Izdebski},
year = {2019},
note = {R package version 0.9.9},
url = {https://CRAN.R-project.org/package=iBreakDown},
}
@Manual{R-iml,
title = {iml: Interpretable Machine Learning},
author = {Christoph Molnar},
year = {2019},
note = {R package version 0.9.0},
url = {https://CRAN.R-project.org/package=iml},
}
@Manual{R-ingredients,
title = {ingredients: Effects and Importances of Model Ingredients},
author = {Przemyslaw Biecek and Hubert Baniecki and Adam Izdebski},
year = {2019},
note = {R package version 0.5.0},
url = {https://CRAN.R-project.org/package=ingredients},
}
@Manual{R-kernlab,
title = {kernlab: Kernel-Based Machine Learning Lab},
author = {Alexandros Karatzoglou and Alex Smola and Kurt Hornik},
year = {2019},
note = {R package version 0.9-29},
url = {https://CRAN.R-project.org/package=kernlab},
}
@Manual{R-measures,
title = {measures: Performance Measures for Statistical Learning},
author = {Philipp Probst},
year = {2018},
note = {R package version 0.2},
url = {https://CRAN.R-project.org/package=measures},
}
@Manual{R-microbenchmark,
title = {microbenchmark: Accurate Timing Functions},
author = {Olaf Mersmann},
year = {2019},
note = {R package version 1.4-7},
url = {https://CRAN.R-project.org/package=microbenchmark},
}
@Manual{R-mlr,
title = {mlr: Machine Learning in R},
author = {Bernd Bischl and Michel Lang and Lars Kotthoff and Julia Schiffner and Jakob Richter and Zachary Jones and Giuseppe Casalicchio and Mason Gallo and Patrick Schratz},
year = {2020},
note = {R package version 2.17.0},
url = {https://CRAN.R-project.org/package=mlr},
}
@Manual{R-mlr3,
title = {mlr3: Machine Learning in R - Next Generation},
author = {Michel Lang and Bernd Bischl and Jakob Richter and Patrick Schratz and Martin Binder},
year = {2019},
note = {R package version 0.1.6},
url = {https://CRAN.R-project.org/package=mlr3},
}
@Manual{R-mmpf,
title = {mmpf: Monte-Carlo Methods for Prediction Functions},
author = {Zachary Jones},
year = {2018},
note = {R package version 0.0.5},
url = {https://CRAN.R-project.org/package=mmpf},
}
@Manual{R-nnet,
title = {nnet: Feed-Forward Neural Networks and Multinomial Log-Linear Models},
author = {Brian Ripley},
year = {2016},
note = {R package version 7.3-12},
url = {https://CRAN.R-project.org/package=nnet},
}
@Manual{R-party,
title = {party: A Laboratory for Recursive Partytioning},
author = {Torsten Hothorn and Kurt Hornik and Carolin Strobl and Achim Zeileis},
year = {2019},
note = {R package version 1.3-3},
url = {https://CRAN.R-project.org/package=party},
}
@Manual{R-partykit,
title = {partykit: A Toolkit for Recursive Partytioning},
author = {Torsten Hothorn and Achim Zeileis},
year = {2019},
note = {R package version 1.2-5},
url = {https://CRAN.R-project.org/package=partykit},
}
@Manual{R-pdp,
title = {pdp: Partial Dependence Plots},
author = {Brandon Greenwell},
note = {https://bgreenwell.github.io/pdp/index.html,
https://github.com/bgreenwell/pdp},
year = {2019},
}
@Manual{R-pkgsearch,
title = {pkgsearch: Search and Query CRAN R Packages},
author = {Gábor Csárdi and Maëlle Salmon},
year = {2019},
note = {R package version 3.0.2},
url = {https://CRAN.R-project.org/package=pkgsearch},
}
@Manual{R-plyr,
title = {plyr: Tools for Splitting, Applying and Combining Data},
author = {Hadley Wickham},
year = {2019},
note = {R package version 1.8.5},
url = {https://CRAN.R-project.org/package=plyr},
}
@Manual{R-R6,
title = {R6: Encapsulated Classes with Reference Semantics},
author = {Winston Chang},
year = {2019},
note = {R package version 2.4.1},
url = {https://CRAN.R-project.org/package=R6},
}
@Manual{R-randomForestExplainer,
title = {randomForestExplainer: Explaining and Visualizing Random Forests in Terms of Variable
Importance},
author = {Aleksandra Paluszynska and Przemyslaw Biecek and Yue Jiang},
year = {2019},
note = {R package version 0.10.0},
url = {https://CRAN.R-project.org/package=randomForestExplainer},
}
@Manual{R-ranger,
title = {ranger: A Fast Implementation of Random Forests},
author = {Marvin N. Wright and Stefan Wager and Philipp Probst},
year = {2020},
note = {R package version 0.12.1},
url = {https://CRAN.R-project.org/package=ranger},
}
@Manual{R-rfVarImpOOB,
title = {rfVarImpOOB: Unbiased Variable Importance for Random Forests},
author = {Markus Loecher},
year = {2019},
note = {R package version 1.0},
url = {https://CRAN.R-project.org/package=rfVarImpOOB},
}
@Manual{R-SuperLearner,
title = {SuperLearner: Super Learner Prediction},
author = {Eric Polley and Erin LeDell and Chris Kennedy and Mark {van der Laan}},
year = {2019},
note = {R package version 2.0-26},
url = {https://CRAN.R-project.org/package=SuperLearner},
}
@Manual{R-tibble,
title = {tibble: Simple Data Frames},
author = {Kirill Müller and Hadley Wickham},
year = {2019},
note = {R package version 2.1.3},
url = {https://CRAN.R-project.org/package=tibble},
}
@Manual{R-tree.interpreter,
title = {tree.interpreter: Random Forest Prediction Decomposition and Feature Importance
Measure},
author = {Qingyao Sun},
year = {2019},
note = {R package version 0.1.0},
url = {https://CRAN.R-project.org/package=tree.interpreter},
}
@Manual{R-varImp,
title = {varImp: RF Variable Importance for Arbitrary Measures},
author = {Philipp Probst},
year = {2019},
note = {R package version 0.3},
url = {https://CRAN.R-project.org/package=varImp},
}
@Manual{R-vip,
title = {vip: Variable Importance Plots},
author = {Brandon Greenwell and Brad Boehmke and Bernie Gray},
note = {R package version 0.2.1},
url = {https://github.com/koalaverse/vip/},
year = {2019},
}
@Manual{R-vita,
title = {vita: Variable Importance Testing Approaches},
author = {Ender Celik},
year = {2015},
note = {R package version 1.0.0},
url = {https://CRAN.R-project.org/package=vita},
}
@Manual{R-vivo,
title = {vivo: Local Variable Importance via Oscillations of Ceteris Paribus
Profiles},
author = {Anna Kozak and Przemyslaw Biecek},
year = {2019},
note = {R package version 0.1.1},
url = {https://CRAN.R-project.org/package=vivo},
}
@Manual{R-xgboost,
title = {xgboost: Extreme Gradient Boosting},
author = {Tianqi Chen and Tong He and Michael Benesty and Vadim Khotilovich and Yuan Tang and Hyunsu Cho and Kailong Chen and Rory Mitchell and Ignacio Cano and Tianyi Zhou and Mu Li and Junyuan Xie and Min Lin and Yifeng Geng and Yutian Li},
year = {2019},
note = {R package version 0.90.0.2},
url = {https://CRAN.R-project.org/package=xgboost},
}
@Article{DALEX2018,
title = {DALEX: Explainers for Complex Predictive Models in R},
author = {Przemyslaw Biecek},
journal = {Journal of Machine Learning Research},
year = {2018},
volume = {19},
pages = {1-5},
number = {84},
url = {http://jmlr.org/papers/v19/18-416.html},
}
@Book{ggplot22016,
author = {Hadley Wickham},
title = {ggplot2: Elegant Graphics for Data Analysis},
publisher = {Springer-Verlag New York},
year = {2016},
isbn = {978-3-319-24277-4},
url = {https://ggplot2.tidyverse.org},
}
@Article{glmnet2010,
title = {Regularization Paths for Generalized Linear Models via Coordinate Descent},
author = {Jerome Friedman and Trevor Hastie and Robert Tibshirani},
journal = {Journal of Statistical Software},
year = {2010},
volume = {33},
number = {1},
pages = {1--22},
url = {http://www.jstatsoft.org/v33/i01/},
}
@Article{glmnet2011,
title = {Regularization Paths for Cox's Proportional Hazards Model via Coordinate Descent},
author = {Noah Simon and Jerome Friedman and Trevor Hastie and Rob Tibshirani},
journal = {Journal of Statistical Software},
year = {2011},
volume = {39},
number = {5},
pages = {1--13},
url = {http://www.jstatsoft.org/v39/i05/},
}
@Misc{iBreakDown2019,
title = {iBreakDown: Uncertainty of Model Explanations for Non-additive Predictive Models},
author = {Alicja Gosiewska and Przemyslaw Biecek},
year = {2019},
eprint = {arXiv:1903.11420},
url = {https://arxiv.org/abs/1903.11420v1},
}
@Article{iml2018,
author = {Christoph Molnar and Bernd Bischl and Giuseppe Casalicchio},
title = {iml: An R package for Interpretable Machine Learning},
doi = {10.21105/joss.00786},
url = {http://joss.theoj.org/papers/10.21105/joss.00786},
year = {2018},
publisher = {Journal of Open Source Software},
volume = {3},
number = {26},
pages = {786},
journal = {JOSS},
}
@Article{kernlab2004,
title = {kernlab -- An {S4} Package for Kernel Methods in {R}},
author = {Alexandros Karatzoglou and Alex Smola and Kurt Hornik and Achim Zeileis},
journal = {Journal of Statistical Software},
year = {2004},
volume = {11},
number = {9},
pages = {1--20},
url = {http://www.jstatsoft.org/v11/i09/},
}
@Article{mlr,
title = {{mlr}: Machine Learning in R},
author = {Bernd Bischl and Michel Lang and Lars Kotthoff and Julia Schiffner and Jakob Richter and Erich Studerus and Giuseppe Casalicchio and Zachary M. Jones},
journal = {Journal of Machine Learning Research},
year = {2016},
volume = {17},
number = {170},
pages = {1-5},
url = {http://jmlr.org/papers/v17/15-066.html},
}
@Article{automatic,
title = {Automatic model selection for high-dimensional survival analysis},
author = {Michel Lang and Helena Kotthaus and Peter Marwedel and Claus Weihs and Joerg Rahnenfuehrer and Bernd Bischl},
journal = {Journal of Statistical Computation and Simulation},
year = {2014},
volume = {85},
number = {1},
pages = {62-76},
publisher = {Taylor & Francis},
}
@InCollection{bischl2016class,
title = {On Class Imbalance Correction for Classification Algorithms in Credit Scoring},
author = {Bernd Bischl and Tobias Kuehn and Gero Szepannek},
booktitle = {Operations Research Proceedings 2014},
pages = {37-43},
year = {2016},
publisher = {Springer},
}
@Article{mlrmbo,
title = {mlrMBO: A Modular Framework for Model-Based Optimization of Expensive Black-Box Functions},
author = {Bernd Bischl and Jakob Richter and Jakob Bossek and Daniel Horn and Janek Thomas and Michel Lang},
journal = {arXiv preprint arXiv:1703.03373},
year = {2017},
}
@Article{multilabel,
title = {Multilabel Classification with R Package mlr},
author = {Philipp Probst and Quay Au and Giuseppe Casalicchio and Clemens Stachl and Bernd Bischl},
journal = {arXiv preprint arXiv:1703.08991},
year = {2017},
}
@Article{openml,
title = {OpenML: An R package to connect to the machine learning platform OpenML},
author = {Giuseppe Casalicchio and Jakob Bossek and Michel Lang and Dominik Kirchhoff and Pascal Kerschke and Benjamin Hofner and Heidi Seibold and Joaquin Vanschoren and Bernd Bischl},
journal = {Computational Statistics},
pages = {1-15},
year = {2017},
publisher = {Springer},
}
@Article{mlr3,
title = {{mlr3}: A modern object-oriented machine learning framework in {R}},
author = {Michel Lang and Martin Binder and Jakob Richter and Patrick Schratz and Florian Pfisterer and Stefan Coors and Quay Au and Giuseppe Casalicchio and Lars Kotthoff and Bernd Bischl},
journal = {Journal of Open Source Software},
year = {2019},
month = {dec},
doi = {10.21105/joss.01903},
url = {https://joss.theoj.org/papers/10.21105/joss.01903},
}
@Book{nnet2002,
title = {Modern Applied Statistics with S},
author = {W. N. Venables and B. D. Ripley},
publisher = {Springer},
edition = {Fourth},
address = {New York},
year = {2002},
note = {ISBN 0-387-95457-0},
url = {http://www.stats.ox.ac.uk/pub/MASS4},
}
@Article{party2006a,
title = {Unbiased Recursive Partitioning: A Conditional Inference Framework},
author = {Torsten Hothorn and Kurt Hornik and Achim Zeileis},
journal = {Journal of Computational and Graphical Statistics},
year = {2006},
volume = {15},
number = {3},
pages = {651--674},
}
@Article{party2008a,
title = {Model-Based Recursive Partitioning},
author = {Achim Zeileis and Torsten Hothorn and Kurt Hornik},
journal = {Journal of Computational and Graphical Statistics},
year = {2008},
volume = {17},
number = {2},
pages = {492--514},
}
@Article{party2006b,
title = {Survival Ensembles},
author = {Torsten Hothorn and Peter Buehlmann and Sandrine Dudoit and Annette Molinaro and Mark {Van Der Laan}},
journal = {Biostatistics},
year = {2006},
volume = {7},
number = {3},
pages = {355--373},
}
@Article{party2007a,
title = {Bias in Random Forest Variable Importance Measures: Illustrations, Sources and a Solution},
author = {Carolin Strobl and Anne-Laure Boulesteix and Achim Zeileis and Torsten Hothorn},
journal = {BMC Bioinformatics},
year = {2007},
volume = {8},
number = {25},
url = {http://www.biomedcentral.com/1471-2105/8/25},
}
@Article{party2008b,
title = {Conditional Variable Importance for Random Forests},
author = {Carolin Strobl and Anne-Laure Boulesteix and Thomas Kneib and Thomas Augustin and Achim Zeileis},
journal = {BMC Bioinformatics},
year = {2008},
volume = {9},
number = {307},
url = {http://www.biomedcentral.com/1471-2105/9/307},
}
@Article{partykit2015,
title = {{partykit}: A Modular Toolkit for Recursive Partytioning in {R}},
author = {Torsten Hothorn and Achim Zeileis},
journal = {Journal of Machine Learning Research},
year = {2015},
volume = {16},
pages = {3905-3909},
url = {http://jmlr.org/papers/v16/hothorn15a.html},
}
@Article{partykit2006,
title = {Unbiased Recursive Partitioning: A Conditional Inference Framework},
author = {Torsten Hothorn and Kurt Hornik and Achim Zeileis},
journal = {Journal of Computational and Graphical Statistics},
year = {2006},
volume = {15},
number = {3},
doi = {10.1198/106186006X133933},
pages = {651--674},
}
@Article{partykit2008,
title = {Model-Based Recursive Partitioning},
author = {Achim Zeileis and Torsten Hothorn and Kurt Hornik},
journal = {Journal of Computational and Graphical Statistics},
year = {2008},
volume = {17},
number = {2},
doi = {10.1198/106186008X319331},
pages = {492--514},
}
@Article{pdp2017,
title = {pdp: An R Package for Constructing Partial Dependence Plots},
author = {Brandon M. Greenwell},
journal = {The R Journal},
year = {2017},
volume = {9},
number = {1},
pages = {421--436},
url = {https://journal.r-project.org/archive/2017/RJ-2017-016/index.html},
}
@Article{plyr2011,
title = {The Split-Apply-Combine Strategy for Data Analysis},
author = {Hadley Wickham},
journal = {Journal of Statistical Software},
year = {2011},
volume = {40},
number = {1},
pages = {1--29},
url = {http://www.jstatsoft.org/v40/i01/},
}
@Article{ranger2017,
title = {{ranger}: A Fast Implementation of Random Forests for High Dimensional Data in {C++} and {R}},
author = {Marvin N. Wright and Andreas Ziegler},
journal = {Journal of Statistical Software},
year = {2017},
volume = {77},
number = {1},
pages = {1--17},
doi = {10.18637/jss.v077.i01},
}
@Article{tree.interpreter2019,
title = {A {Debiased} {MDI} {Feature} {Importance} {Measure} for {Random} {Forests}},
url = {http://arxiv.org/abs/1906.10845},
abstract = {Tree ensembles such as Random Forests have achieved impressive empirical success across a wide variety of applications. To understand how these models make predictions, people routinely turn to feature importance measures calculated from tree ensembles. It has long been known that Mean Decrease Impurity (MDI), one of the most widely used measures of feature importance, incorrectly assigns high importance to noisy features, leading to systematic bias in feature selection. In this paper, we address the feature selection bias of MDI from both theoretical and methodological perspectives. Based on the original definition of MDI by Breiman et al. for a single tree, we derive a tight non-asymptotic bound on the expected bias of MDI importance of noisy features, showing that deep trees have higher (expected) feature selection bias than shallow ones. However, it is not clear how to reduce the bias of MDI using its existing analytical expression. We derive a new analytical expression for MDI, and based on this new expression, we are able to propose a debiased MDI feature importance measure using out-of-bag samples, called MDI-oob. For both the simulated data and a genomic ChIP dataset, MDI-oob achieves state-of-the-art performance in feature selection from Random Forests for both deep and shallow trees.},
urldate = {2019-10-18},
journal = {arXiv:1906.10845 [cs, stat]},
author = {Xiao Li and Yu Wang and Sumanta Basu and Karl Kumbier and Bin Yu},
month = {jun},
year = {2019},
note = {arXiv: 1906.10845},
keywords = {Statistics - Machine Learning, Computer Science - Machine Learning},
annote = {Comment: The first two authors contributed equally to this paper},
}
@incollection{lundberg_unified_2017,
title = {A Unified Approach to Interpreting Model Predictions},
author = {Lundberg, Scott M and Lee, Su-In},
booktitle = {Advances in Neural Information Processing Systems 30},
pages = {4765--4774},
year = {2017},
publisher = {Curran Associates, Inc.},
url = {http://papers.nips.cc/paper/7062-a-unified-approach-to-interpreting-model-predictions.pdf}
}
@misc{janzing-2019-feature,
title = {Feature relevance quantification in explainable AI: A causal problem},
author = {Dominik Janzing and Lenon Minorics and Patrick Blöbaum},
year = {2019},
eprint = {1910.13413},
archivePrefix = {arXiv},
primaryClass = {stat.ML}
}
@misc{zien-2009-feature,
title = {The Feature Importance Ranking Measure},
author = {Alexander Zien and Nicole Kraemer and Soeren Sonnenburg and Gunnar Raetsch},
year = {2009},
eprint = {0906.4258},
archivePrefix = {arXiv},
primaryClass = {stat.ML}
}
@misc{apley-2016-visualizing,
title = {Visualizing the Effects of Predictor Variables in Black Box Supervised Learning Models},
author = {Daniel W. Apley and Jingyu Zhu},
year = {2016},
eprint = {1612.08468},
archivePrefix = {arXiv},
primaryClass = {stat.ME}
}
@misc{parr-2019-technical,
title = {Technical Report: A Stratification Approach to Partial Dependence for Codependent Variables},
author = {Terence Parr and James D. Wilson},
year = {2019},
eprint = {1907.06698},
archivePrefix = {arXiv},
primaryClass = {cs.LG}
}
@misc{hooker-2019-stop,
title = {Please Stop Permuting Features: An Explanation and Alternatives},
author = {Giles Hooker and Lucas Mentch},
year = {2019},
eprint = {1905.03151},
archivePrefix = {arXiv},
primaryClass = {stat.ME}
}
@misc{doshivelez-2017-rigorous,
title = {Towards A Rigorous Science of Interpretable Machine Learning},
author = {Finale Doshi-Velez and Been Kim},
year = {2017},
eprint = {1702.08608},
archivePrefix = {arXiv},
primaryClass = {stat.ML}
}
@book{hastie-elements-2009,
title = {The Elements of Statistical Learning: Data Mining, Inference, and Prediction, Second Edition},
author = {Trevor Hastie and Robert. Tibshirani and Jerome Friedman},
series = {Springer Series in Statistics},
year = {2009},
publisher = {Springer-Verlag},
}
@book{molnar-2019-iml,
title = {Interpretable Machine Learning},
author = {Christoph Molnar},
note = {\url{https://christophm.github.io/interpretable-ml-book/}},
year = {2019},
subtitle = {A Guide for Making Black Box Models Explainable}
}
@book{classification-breiman-1984,
title = {Classification and Regression Trees},
author = {Leo Breiman and Jerome Friedman and Charles J. Stone, Richard A. Olshen},
isbn = {9780412048418},
series = {The Wadsworth and Brooks-Cole statistics-probability series},
year = {1984},
publisher = {Taylor \& Francis}
}
@book{applied-kuhn-2013,
title = {Applied Predictive Modeling},
author = {Max Kuhn and Kjell Johnson},
isbn = {9781461468493},
series = {SpringerLink : B{\"u}cher},
year = {2013},
publisher = {Springer New York}
}
@article{hooker-2007-generalized,
author = {Giles Hooker},
title = {Generalized Functional ANOVA Diagnostics for High-Dimensional Functions of Dependent Variables},
journal = {Journal of Computational and Graphical Statistics},
volume = {16},
number = {3},
pages = {709-732},
year = {2007},
publisher = {Taylor & Francis},
url = {https://doi.org/10.1198/106186007X237892}
}
@article{laan-2006-statistical,
author = {van der Laan, M.},
title = {Statistical Inference for Variable Importance},
journal = {The International Journal of Biostatistics},
year = {2006},
volume = {2},
number = {1},
url = {https://doi.org/10.2202/1557-4679.1008}
}
@article{strumbelj-2014-explaining,
author = {{Š}trumbelj, Erik and Kononenko, Igor},
title = {Explaining prediction models and individual predictions with feature contributions},
journal = {Knowledge and Information Systems},
year = {2014},
volume = {31},
number = {3},
pages = {647--665},
url = {https://doi.org/10.1007/s10115-013-0679-x}
}
@article{friedman-2001-greedy,
author = {Jerome H. Friedman},
title = {Greedy Function Approximation: A Gradient Boosting Machine},
journal = {The Annals of Statistics},
year = {2001},
volume = {29},
number = {5},
pages = {1189--1232},
url = {https://doi.org/10.1214/aos/1013203451}
}
@article{strobl-2019-conditional,
title={Conditional variable importance for random forests},
author={Strobl, Carolin and Boulesteix, Anne-Laure and Kneib, Thomas and Augustin, Thomas and Zeileis, Achim},
journal={BMC Bioinformatics},
year={2008},
volume = {9},
number = {1},
pages = {307},
url = {https://doi.org/10.1186/1471-2105-9-307}
}
@article{lundberg-explainable-2019,
title={Explainable AI for Trees: From Local Explanations to Global Understanding},
author={Lundberg, Scott M and Erion, Gabriel and Chen, Hugh and DeGrave, Alex and Prutkin, Jordan M and Nair, Bala and Katz, Ronit and Himmelfarb, Jonathan and Bansal, Nisha and Lee, Su-In},
journal={arXiv preprint arXiv:1905.04610},
year={2019}
}
@article{random-breiman-2001,
author = {Breiman, Leo},
title = {Random Forests},
journal = {Machine Learning},
year = {2001},
volume = {45},
number = {1},
pages = {5--32},
url = {https://doi.org/10.1023/A:1010933404324}
}
@article{greenwell-simple-2018,
title = {A Simple and Effective Model-Based Variable Importance Measure},
author = {Greenwell, Brandon M. and Boehmke, Bradley C. and McCarthy, Andrew J.},
journal = {arXiv preprint arXiv:1805.04755},
year = {2018}
}
@article{fisher-model-2018,
title = {Model Class Reliance: Variable Importance Measures for any Machine Learning Model Class, from the "Rashomon" Perspective},
author = {Fisher, A. and Rudin, C. and Dominici, F.},
journal = {arXiv preprint arXiv:1801.01489},
year = {2018}
}
@article{multivariate-friedman-1991,
author = {Jerome H. Friedman},
title = {Multivariate Adaptive Regression Splines},
journal = {The Annals of Statistics},
year = {1991},
volume = {19},
number = {1},
pages = {1--67},
url = {https://doi.org/10.1214/aos/1176347963},
}
@article{bagging-breiman-1996,
author = {Leo Breiman},
title = {Bagging Predictors},
journal = {Machine Learning},
year = {1996},
volume = {8},
number = {2},
pages = {209--218},
url = {https://doi.org/10.1023/A:1018054314350},
}
@article{data-gedeon-1997,
author = {Gedeon, T.D.},
title = {Data mining of inputs: Analysing magnitude and functional measures},
journal = {International Journal of Neural Systems},
year = {1997},
volume = {24},
number = {2},
pages = {123--140},
url = {https://doi.org/10.1007/s10994-006-6226-1},
}
@article{ames-cock-2011,
title = {Ames, Iowa: Alternative to the Boston Housing Data as an
End of Semester Regression Project},
author = {Dean De Cock},
journal = {Journal of Statistics Education},
year = {2011},
volume = {19},
number = {3},
pages = {1--15},
url = {https://doi.org/10.1080/10691898.2011.11889627}
}
@article{robust-cleveland-1979,
author = { William S. Cleveland},
title = {Robust Locally Weighted Regression and Smoothing Scatterplots},
journal = {Journal of the American Statistical Association},
volume = {74},
number = {368},
pages = {829-836},
year = {1979},
doi = {https://doi.org/10.1080/01621459.1979.10481038},
}
@article{interpreting-garson-1991,
author = {David G. Garson},
title = {Interpreting Neural-network Connection Weights},
journal = {Artificial Intelligence Expert},
volume = {6},
number = {4},
year = {1991},
pages = {46--51},
}
@article{back-goh-1995,
title = {Back-propagation neural networks for modeling complex systems},
journal = {Artificial Intelligence in Engineering},
volume = {9},
number = {3},
pages = {143--151},
year = {1995},
author = {A.T.C. Goh},
url = {https://dx.doi.org/10.1016/0954-1810(94)00011-S}
}
@article{accurate-olden-2004,
title = {An accurate comparison of methods for quantifying variable importance in artificial neural networks using simulated data},
journal = {Ecological Modelling},
volume = {178},
number = {3},
pages = {389--397},
year = {2004},
author = {Julian D Olden and Michael K Joy and Russell G Death},
url = {https://dx.doi.org/10.1016/j.ecolmodel.2004.03.013}
}
@article{harrison-1978-hedonic,
title = {Hedonic Housing Prices and the Demand for Clean Air},
author = {David Harrison and Daniel L. Rubinfeld},
year = {1978},
journal = {Journal of Environmental Economics and Management},
volume = {5},
number = {1},
pages = {81-102},
url = {https://doi.org/10.1016/0095-0696(78)90006-2},
}
@article{goldstein-peeking-2015,
title = {Peeking Inside the Black Box: Visualizing Statistical Learning with Plots of Individual Conditional Expectation},
author = {Alex Goldstein and Adam Kapelner and Justin Bleich and Emil Pitkin},
journal = {Journal of Computational and Graphical Statistics},
volume = {24},
number = {1},
pages = {44--65},
year = {2015},
url = {https://doi.org/10.1080/10618600.2014.907095},
}
@article{friedman-ppr-1981,
title = {Projection Pursuit Regression},
author = {Jerome H. Friedman and Werner Stuetzle},
journal = {Journal of the American Statistical Association},
year = {1981},
volume = {76},
number = {376},
pages = {817--823},
url = {https://doi.org/10.1080/01621459.1981.10477729},
}
@article{scholbeck-2019-sampling,
author = {Christian A. Scholbeck and Christoph Molnar and Christian Heumann and Bernd Bischl and Giuseppe Casalicchio},
title = {Sampling, Intervention, Prediction, Aggregation: {A} Generalized Framework for Model Agnostic Interpretations},
journal = {CoRR},
volume = {abs/1904.03959},
year = {2019},
url = {http://arxiv.org/abs/1904.03959},
archivePrefix = {arXiv}
}
@article{montavon-2018-methods,
title = {Methods for interpreting and understanding deep neural networks},
journal = {Digital Signal Processing},
volume = {73},
pages = {1--15},
year = {2018},
url = {https://doi.org/10.1016/j.dsp.2017.10.011},
author = {Grégoire Montavon and Wojciech Samek and Klaus-Robert Müller},
}
@inproceedings{poulin-2006-visual,
author = {Poulin, Brett and Eisner, Roman and Szafron, Duane and Lu, Paul and Greiner, Russ and Wishart, D. S. and Fyshe, Alona and Pearcy, Brandon and MacDonell, Cam and Anvik, John},
title = {Visual Explanation of Evidence in Additive Classifiers},
year = {2006},
publisher = {AAAI Press},
booktitle = {Proceedings of the 18th Conference on Innovative Applications of Artificial Intelligence - Volume 2},
pages = {1822--1829},
numpages = {8},
location = {Boston, Massachusetts},
series = {IAAI’06}
}
@inproceedings{caruana-2015-intelligible,
author = {Caruana, Rich and Lou, Yin and Gehrke, Johannes and Koch, Paul and Sturm, Marc and Elhadad, Noemie},
title = {Intelligible Models for HealthCare: Predicting Pneumonia Risk and Hospital 30-Day Readmission},
year = {2015},
isbn = {9781450336642},
publisher = {Association for Computing Machinery},
address = {New York, NY, USA},
url = {https://doi.org/10.1145/2783258.2788613},
booktitle = {Proceedings of the 21th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining},
pages = {1721--1730},
numpages = {10},
keywords = {intelligibility, logistic regression, healthcare, interaction detection, risk prediction, classification, additive models},
location = {Sydney, NSW, Australia},
series = {KDD '15}
}
@inproceedings{bibal-2016-intterpretability,
title = {Interpretability of machine learning models and representations: an introduction},
author = {Adrien Bibal and Beno{\^i}t Fr{\'e}nay},
booktitle = {ESANN},
year = {2016}
}
@inproceedings{bau-2017-network,
author = {Bau, David and Zhou, Bolei and Khosla, Aditya and Oliva, Aude and Torralba, Antonio},
title = {Network Dissection: Quantifying Interpretability of Deep Visual Representations},
booktitle = {The IEEE Conference on Computer Vision and Pattern Recognition (CVPR)},
month = {July},
year = {2017}
}
@manual{R-earth-fixed,
title = {earth: Multivariate Adaptive Regression Splines},
author = {Stephen Milborrow},
year = {2019},
note = {R package version 5.1.2},
url = {https://CRAN.R-project.org/package=earth},
}
| {
"pile_set_name": "Github"
} |
package com.baselet.element.relation.helper;
import com.baselet.control.SharedUtils;
import com.baselet.control.basics.geom.Point;
import com.baselet.control.basics.geom.PointDouble;
import com.baselet.control.basics.geom.Rectangle;
import com.baselet.control.constants.SharedConstants;
import com.baselet.element.sticking.PointDoubleIndexed;
public class RelationPointHandlerUtils {
static Rectangle calculateRelationRectangleBasedOnPoints(PointDouble upperLeftCorner, int gridSize, RelationPointList relationPoints) {
// Calculate new Relation position and size
Rectangle newSize = relationPoints.createRectangleContainingAllPointsAndTextSpace();
if (newSize == null) {
throw new RuntimeException("This relation has no points: " + relationPoints);
}
// scale with zoom factor
newSize.setBounds(
newSize.getX() * gridSize / SharedConstants.DEFAULT_GRID_SIZE,
newSize.getY() * gridSize / SharedConstants.DEFAULT_GRID_SIZE,
newSize.getWidth() * gridSize / SharedConstants.DEFAULT_GRID_SIZE,
newSize.getHeight() * gridSize / SharedConstants.DEFAULT_GRID_SIZE);
// Realign new size to grid (should not be necessary as long as SELECTCIRCLERADIUS == DefaultGridSize) and add 1x gridSize to the right end (otherwise the selection-circles would change by 1px because Swing draws only to width-1 instead of width)
newSize.setLocation(SharedUtils.realignTo(false, newSize.getX(), false, gridSize), SharedUtils.realignTo(false, newSize.getY(), false, gridSize));
newSize.setSize(SharedUtils.realignTo(false, newSize.getWidth(), true, gridSize) + gridSize, SharedUtils.realignTo(false, newSize.getHeight(), true, gridSize) + gridSize);
// and move to correct place of Relation
newSize.move(upperLeftCorner.getX().intValue(), upperLeftCorner.getY().intValue());
return newSize;
}
static PointDoubleIndexed getRelationPointContaining(Point point, RelationPointList points) {
for (RelationPoint relationPoint : points.getPointHolders()) {
if (relationPoint.getSizeAbsolute().contains(point)) {
return relationPoint.getPoint();
}
}
return null;
}
}
| {
"pile_set_name": "Github"
} |
import { AfterViewInit, Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { ReCaptchaV3Service, ScriptService } from '../../projects/ngx-captcha-lib/src/public_api';
declare var hljs: any;
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'ngx-recaptcha-3-demo',
templateUrl: './re-captcha-3-demo.component.html',
})
export class ReCaptcha3DemoComponent implements OnInit, AfterViewInit {
public siteKey?: string = '6Ldb528UAAAAAMD7bdsxQz2gQSl-Jb-kGTyAHThi';
public action?: string = 'homepage';
public token?: string;
public error?: string;
public readonly constructorCode = `
import { ReCaptchaV3Service } from 'ngx-captcha';
constructor(
private reCaptchaV3Service: ReCaptchaV3Service
) { }
`;
public readonly methodCode = `
this.reCaptchaV3Service.execute(this.siteKey, 'homepage', (token) => {
console.log('This is your token: ', token);
}, {
useGlobalDomain: false // optional
});
`;
constructor(
private reCaptchaV3Service: ReCaptchaV3Service,
private scriptService: ScriptService,
private cdr: ChangeDetectorRef
) { }
ngOnInit(): void {
}
ngAfterViewInit(): void {
this.highlight();
}
execute(): void {
this.token = undefined;
if (!this.siteKey) {
this.error = 'Site key is not set';
return;
}
if (!this.action) {
this.error = 'Action is not set';
return;
}
// clean script to make sure siteKey is set correctly (because previous script could be incorrect)
this.scriptService.cleanup();
this.error = undefined;
this.reCaptchaV3Service.execute(this.siteKey, 'reCaptcha3DemoPage', (token) => {
this.token = token;
console.log('Your token is: ', token);
this.cdr.detectChanges();
}, {
useGlobalDomain: false
});
}
private highlight(): void {
const highlightBlocks = document.getElementsByTagName('code');
for (let i = 0; i < highlightBlocks.length; i++) {
const block = highlightBlocks[i];
hljs.highlightBlock(block);
}
}
}
| {
"pile_set_name": "Github"
} |
#include "StableHeader.h"
#include "gkShaderParamDataSource.h"
#include "gkRenderable.h"
#include "gk_Camera.h"
#include "ICamera.h"
#include "RenderCamera.h"
#include "gkRendererGL330.h"
#include "RendererCVars.h"
//-----------------------------------------------------------------------
gkShaderParamDataSource::gkShaderParamDataSource()
: m_pCurrentRenderable(NULL)
, m_pCurrentCamera(NULL)
, m_bIsWorldMatrixOutOfDate(true)
, m_bIsViewMatrixOutOfDate(true)
, m_bIsProjectionMatrixOutOfDate(true)
, m_bIsWorldViewMatrixOutOfDate(true)
, m_bIsViewProjMatrixOutOfDate(true)
, m_bIsWorldViewProjMatrixOutOfDate(true)
, m_bIsInverseWorldMatrixOutOfDate(true)
, m_bIsInverseWorldViewMatrixOutOfDate(true)
, m_bIsInverseViewMatrixOutOfDate(true)
, m_bIsInverseTransposeWorldMatrixOutOfDate(true)
, m_bIsInverseTransposeWorldViewMatrixOutOfDate(true)
, m_bIsCameraPositionOutOfDate(true)
, m_bIsCameraPositionObjectSpaceOutOfDate(true)
{
m_pCurrentCamera = new CRenderCamera;
m_pShadowsCamera[0] = new CRenderCamera;
m_pShadowsCamera[1] = new CRenderCamera;
m_pShadowsCamera[2] = new CRenderCamera;
}
//-----------------------------------------------------------------------
gkShaderParamDataSource::~gkShaderParamDataSource()
{
SAFE_DELETE(m_pCurrentCamera);
SAFE_DELETE(m_pShadowsCamera[0]);
SAFE_DELETE(m_pShadowsCamera[1]);
SAFE_DELETE(m_pShadowsCamera[2]);
}
//-----------------------------------------------------------------------
void gkShaderParamDataSource::setCurrentRenderable(const gkRenderable* rend)
{
m_pCurrentRenderable = rend;
// 有关world的矩阵全部过期
m_bIsWorldMatrixOutOfDate = true;
m_bIsWorldViewMatrixOutOfDate = true;
m_bIsWorldViewProjMatrixOutOfDate = true;
m_bIsInverseWorldMatrixOutOfDate = true;
m_bIsInverseWorldViewMatrixOutOfDate = true;
m_bIsInverseTransposeWorldMatrixOutOfDate = true;
m_bIsInverseTransposeWorldViewMatrixOutOfDate = true;
}
//-----------------------------------------------------------------------
void gkShaderParamDataSource::setWorldMatrices(const Matrix44* m)
{
m_matWorldMatrix = *m;
m_bIsWorldMatrixOutOfDate = false;
}
//-----------------------------------------------------------------------
void gkShaderParamDataSource::setMainCamera(const CCamera* cam)
{
const Matrix34& m34 = cam->GetMatrix();
m_pCam = cam;
CRenderCamera c;
float Near = cam->GetNearPlane(), Far = cam->GetFarPlane();
float wT = tanf(cam->GetFov()*0.5f)*Near, wB = -wT;
float wR = wT * cam->GetProjRatio(), wL = -wR;
m_pCurrentCamera->Frustum(wL + cam->GetAsymL(), wR + cam->GetAsymR(), wB + cam->GetAsymB(), wT + cam->GetAsymT(), Near, Far);
Vec3 vEye = cam->GetPosition();
Vec3 vAt = vEye + Vec3(m34(0, 1), m34(1, 1), m34(2, 1));
Vec3 vUp = Vec3(m34(0, 2), m34(1, 2), m34(2, 2));
m_pCurrentCamera->LookAt(vEye, vAt, vUp);
m_vCamDir = (vAt - vEye).GetNormalized();
m_vCamPos = vEye;
// update the far clip
Vec3 lookDir = vAt - vEye;
lookDir.normalize();
Vec3 m_farCenter = lookDir * Far;
Vec3 rightDir = vUp % lookDir;
rightDir.normalize();
Vec3 headDir = lookDir % rightDir;
headDir.normalize();
float h = tanf(cam->GetFov() * 0.5f) * Far;
float w = h * cam->GetProjRatio();
rightDir *= w;
headDir *= h;
m_ScreenFarVerts[0] = Vec3(m_farCenter + rightDir - headDir);
m_ScreenFarVerts[1] = Vec3(m_farCenter - rightDir - headDir);
m_ScreenFarVerts[2] = Vec3(m_farCenter + rightDir + headDir);
m_ScreenFarVerts[3] = Vec3(m_farCenter - rightDir + headDir);
m_viewparam = Vec4(getRenderer()->GetScreenWidth(), getRenderer()->GetScreenHeight(), cam->GetNearPlane(), cam->GetFarPlane());
// 有关view的矩阵全部过期
m_bIsViewMatrixOutOfDate = true;
m_bIsProjectionMatrixOutOfDate = true;
m_bIsWorldViewMatrixOutOfDate = true;
m_bIsWorldViewProjMatrixOutOfDate = true;
m_bIsInverseViewMatrixOutOfDate = true;
m_bIsInverseWorldViewMatrixOutOfDate = true;
m_bIsInverseTransposeWorldViewMatrixOutOfDate = true;
// backup the main cam's matrix here [10/25/2011 Kaiming]
//
m_matBackupViewMatrix = getViewMatrix();
m_matBackupViewMatrix.Transpose();
m_matBackupProjMatrix = getProjectionMatrix();
m_matBackupProjMatrix.Transpose();
m_matBackupViewProjMatrix = m_matBackupProjMatrix * m_matBackupViewMatrix;
}
void gkShaderParamDataSource::setShadowCascadeCamera(const CCamera* cam, uint8 index)
{
const Matrix34& m34 = cam->GetMatrix();
float Near = cam->GetNearPlane(), Far = cam->GetFarPlane();
float wT = tanf(cam->GetFov()*0.5f)*Near, wB = -wT;
float wR = wT * cam->GetProjRatio(), wL = -wR;
m_pShadowsCamera[index]->Frustum(wL + cam->GetAsymL(), wR + cam->GetAsymR(), wB + cam->GetAsymB(), wT + cam->GetAsymT(), Near, Far);
Vec3 vEye = cam->GetPosition();
Vec3 vAt = vEye + Vec3(m34(0, 1), m34(1, 1), m34(2, 1));
Vec3 vUp = Vec3(m34(0, 2), m34(1, 2), m34(2, 2));
m_pShadowsCamera[index]->LookAt(vEye, vAt, vUp);
}
//-----------------------------------------------------------------------
// void gkShaderParamDataSource::setCurrentRenderTarget( const gkRenderTarget* target )
// {
// m_pCurrentRenderTarget = target;
// }
//-----------------------------------------------------------------------
const Matrix44& gkShaderParamDataSource::getWorldMatrix(void) const
{
if (m_bIsWorldMatrixOutOfDate)
{
m_pCurrentRenderable->getWorldTransforms(&m_matWorldMatrix);
m_bIsWorldMatrixOutOfDate = false;
}
return m_matWorldMatrix;
}
//-----------------------------------------------------------------------
const Matrix44& gkShaderParamDataSource::getViewMatrix(void) const
{
if (m_bIsViewMatrixOutOfDate)
{
m_pCurrentCamera->GetModelviewMatrix((float*)(&m_matViewMatrix));
m_bIsViewMatrixOutOfDate = false;
}
return m_matViewMatrix;
}
//-----------------------------------------------------------------------
const Matrix44& gkShaderParamDataSource::getProjectionMatrix(void) const
{
if (m_bIsProjectionMatrixOutOfDate)
{
// hacking way of ortho frustum [10/4/2011 Kaiming]
//if (m_pCam->GetFov() > 0.15f)
m_pCurrentCamera->GetProjectionMatrix((float*)(&m_matProjectionMatrix));
// MSAA process [11/27/2011 Kaiming]
if (g_pRendererCVars->r_PostMsaa)
{
// static int nFrameID = -1;
static Vec3 pOffset = Vec3(0, 0, 0);
// if( nFrameID != gEnv->p )
// {
// Vec2 offs[4] =
// {
// Vec2(0.96f,0.25f),
// Vec2(-0.25f,0.96f),
// Vec2(-0.96f,-0.25f),
// Vec2(0.25f,-0.96f),
// };
// cr2
Vec2 offs[2] =
{
Vec2(-1.f, -1.f),
Vec2(1.f, 1.f),
// Vec2(-0.96f,-0.25f),
// Vec2(0.25f,-0.96f),
};
int nCurrID = gEnv->pProfiler->getFrameCount() % 2; // select 2x msaa or 4x msaa
pOffset.x = (offs[nCurrID].x / (float)gEnv->pRenderer->GetScreenWidth()) * .5f;
pOffset.y = (offs[nCurrID].y / (float)gEnv->pRenderer->GetScreenHeight()) * .5f;
// nFrameID = GetFrameID();
// }
m_matProjectionMatrix.m20 += pOffset.x;
m_matProjectionMatrix.m21 += pOffset.y;
}
m_bIsProjectionMatrixOutOfDate = false;
}
return m_matProjectionMatrix;
}
//-----------------------------------------------------------------------
const Matrix44& gkShaderParamDataSource::getInverseViewMatrix(void) const
{
if (m_bIsInverseViewMatrixOutOfDate)
{
m_matInverseViewMatrix = getViewMatrix().GetInverted();
m_bIsInverseViewMatrixOutOfDate = false;
}
return m_matInverseViewMatrix;
}
//-----------------------------------------------------------------------
const Matrix44& gkShaderParamDataSource::getInverseWorldMatrix(void) const
{
if (m_bIsInverseWorldMatrixOutOfDate)
{
m_matInverseWorldMatrix = getWorldMatrix().GetInverted();
m_bIsInverseWorldMatrixOutOfDate = false;
}
return m_matInverseWorldMatrix;
}
//-----------------------------------------------------------------------
const Matrix44& gkShaderParamDataSource::getWorldViewProjMatrix(void) const
{
if (m_bIsWorldViewProjMatrixOutOfDate)
{
m_matWorldViewProjMatrix = getWorldViewMatrix() * getProjectionMatrix();
m_bIsWorldViewProjMatrixOutOfDate = false;
}
return m_matWorldViewProjMatrix;
}
//-----------------------------------------------------------------------
const Matrix44& gkShaderParamDataSource::getWorldViewMatrix(void) const
{
if (m_bIsWorldViewMatrixOutOfDate)
{
m_matWorldViewMatrix = getWorldMatrix() * getViewMatrix();
m_bIsWorldViewMatrixOutOfDate = false;
}
return m_matWorldViewMatrix;
}
//////////////////////////////////////////////////////////////////////////
const Matrix44& gkShaderParamDataSource::getViewProjMatrix(void) const
{
if (m_bIsViewProjMatrixOutOfDate)
{
m_matViewProjMatrix = getViewMatrix() * getProjectionMatrix();
m_bIsViewProjMatrixOutOfDate = false;
}
return m_matViewProjMatrix;
}
//-----------------------------------------------------------------------
void gkShaderParamDataSource::setLightDir(const Vec3& lightdir)
{
m_vLightDir = lightdir.GetNormalized();/*.GetRotated(Vec3(1,0,0), -g_PI * 0.5f);*/
Matrix44 ViewT = getViewMatrix();
ViewT.Transpose();
m_vLightDirInViewSpace = ViewT.TransformVector(m_vLightDir);
}
const Matrix44& gkShaderParamDataSource::getViewMatrix_ShadowCascade(uint8 index) const
{
if (index < 3)
{
m_pShadowsCamera[index]->GetModelviewMatrix((float*)(&(m_matViewMatrix_ShadowCascade[index])));
}
return m_matViewMatrix_ShadowCascade[index];
}
const Matrix44& gkShaderParamDataSource::getProjectionMatrix_ShadowCascade(uint8 index) const
{
if (index < 3)
{
m_pShadowsCamera[index]->GetProjectionMatrix((float*)(&(m_matProjectionMatrix_ShadowCascade[index])));
}
return m_matProjectionMatrix_ShadowCascade[index];
}
const Matrix44& gkShaderParamDataSource::getWorldViewProjMatrix_ShadowCascade(uint8 index) const
{
if (index < 3)
{
m_matWorldViewProjMatrix_ShadowCascade[index] = getWorldViewMatrix_ShadowCascade(index) * getProjectionMatrix_ShadowCascade(index);
}
return m_matWorldViewProjMatrix_ShadowCascade[index];
}
const Matrix44& gkShaderParamDataSource::getWorldViewMatrix_ShadowCascade(uint8 index) const
{
if (index < 3)
{
m_matWorldViewMatrix_ShadowCascade[index] = getWorldMatrix() * getViewMatrix_ShadowCascade(index);
}
return m_matWorldViewMatrix_ShadowCascade[index];
}
const Matrix44& gkShaderParamDataSource::getInverseViewMatrix_ShadowCascade(uint8 index) const
{
if (index < 3)
{
m_matInverseViewMatrix_ShadowCascade[index] = getViewMatrix_ShadowCascade(index).GetInverted();
}
return m_matInverseViewMatrix_ShadowCascade[index];
}
// TODO: 余下的取值函数以后补全
| {
"pile_set_name": "Github"
} |
$NetBSD: patch-ac,v 1.1.1.1 2003/07/24 16:47:52 jschauma Exp $
--- hier.c.orig Thu Sep 30 21:25:58 1999
+++ hier.c
@@ -2,19 +2,16 @@
void hier()
{
- h(auto_home,-1,-1,02755);
+ c(auto_home,"lib","libdjbfft.a",-1,-1,0644);
- d(auto_home,"lib",-1,-1,02755);
- c(auto_home,"lib","djbfft.a",-1,-1,0644);
-
- d(auto_home,"include",-1,-1,02755);
- c(auto_home,"include","real4.h",-1,-1,0644);
- c(auto_home,"include","real8.h",-1,-1,0644);
- c(auto_home,"include","complex4.h",-1,-1,0644);
- c(auto_home,"include","complex8.h",-1,-1,0644);
- c(auto_home,"include","fftc4.h",-1,-1,0644);
- c(auto_home,"include","fftc8.h",-1,-1,0644);
- c(auto_home,"include","fftr4.h",-1,-1,0644);
- c(auto_home,"include","fftr8.h",-1,-1,0644);
- c(auto_home,"include","fftfreq.h",-1,-1,0644);
+ d(auto_home,"include/djbfft",-1,-1,0755);
+ c(auto_home,"include/djbfft","real4.h",-1,-1,0644);
+ c(auto_home,"include/djbfft","real8.h",-1,-1,0644);
+ c(auto_home,"include/djbfft","complex4.h",-1,-1,0644);
+ c(auto_home,"include/djbfft","complex8.h",-1,-1,0644);
+ c(auto_home,"include/djbfft","fftc4.h",-1,-1,0644);
+ c(auto_home,"include/djbfft","fftc8.h",-1,-1,0644);
+ c(auto_home,"include/djbfft","fftr4.h",-1,-1,0644);
+ c(auto_home,"include/djbfft","fftr8.h",-1,-1,0644);
+ c(auto_home,"include/djbfft","fftfreq.h",-1,-1,0644);
}
| {
"pile_set_name": "Github"
} |
// Copyright 2019 Chaos Mesh Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"context"
"fmt"
"github.com/go-logr/logr"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/client-go/tools/record"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/chaos-mesh/chaos-mesh/controllers/common"
"github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
"github.com/chaos-mesh/chaos-mesh/controllers/iochaos"
"github.com/chaos-mesh/chaos-mesh/pkg/utils"
)
// IoChaosReconciler reconciles an IoChaos object
type IoChaosReconciler struct {
client.Client
client.Reader
record.EventRecorder
Log logr.Logger
}
// +kubebuilder:rbac:groups=chaos-mesh.org,resources=iochaos,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=chaos-mesh.org,resources=iochaos/status,verbs=get;update;patch
// Reconcile reconciles an IOChaos resource
func (r *IoChaosReconciler) Reconcile(req ctrl.Request) (result ctrl.Result, err error) {
logger := r.Log.WithValues("reconciler", "iochaos")
if !common.ControllerCfg.ClusterScoped && req.Namespace != common.ControllerCfg.TargetNamespace {
// NOOP
logger.Info("ignore chaos which belongs to an unexpected namespace within namespace scoped mode",
"chaosName", req.Name, "expectedNamespace", common.ControllerCfg.TargetNamespace, "actualNamespace", req.Namespace)
return ctrl.Result{}, nil
}
chaos := &v1alpha1.IoChaos{}
if err := r.Client.Get(context.Background(), req.NamespacedName, chaos); err != nil {
if apierrors.IsNotFound(err) {
r.Log.Info("io chaos not found")
} else {
r.Log.Error(err, "unable to get io chaos")
}
return ctrl.Result{}, nil
}
scheduler := chaos.GetScheduler()
duration, err := chaos.GetDuration()
if err != nil {
r.Log.Error(err, fmt.Sprintf("unable to get iochaos[%s/%s]'s duration", chaos.Namespace, chaos.Name))
return ctrl.Result{}, err
}
if scheduler == nil && duration == nil {
return r.commonIoChaos(chaos, req)
} else if scheduler != nil && duration != nil {
return r.scheduleIoChaos(chaos, req)
}
if err != nil {
if chaos.IsDeleted() || chaos.IsPaused() {
r.Event(chaos, v1.EventTypeWarning, utils.EventChaosRecoverFailed, err.Error())
} else {
r.Event(chaos, v1.EventTypeWarning, utils.EventChaosInjectFailed, err.Error())
}
}
return result, nil
}
func (r *IoChaosReconciler) commonIoChaos(chaos *v1alpha1.IoChaos, req ctrl.Request) (ctrl.Result, error) {
cr := iochaos.NewCommonReconciler(r.Client, r.Reader, r.Log.WithValues("iochaos", req.NamespacedName), req, r.EventRecorder)
return cr.Reconcile(req)
}
func (r *IoChaosReconciler) scheduleIoChaos(chaos *v1alpha1.IoChaos, req ctrl.Request) (ctrl.Result, error) {
sr := iochaos.NewTwoPhaseReconciler(r.Client, r.Reader, r.Log.WithValues("iochaos", req.NamespacedName), req, r.EventRecorder)
return sr.Reconcile(req)
}
func (r *IoChaosReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&v1alpha1.IoChaos{}).
Complete(r)
}
| {
"pile_set_name": "Github"
} |

# Chroxy [](https://travis-ci.org/holsee/chroxy)
A proxy service to mediate access to Chrome that is run in headless mode,
for use in high-frequency application load testing, end-user behaviour
simulations and programmatic access to Chrome Devtools.
Enables automatic initialisation of the underlying chrome browser pages upon the
request for a connection, as well as closing the page once the WebSocket
connection is closed.
This project was born out of necessity, as we needed to orchestrate a large
number of concurrent browser scenario executions, with low-level control and
advanced introspection capabilities.
## Features
* Direct WebSocket connections to chrome pages, speaking [Chrome Remote Debug
protocol](https://chromedevtools.github.io/devtools-protocol/).
* Provides connections to Chrome Browser Pages via WebSocket connection.
* Manages Chrome Browser process via Erlang processes using `erlexec`
* OS Process supervision and resiliency through automatic restart on crash.
* Uses Chrome Remote Debugging Protocol for optimal client compatibility.
* Transparent Dynamic Proxy provides automatic resource cleanup.
## Cowboy Compatibility
Cowboy is a major dependency of Phoenix, as such here is a little notice as to
which versions of cowboy are hard dependencies of Chroxy. This notice will be
removed at version 1.0 of Chroxy.
`Cowboy 1.x` <= version 0.5.1
`Cowboy 2.x` > version 0.6.0
## Project Goals
The objective of this project is to enable connections to headless chrome
instances with *minimal overhead and abstractions*. Unlike browser testing
frameworks such as `Hound` and `Wallaby`, Chroxy aims to provide direct
unfettered access to the underlying browser using the [Chrome Debug
protocol](https://chromedevtools.github.io/devtools-protocol/) whilst
enabling many 1000s of concurrent connections channelling these to an underlying
chrome browser resource pool.
### Elixir Supervision of Chrome OS Processes - Resiliency
Chroxy uses Elixir processes and OTP supervision to manage the chrome instances,
as well as including a transparent proxy to facilitate automatic initialisation
and termination of the underlying chrome page based on the upstream connection
lifetime.
## Getting Started
_Get dependencies and compile:_
```
$ mix do deps.get, compile
```
_Run the Chroxy Server:_
```
$ mix run --no-halt
```
_Run with an attached session:_
```
$ iex -S mix
```
_Run Docker image_
Note: Chrome required a bump in shared memory allocation when running within
docker in order to function in a stable manner.
Exposes 1330, and 1331 (default ports for connection api and chrome proxy endpoint).
```
docker build . -t chroxy
docker run --shm-size 2G -p 1330:1330 -p 1331:1331 chroxy
```
## Operation Examples:
### Using [Chroxy Client](https://github.com/holsee/chroxy_client) & `ChromeRemoteInterface`
_Establish 100 Browser Connections:_
``` elixir
clients = Enum.map(1..100, fn(_) ->
ChroxyClient.page_session!(%{host: "localhost", port: 1330})
end)
```
_Run 100 Asynchronous browser operations:_
``` elixir
Task.async_stream(clients, fn(client) ->
url = "https://github.com/holsee"
{:ok, _} = ChromeRemoteInterface.RPC.Page.navigate(client, %{url: url})
end, timeout: :infinity) |> Stream.run
```
You can then use any `Page` related functionality using
`ChromeRemoteInterface`.
### Use any client that speaks Chrome Debug Protocol:
_Get the address for a connection:_
```
$ curl http://localhost:1330/api/v1/connection
ws://localhost:1331/devtools/page/2CD7F0BC05863AB665D1FB95149665AF
```
With this address you can establish the connection to the chrome instance (which
is routed via a transparent proxy).
## Configuration
The configuration is designed to be friendly for containerisation as such uses
environment variables
### Chroxy as a Library
``` elixir
def deps do
[{:chroxy, "~> 0.3"}]
end
```
If using Chroxy as a dependency of another mix projects you may wish to leverage
the configuration implementation of Chroxy by replication the configuration in
`"../deps/chroxy/config/config.exs"`.
Example: Create a Page Session, Registering for Event and Navigating to URL
``` elixir
ws_addr = Chroxy.connection()
{:ok, page} = ChromeRemoteInterface.PageSession.start_link(ws_addr)
ChromeRemoteInterface.RPC.Page.enable(page)
ChromeRemoteInterface.PageSession.subscribe(page, "Page.loadEventFired", self())
url = "https://github.com/holsee"
{:ok, _} = ChromeRemoteInterface.RPC.Page.navigate(page, %{url: url})
# Message Received by self() => {:chrome_remote_interface, "Page.loadEventFired", _}
```
### Configuration Variables
Ports, Proxy Host and Endpoint Scheme are managed via Env Vars.
| Variable | Default | Desc. |
| :------------------------ | :------------ | :--------------------------------------------------------- |
| CHROXY_CHROME_PORT_FROM | 9222 | Starting port in the Chrome Browser port range |
| CHROXY_CHROME_PORT_TO | 9223 | Last port in the Chrome Browser port range |
| CHROXY_PROXY_HOST | "127.0.0.1" | Host which is substituted to route connections via proxy |
| CHROXY_PROXY_PORT | 1331 | Port which proxy listener will accept connections on |
| CHROXY_ENDPOINT_SCHEME | :http | `HTTP` or `HTTPS` |
| CHROXY_ENDPOINT_PORT | 1330 | HTTP API will register on this port |
| CHROXY_CHROME_SERVER_PAGE_WAIT_MS | 200 | Milliseconds to wait after asking chrome to create a page |
| CHROME_CHROME_SERVER_CRASH_DUMPS_DIR | "/tmp" | Directory to which chrome will write crash dumps |
## Components
### Proxy
An intermediary TCP proxy is in place to allow for monitoring of the _upstream_
client and _downstream_ chrome RSP web socket connections, in order to clean up
resources after connections are closed.
`Chroxy.ProxyListener` - Incoming Connection Management & Delegation
* Listens for incoming connections on `CHROXY_PROXY_HOST`:`CHROXY_PROXY_PORT`.
* Exposes `accept/1` function which will accept the next _upstream_ TCP connection and
delegate the connection to a `ProxyServer` process along with the `proxy_opts`
which enables the dynamic configuration of the _downstream_ connection.
`Chroxy.ProxyServer` - Dynamically Configured Transparent Proxy
* A dynamically configured transparent proxy.
* Manages delegated connection as the _upstream_ connection.
* Establishes _downstream_ connection based on `proxy_opts` or
`ProxyServer.Hook.up/2` hook modules response, at initialisation.
`Chroxy.ProxyServer.Hook` - Behaviour for `ProxyServer` hooks. Example: `ChromeProxy`
* A mechanism by which a module/server can be invoked when a `ProxyServer`
process is coming _up_ or _down_.
* Two _optional_ callbacks can be implemented:
* `@spec up(indentifier(), proxy_opts()) :: proxy_opts()`
* provides the registered process with the option to add or change proxy
options prior to downstream connection initialisation.
* `@spec down(indentifier(), proxy_state) :: :ok`
* provides the registered process with a signal that the proxy connection
is about to terminate, due to either _upstream_ or _downstream_
connections closing.
### Chrome Browser Management
Chrome is the first browser supported, and the following server processes manage
the communication and lifetime of the Chrome Browsers and Tabs.
`Chroxy.ChromeProxy` - Implements `ProxyServer.Hook` for Chrome resource management
* Exposes function `connection/1` which returns the websocket connection
to the browser tab, with the proxy host and port substituted in order to
route the connection via the underlying `ProxyServer` process.
* Registers for callbacks from the underlying `ProxyServer`, implementing the
`down/2` callback in order to clean up the Chrome resource when connections
close.
`Chroxy.ChromeServer` - Wraps Chrome Browser OS Process
* Process which manages execution and control of a Chrome Browser OS process.
* Provides basic API wrapper to manage the required browser level functionality
around page creation, access and closing.
* Translates browser logging to elixir logging, with correct levels.
`Chroxy.BrowserPool` - Inits & Controls access to pool of browser processes
* Exposes `connection/0` function which will return a WebSocket connection to a
browser tab, from a random browser process in the managed pool.
`Chroxy.BrowerPool.Chrome` - Chrome Process Pool
* Manages `ChromeServer` process pool, responsible for spawning a browser
process for each defined PORT in the port range configured.
### HTTP API - `Chroxy.Endpoint`
`GET /api/v1/connection`
Returns WebSocket URI `ws://` to a Chrome Browser Page which is routed via the
Proxy. This is the first port of call for an external client connecting to the service.
Request:
```
$ curl http://localhost:1330/api/v1/connection
```
Response:
```
ws://localhost:1331/devtools/page/2CD7F0BC05863AB665D1FB95149665AF
```
## Kubernetes
The following is an example configuration which can be used to run Chroxy on
Kubernetes.
deployment.yaml
```yaml
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: crawler
namespace: default
labels:
app: myApp
tier: crawler
spec:
replicas: 1
revisionHistoryLimit: 1
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 0
maxSurge: 1
selector:
matchLabels:
app: myApp
tier: crawler
template:
metadata:
labels:
app: myApp
tier: crawler
spec:
containers:
- image: eu.gcr.io/..../...:latest # your consumer
name: api
imagePullPolicy: Always
resources:
requests:
cpu: 30m
memory: 100Mi
ports:
- containerPort: 4000
env:
- name: USER_AGENT
value: ...
- name: INSTANCE_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
# [START chroxy]
- name: headless-chrome
image: eu.gcr.io/..../chroxy:latest # chroxy
imagePullPolicy: Always
resources:
requests:
cpu: 30m
memory: 100Mi
env:
- name: CHROXY_CHROME_PORT_FROM
value: "9222"
- name: CHROXY_CHROME_PORT_TO
value: "9223"
ports:
- containerPort: 1331
- containerPort: 1330
# [END chroxy]
```
service.yaml
```yaml
apiVersion: v1
kind: Service
metadata:
namespace: default
name: crawler-api
labels:
app: myApp
tier: crawler
spec:
selector:
app: myApp
tier: crawler
ports:
- port: 4000
protocol: TCP
```
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.