answer
stringlengths
15
1.25M
'use strict'; /*global require, after, before*/ var async = require('async'), assert = require('assert'), db = require('../mocks/databasemock'); describe('Set methods', function() { describe('setAdd()', function() { it('should add to a set', function(done) { db.setAdd('testSet1', 5, function(err) { assert.equal(err, null); assert.equal(arguments.length, 1); done(); }); }); it('should add an array to a set', function(done) { db.setAdd('testSet1', [1, 2, 3, 4], function(err) { assert.equal(err, null); assert.equal(arguments.length, 1); done(); }); }); }); describe('getSetMembers()', function() { before(function(done) { db.setAdd('testSet2', [1,2,3,4,5], done); }); it('should return an empty set', function(done) { db.getSetMembers('doesnotexist', function(err, set) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.equal(Array.isArray(set), true); assert.equal(set.length, 0); done(); }); }); it('should return a set with all elements', function(done) { db.getSetMembers('testSet2', function(err, set) { assert.equal(err, null); assert.equal(set.length, 5); set.forEach(function(value) { assert.notEqual(['1', '2', '3', '4', '5'].indexOf(value), -1); }); done(); }); }); }); describe('setsAdd()', function() { it('should add to multiple sets', function(done) { db.setsAdd(['set1', 'set2'], 'value', function(err) { assert.equal(err, null); assert.equal(arguments.length, 1); done(); }); }); }); describe('getSetsMembers()', function() { before(function(done) { db.setsAdd(['set3', 'set4'], 'value', done); }); it('should return members of two sets', function(done) { db.getSetsMembers(['set3', 'set4'], function(err, sets) { assert.equal(err, null); assert.equal(Array.isArray(sets), true); assert.equal(arguments.length, 2); assert.equal(Array.isArray(sets[0]) && Array.isArray(sets[1]), true); assert.strictEqual(sets[0][0], 'value'); assert.strictEqual(sets[1][0], 'value'); done(); }); }); }); describe('isSetMember()', function() { before(function(done) { db.setAdd('testSet3', 5, done); }); it('should return false if element is not member of set', function(done) { db.isSetMember('testSet3', 10, function(err, isMember) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.equal(isMember, false); done(); }); }); it('should return true if element is a member of set', function(done) { db.isSetMember('testSet3', 5, function(err, isMember) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.equal(isMember, true); done(); }); }); }); describe('isSetMembers()', function() { before(function(done) { db.setAdd('testSet4', [1, 2, 3, 4, 5], done); }); it('should return an array of booleans', function(done) { db.isSetMembers('testSet4', ['1', '2', '10', '3'], function(err, members) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.equal(Array.isArray(members), true); assert.deepEqual(members, [true, true, false, true]); done(); }); }); }); describe('isMemberOfSets()', function() { before(function(done) { db.setsAdd(['set1', 'set2'], 'value', done); }); it('should return an array of booleans', function(done) { db.isMemberOfSets(['set1', 'testSet1', 'set2', 'doesnotexist'], 'value', function(err, members) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.equal(Array.isArray(members), true); assert.deepEqual(members, [true, false, true, false]); done(); }); }); }); describe('setCount()', function() { before(function(done) { db.setAdd('testSet5', [1,2,3,4,5], done); }); it('should return the element count of set', function(done) { db.setCount('testSet5', function(err, count) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.strictEqual(count, 5); done(); }); }); }); describe('setsCount()', function() { before(function(done) { async.parallel([ async.apply(db.setAdd, 'set5', [1,2,3,4,5]), async.apply(db.setAdd, 'set6', 1), async.apply(db.setAdd, 'set7', 2) ], done); }); it('should return the element count of sets', function(done) { db.setsCount(['set5', 'set6', 'set7', 'doesnotexist'], function(err, counts) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.equal(Array.isArray(counts), true); assert.deepEqual(counts, [5, 1, 1, 0]); done(); }); }); }); describe('setRemove()', function() { before(function(done) { db.setAdd('testSet6', [1, 2], done); }); it('should remove a element from set', function(done) { db.setRemove('testSet6', '2', function(err) { assert.equal(err, null); assert.equal(arguments.length, 1); db.isSetMember('testSet6', '2', function(err, isMember) { assert.equal(err, null); assert.equal(isMember, false); done(); }); }); }); }); describe('setsRemove()', function() { before(function(done) { db.setsAdd(['set1', 'set2'], 'value', done); }); it('should remove a element from multiple sets', function(done) { db.setsRemove(['set1', 'set2'], 'value', function(err) { assert.equal(err, null); assert.equal(arguments.length, 1); db.isMemberOfSets(['set1', 'set2'], 'value', function(err, members) { assert.equal(err, null); assert.deepEqual(members, [false, false]); done(); }); }); }); }); describe('setRemoveRandom()', function() { before(function(done) { db.setAdd('testSet7', [1,2,3,4,5], done); }); it('should remove a random element from set', function(done) { db.setRemoveRandom('testSet7', function(err, element) { assert.equal(err, null); assert.equal(arguments.length, 2); db.isSetMember('testSet', element, function(err, ismember) { assert.equal(err, null); assert.equal(ismember, false); done(); }); }); }); }); after(function(done) { db.flushdb(done); }); });
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; using System.Linq.Expressions; namespace BusinessLogic.Repositories { public class Repository<T> : IRepository<T> where T : class { private readonly DbContext _context; private readonly DbSet<T> _dbSet; public Repository(DbContext context) { this._context = context; this._dbSet = context.Set<T>(); } public virtual void Add(T entity) { this._dbSet.Add(entity); this._context.SaveChanges(); } public virtual void Delete(int id, string userID) { var entry = this._dbSet.Find(id); this._dbSet.Remove(entry); this._context.SaveChanges(); } public IQueryable<T> GetAll() { return this._dbSet.AsQueryable(); } public T GetByID(int? id, string userID) { return this._dbSet.Find(id); } public void Edit(T entity) { this._context.Set<T>().AddOrUpdate(entity); this._context.SaveChanges(); } public void Edit(List<T> entities) { foreach (var entity in entities) Edit(entity); } public int GetCount() { return this._dbSet.Count(); } private IEnumerable<T> Find(Expression<Func<T, bool>> predicate) { return this._dbSet.Where(predicate); } } }
// pythonFlu - Python wrapping for OpenFOAM C++ API // This program is free software: you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // Author : Alexey PETROV #ifndef <API key> #define <API key> %import "Foam/src/OpenFOAM/fields/tmp/tmp.i" %import "Foam/ext/common/ext_tmp.hxx" %define <API key>( Type, TPatchField, TMesh ) %typecheck( <API key> ) Foam::GeometricField< Type, TPatchField, TMesh >& { void *ptr; int res_T = SWIG_ConvertPtr( $input, (void **) &ptr, $descriptor( Foam::GeometricField< Type, TPatchField, TMesh > * ), 0 ); int res_tmpT = SWIG_ConvertPtr( $input, (void **) &ptr, $descriptor( Foam::tmp< Foam::GeometricField< Type, TPatchField, TMesh > > * ), 0 ); int res_ext_tmpT = SWIG_ConvertPtr( $input, (void **) &ptr, $descriptor( Foam::ext_tmp< Foam::GeometricField< Type, TPatchField, TMesh > > * ), 0 ); $1 = SWIG_CheckState( res_T ) || SWIG_CheckState( res_tmpT ) || SWIG_CheckState( res_ext_tmpT ); } %typemap( in ) Foam::GeometricField< Type, TPatchField, TMesh >& { void *argp = 0; int res = 0; res = SWIG_ConvertPtr( $input, &argp, $descriptor( Foam::GeometricField< Type, TPatchField, TMesh > * ), %convertptr_flags ); if ( SWIG_IsOK( res )&& argp ){ Foam::GeometricField< Type, TPatchField, TMesh > * res = %reinterpret_cast( argp, Foam::GeometricField< Type, TPatchField, TMesh >* ); $1 = res; } else { res = SWIG_ConvertPtr( $input, &argp, $descriptor( Foam::tmp< Foam::GeometricField< Type, TPatchField, TMesh > >* ), %convertptr_flags ); if ( SWIG_IsOK( res ) && argp ) { Foam::tmp<Foam::GeometricField< Type, TPatchField, TMesh> >* tmp_res =%reinterpret_cast( argp, Foam::tmp< Foam::GeometricField< Type, TPatchField, TMesh > > * ); $1 = tmp_res->operator->(); } else { res = SWIG_ConvertPtr( $input, &argp, $descriptor( Foam::ext_tmp< Foam::GeometricField< Type, TPatchField, TMesh > >* ), %convertptr_flags ); if ( SWIG_IsOK( res ) && argp ) { Foam::ext_tmp<Foam::GeometricField< Type, TPatchField, TMesh> >* tmp_res =%reinterpret_cast( argp, Foam::ext_tmp< Foam::GeometricField< Type, TPatchField, TMesh > > * ); $1 = tmp_res->operator->(); } else { %argument_fail( res, "$type", $symname, $argnum ); } } } } %enddef %import "Foam/src/OpenFOAM/primitives/scalar.i" %include "Foam/src/finiteVolume/volMesh.hpp" %include "Foam/src/finiteVolume/fields/fvPatchFields/fvPatchField.cpp" <API key>( Foam::scalar, Foam::fvPatchField, Foam::volMesh ); %import "Foam/src/OpenFOAM/primitives/vector.i" %include "Foam/src/finiteVolume/volMesh.hpp" %include "Foam/src/finiteVolume/fields/fvPatchFields/fvPatchField.cpp" <API key>( Foam::Vector< Foam::scalar >, Foam::fvPatchField, Foam::volMesh ); %import "Foam/src/OpenFOAM/primitives/tensor.i" %include "Foam/src/finiteVolume/volMesh.hpp" %include "Foam/src/finiteVolume/fields/fvPatchFields/fvPatchField.cpp" <API key>( Foam::Tensor< Foam::scalar >, Foam::fvPatchField, Foam::volMesh ); %import "Foam/src/OpenFOAM/primitives/symmTensor.i" %include "Foam/src/finiteVolume/volMesh.hpp" %include "Foam/src/finiteVolume/fields/fvPatchFields/fvPatchField.cpp" <API key>( Foam::SymmTensor< Foam::scalar >, Foam::fvPatchField, Foam::volMesh ); %import "Foam/src/OpenFOAM/primitives/sphericalTensor.i" %include "Foam/src/finiteVolume/volMesh.hpp" %include "Foam/src/finiteVolume/fields/fvPatchFields/fvPatchField.cpp" <API key>( Foam::SphericalTensor< Foam::scalar >, Foam::fvPatchField, Foam::volMesh ); %import "Foam/src/OpenFOAM/primitives/scalar.i" %include "Foam/src/finiteVolume/surfaceMesh.hpp" %include "Foam/src/finiteVolume/fields/fvsPatchFields/fvsPatchField.cpp" <API key>( Foam::scalar, Foam::fvsPatchField, Foam::surfaceMesh ); %import "Foam/src/OpenFOAM/primitives/vector.i" %include "Foam/src/finiteVolume/surfaceMesh.hpp" %include "Foam/src/finiteVolume/fields/fvsPatchFields/fvsPatchField.cpp" <API key>( Foam::Vector< Foam::scalar >, Foam::fvsPatchField, Foam::surfaceMesh ); %import "Foam/src/OpenFOAM/primitives/tensor.i" %include "Foam/src/finiteVolume/surfaceMesh.hpp" %include "Foam/src/finiteVolume/fields/fvsPatchFields/fvsPatchField.cpp" <API key>( Foam::Tensor< Foam::scalar >, Foam::fvsPatchField, Foam::surfaceMesh ); #endif
#ifndef VALUE_H_ #define VALUE_H_ // Cost parameters #define CARCOST 100 #define TICKETCOST 300 #define CENTSPERLITRE 130 #define METERSPERLITRE 15000 // Headers #include <limits.h> #include <immintrin.h> #include "instance.h" #include "random.h" #include "macros.h" #include "types.h" #define COST(I, DR, L) ((DR)[(I)] ? (PATHCOST((L)[I]) + CARCOST) : TICKETCOST) #define PATHCOST(p) ROUND(value, (float)(p) / METERSPERLITRE * CENTSPERLITRE) #define EURO(i) ((float)(i) / 100) #define R5 2520 #define R4 90 #define R3 6 meter minpath(agent *c, agent n, agent dr, const meter *sp); #endif /* VALUE_H_ */
// only be used by a person authorised under and to the extent permitted // by a subsisting licensing agreement from ARM Limited or its affiliates // or between you and a party authorised by ARM // ALL RIGHT RESERVED // This entire notice must be reproduced on all copies of this file // and copies of this files may only be made by a person if such person is // from ARM Limited or its affiliates or between you and a party authorised by ARM #ifndef CRYS_RND_H #define CRYS_RND_H #include "crys_error.h" #include "ssi_aes.h" #ifdef __cplusplus extern "C" { #endif /*! @file @brief This file contains the CRYS APIs used for random number generation. The random-number generation module implements referenced standard [SP800-90]. */ /*! Maximal reseed counter - indicates maximal number of requests allowed between reseeds; according to NIST 800-90 it is (2^48 - 1), our restriction is : (0xFFFFFFFF - 0xF).*/ #define <API key> (0xFFFFFFFF - 0xF) /* maximal requested size counter (12 bits active) - maximal count of generated random 128 bit blocks allowed per one request of Generate function according NIST 800-90 it is (2^12 - 1) = 0x3FFFF */ #define <API key> 0x3FFFF /*! AES output block size in words. */ #define <API key> <API key> /* RND seed and additional input sizes */ #define <API key> 12 #ifndef <API key> #define <API key> <API key> #endif /* Max size of generated random vector in bits according uint16_t type of * * input size parameter in CRYS_RND_Generate function */ #define <API key> 0xFFFF /* allowed sizes of AES Key, in words */ #define <API key> 4 #define <API key> 6 #define <API key> 8 /* Definitions of temp buffer for RND_DMA version of CRYS_RND */ /* Definitions of temp buffer for DMA version of CRYS_RND */ #define <API key> 1528 /*! A definition for RAM buffer to be internally used in instantiation (or reseeding) operation. */ typedef struct { /* include the specific fields that are used by the low level */ uint32_t crysRndWorkBuff[<API key>]; }CRYS_RND_WorkBuff_t; #define <API key> CRYS_RND_WorkBuff_t #define crysRndEntrIntBuff crysRndWorkBuff /* RND source buffer inner (entrpopy) offset */ #define <API key> 2 /* Max size for one RNG operation */ #define <API key> 3*1024 /* Size of the expected output buffer used by FIPS KAT */ #define <API key> 64 /* Definition of Fast or Slow mode of random generator (TRNG)*/ typedef enum { CRYS_RND_Fast = 0, CRYS_RND_Slow = 1, CRYS_RND_ModeLast = 0x7FFFFFFF, } CRYS_RND_mode_t; /* The internal state of DRBG mechanism based on AES CTR and CBC-MAC algorithms. It is set as global data defined by the following structure */ typedef struct { /* Seed buffer, consists from concatenated Key||V: max size 12 words */ uint32_t Seed[<API key>]; /* Previous value for continuous test */ uint32_t PreviousRandValue[<API key>]; /* AdditionalInput buffer max size = seed max size words + 4w for padding*/ uint32_t <API key>[<API key>+3]; uint32_t AdditionalInput[<API key>+4]; uint32_t AddInputSizeWords; /* size of additional data set by user, words */ /* entropy source size in words */ uint32_t <API key>; /* reseed counter (32 bits active) - indicates number of requests for entropy since instantiation or reseeding */ uint32_t ReseedCounter; /* key size: 4 or 8 words according to security strength 128 bits or 256 bits*/ uint32_t KeySizeWords; /* State flag (see definition of StateFlag above), containing bit-fields, defining: - b'0: instantiation steps: 0 - not done, 1 - done; - 2b'9,8: working or testing mode: 0 - working, 1 - KAT DRBG test, 2 - KAT TRNG test; b'16: flag defining is Previous random valid or not: 0 - not valid, 1 - valid */ uint32_t StateFlag; /* Trng processing flag - indicates which ROSC lengths are: - allowed (bits 0-3); - total started (bits 8-11); - processed (bits 16-19); - started, but not processed (bits24-27) */ uint32_t TrngProcesState; /* validation tag */ uint32_t ValidTag; /* Rnd source entropy size in bits */ uint32_t EntropySizeBits; } CRYS_RND_State_t; /*! The RND Generate vector function pointer type definition. The prototype intendent for External and CRYS internal RND functions pointers definitions. Full description can be found in ::<API key> function API. */ typedef uint32_t (*<API key>)( \ CRYS_RND_State_t *rndState_ptr, /*context*/ \ uint16_t outSizeBytes, \ uint8_t *out_ptr /*out*/); /*! definition of RND context that includes CRYS RND state structure and a function pointer for rnd generate function */ typedef struct { /* The pointer to internal state of RND */ CRYS_RND_State_t rndState; /* The pointer to user given function for generation random vector */ <API key> rndGenerateVectFunc; } CRYS_RND_Context_t; /*! Required for internal FIPS verification for PRNG KAT. */ typedef struct { CRYS_RND_WorkBuff_t rndWorkBuff; uint8_t rndOutputBuff[<API key>]; } <API key>; /*! @brief This function initializes the RND context. It must be called at least once prior to using this context with any API that requires it as a parameter (e.g., other RND APIs, asymmetric cryptography key generation and signatures). It is called as part of ARM TrustZone CryptoCell library initialization, which initializes and returns the primary RND context. This primary context can be used as a single global context for all RND needs. Alternatively, other contexts may be initialized and used with a more limited scope (for specific applications or specific threads). The call to this function must be followed by a call to ::<API key> API to set the generate vector function. It implements referenced standard [SP800-90] - 10.2.1.3.2 - CTR-DRBG Instantiate algorithm using AES (FIPS-PUB 197) and Derivation Function (DF). \note Additional data can be mixed with the random seed (personalization data or nonce). If required, this data should be provided by calling ::<API key> prior to using this API. @return CRYS_OK on success. @return A non-zero value from crys_rnd_error.h on failure. */ CIMPORT_C CRYSError_t <API key>( CRYS_RND_Context_t *rndContext_ptr, /*!< [in/out] Pointer to the RND context buffer allocated by the user, which is used to maintain the RND state, as well as pointers to the functions used for random vector generation. This context must be saved and provided as a parameter to any API that uses the RND module. \note the context must be cleared before sent to the function. */ CRYS_RND_WorkBuff_t *rndWorkBuff_ptr /*!< [in/out] Scratchpad for the RND module's work. */ ); /*! @brief Clears existing RNG instantiation state. @return CRYS_OK on success. @return A non-zero value from crys_rnd_error.h on failure. */ CIMPORT_C CRYSError_t <API key>( CRYS_RND_Context_t *rndContext_ptr /*!< [in/out] Pointer to the RND context buffer. */ ); /*! @brief This function is used for reseeding the RNG with additional entropy and additional user-provided input. (additional data should be provided by calling ::<API key> prior to using this API). It implements referenced standard [SP800-90] - 10.2.1.4.2 - CTR-DRBG Reseeding algorithm, using AES (FIPS-PUB 197) and Derivation Function (DF). @return CRYS_OK on success. @return A non-zero value from crys_rnd_error.h on failure. */ CIMPORT_C CRYSError_t CRYS_RND_Reseeding( CRYS_RND_Context_t *rndContext_ptr, /*!< [in/out] Pointer to the RND context buffer. */ CRYS_RND_WorkBuff_t *rndWorkBuff_ptr /*!< [in/out] Scratchpad for the RND module's work. */ ); /*! @brief Generates a random vector according to the algorithm defined in referenced standard [SP800-90] - 10.2.1.5.2 - CTR-DRBG. The generation algorithm uses AES (FIPS-PUB 197) and Derivation Function (DF). \note <ul id="noteb"><li> The RND module must be instantiated prior to invocation of this API.</li> <li> In the following cases, Reseeding operation must be performed prior to vector generation:</li> <ul><li> Prediction resistance is required.</li> <li> The function returns <API key>, stating that the Reseed Counter has passed its upper-limit (2^32-2).</li></ul></ul> @return CRYS_OK on success. @return A non-zero value from crys_rnd_error.h on failure. */ CIMPORT_C CRYSError_t <API key>( CRYS_RND_State_t *rndState_ptr, /*!< [in/out] Pointer to the RND state structure, which is part of the RND context structure. Use rndContext->rndState field of the context for this parameter. */ uint16_t outSizeBytes, /*!< [in] The size in bytes of the random vector required. The maximal size is 2^16 -1 bytes. */ uint8_t *out_ptr /*!< [out] The pointer to output buffer. */ ); /*! @brief This function sets the RND vector generation function into the RND context. It must be called after ::<API key>, and prior to any other API that requires the RND context as parameter. It is called as part of ARM TrustZone CryptoCell library initialization, to set the RND vector generation function into the primary RND context, after ::<API key> is called. @return CRYS_OK on success. @return A non-zero value from crys_rnd_error.h on failure. */ CRYSError_t <API key>( CRYS_RND_Context_t *rndContext_ptr, /*!< [in/out] Pointer to the RND context buffer allocated by the user, which is used to maintain the RND state as well as pointers to the functions used for random vector generation. */ <API key> rndGenerateVectFunc /*!< [in] Pointer to the random vector generation function. The pointer should point to the ::<API key> function. */ ); /*! @brief Generates a random vector with specific limitations by testing candidates (described and used in FIPS 186-4: B.1.2, B.4.2 etc.). This function will draw a random vector, compare it to the range limits, and if within range - return it in rndVect_ptr. If outside the range, the function will continue retrying until a conforming vector is found, or the maximal retries limit is exceeded. If maxVect_ptr is provided, rndSizeInBits specifies its size, and the output vector must conform to the range [1 < rndVect < maxVect_ptr]. If maxVect_ptr is NULL, rndSizeInBits specifies the exact required vector size, and the output vector must be the exact same bit size (with its most significant bit = 1). \note The RND module must be instantiated prior to invocation of this API. @return CRYS_OK on success. @return A non-zero value from crys_rnd_error.h on failure. */ CIMPORT_C CRYSError_t <API key>( CRYS_RND_Context_t *rndContext_ptr, /*!< [in/out] Pointer to the RND context buffer. */ uint32_t rndSizeInBits, /*!< [in] The size in bits of the random vector required. The allowed size in range 2 <= rndSizeInBits < 2^19-1, bits. */ uint8_t *maxVect_ptr, /*!< [in] Pointer to the vector defining the upper limit for the random vector output, Given as little-endian byte array. If not NULL, its actual size is treated as [(rndSizeInBits+7)/8] bytes. */ uint8_t *rndVect_ptr /*!< [in/out] Pointer to the output buffer for the random vector. Must be at least [(rndSizeInBits+7)/8] bytes. Treated as little-endian byte array. */ ); /*! @brief Used for adding additional input/personalization data provided by the user, to be later used by the ::<API key>/::CRYS_RND_Reseeding/::<API key> functions. @return CRYS_OK on success. @return A non-zero value from crys_rnd_error.h on failure. */ CIMPORT_C CRYSError_t <API key>( CRYS_RND_Context_t *rndContext_ptr, /*!< [in/out] Pointer to the RND context buffer. */ uint8_t *additonalInput_ptr, /*!< [in] The Additional Input buffer. */ uint16_t additonalInputSize /*!< [in] The size of the Additional Input buffer. Must be <= 48, and a multiple of 4. */ ); /*! @brief The <API key> function sets KAT mode bit into StateFlag of global <API key> structure. The user must call this function before calling functions performing KAT tests. \note Total size of entropy and nonce must be not great than: ::<API key>, defined. @return CRYS_OK on success. @return A non-zero value from crys_rnd_error.h on failure. */ CIMPORT_C CRYSError_t <API key>( CRYS_RND_Context_t *rndContext_ptr, /*!< [in/out] Pointer to the RND context buffer. */ uint8_t *entrData_ptr, /*!< [in] Entropy data. */ uint32_t entrSize, /*!< [in] Entropy size in bytes. */ uint8_t *nonce_ptr, /*!< [in] Nonce. */ uint32_t nonceSize, /*!< [in] Entropy size in bytes. */ CRYS_RND_WorkBuff_t *workBuff_ptr /*!< [out] RND working buffer, must be the same buffer, which should be passed into Instantiation/Reseeding functions. */ ); /*! @brief The <API key> function disables KAT mode bit into StateFlag of global <API key> structure. The user must call this function after KAT tests before actual using RND module (Instantiation etc.). @return CRYS_OK on success. @return A non-zero value from crys_rnd_error.h on failure. */ CIMPORT_C void <API key>( CRYS_RND_Context_t *rndContext_ptr /*!< [in/out] Pointer to the RND context buffer. */ ); #ifdef __cplusplus } #endif #endif /* #ifndef CRYS_RND_H */
namespace Tsu.Voltmeters.Appa { partial class <API key> { <summary> Required designer variable. </summary> private System.ComponentModel.IContainer components; <summary> Clean up any resources being used. </summary> <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { this.Disconnect(); if (disposing && (components != null)) { com2usb.Dispose(); components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code <summary> Required method for Designer support - do not modify the contents of this method with the code editor. </summary> private void InitializeComponent() { components = new System.ComponentModel.Container(); } #endregion } }
# <API key> _namespace: [SMRUCC.genomics.Data.Reactome.LocalMySQL.Tables.gk_current](./index.md)_ DROP TABLE IF EXISTS `<API key>`; /*!40101 SET @saved_cs_client = @@<API key> */; /*!40101 SET <API key> = utf8 */; CREATE TABLE `<API key>` ( `DB_ID` int(10) unsigned NOT NULL, `changedAttribute` text, PRIMARY KEY (`DB_ID`), FULLTEXT KEY `changedAttribute` (`changedAttribute`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET <API key> = @saved_cs_client */;
package ru.trolsoft.utils.files; import ru.trolsoft.utils.StrUtils; import java.io.*; import java.util.Random; public class IntelHexWriter { private final Writer writer; private int segmentAddress = 0; public IntelHexWriter(Writer writer) { if (writer instanceof BufferedWriter) { this.writer = writer; } else { this.writer = new BufferedWriter(writer); } } // public IntelHexWriter(String fileName) throws IOException { // this(new FileWriter(fileName)); public void addData(int offset, byte data[], int bytesPerLine) throws IOException { if (data.length == 0) { return; } //System.out.println("::" + data.length); byte buf[] = new byte[bytesPerLine]; int pos = 0; int bytesToAdd = data.length; while (bytesToAdd > 0) { if (offset % bytesPerLine != 0) { // can be true for first line if offset doesn't aligned buf = new byte[bytesPerLine - offset % bytesPerLine]; } else if (bytesToAdd < bytesPerLine) { // last line buf = new byte[bytesToAdd]; } else if (buf.length != bytesPerLine) { buf = new byte[bytesPerLine]; } System.arraycopy(data, pos, buf, 0, buf.length); // Goto next segment if no more space available in current if (offset + buf.length - 1 > segmentAddress + 0xffff) { int nextSegment = ((offset + bytesPerLine) >> 4) << 4; addSegmentRecord(nextSegment); segmentAddress = nextSegment; } addDataRecord(offset & 0xffff, buf); bytesToAdd -= buf.length; offset += buf.length; pos += buf.length; } } private void addSegmentRecord(int offset) throws IOException { int paragraph = offset >> 4; int hi = (paragraph >> 8) & 0xff; int lo = paragraph & 0xff; int crc = 2 + 2 + hi + lo; crc = (-crc) & 0xff; String rec = ":02000002" + hex(hi) + hex(lo) + hex(crc); write(rec); // 02 0000 02 10 00 EC //:02 0000 04 00 01 F9 } private void addEofRecord() throws IOException { write(":00000001FF"); } private void write(String s) throws IOException { writer.write(s); //writer.write(0x0d); writer.write(0x0a); } private void addDataRecord(int offset, byte[] data) throws IOException { int hi = (offset >> 8) & 0xff; int lo = offset & 0xff; int crc = data.length + hi + lo; String rec = ":" + hex(data.length) + hex(hi) + hex(lo) + "00"; for (byte d : data) { rec += hex(d); crc += d; } crc = (-crc) & 0xff; rec += hex(crc); write(rec); } private static String hex(int b) { return StrUtils.byteToHexStr((byte)b); } public void done() throws IOException { addEofRecord(); writer.flush(); } public static void main(String ... args) throws IOException { IntelHexWriter w = new IntelHexWriter(new OutputStreamWriter(System.out)); // w.addDataRecord(0x0190, new byte[] {0x56, 0x45, 0x52, 0x53, 0x49, 0x4F, 0x4E, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x41, // 0x54, 0x0D, 0x0A}); byte[] data = new byte[Math.abs(new Random().nextInt() % 1024)]; for (int i = 0; i < data.length; i++) { data[i] = (byte) (i % 0xff); } w.addData(0x10000 - 0x100, data, 16); w.done(); } }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_131) on Mon May 29 22:14:24 CST 2017 --> <title>org.cripac.isee.vpe.alg.pedestrian.attr Class Hierarchy</title> <meta name="date" content="2017-05-29"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><! try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title = "org.cripac.isee.vpe.alg.pedestrian.attr Class Hierarchy"; } } catch (err) { } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar.top"> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../../org/cripac/isee/vpe/alg/package-tree.html">Prev</a></li> <li><a href="../../../../../../../org/cripac/isee/vpe/alg/pedestrian/reid/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/cripac/isee/vpe/alg/pedestrian/attr/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if (window == top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.top"> </a></div> <div class="header"> <h1 class="title">Hierarchy For Package org.cripac.isee.vpe.alg.pedestrian.attr</h1> <span class="<API key>">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../../../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li type="circle">org.cripac.isee.vpe.alg.pedestrian.attr.<a href="../../../../../../../org/cripac/isee/vpe/alg/pedestrian/attr/<API key>.html" title="class in org.cripac.isee.vpe.alg.pedestrian.attr"><span class="typeNameLink"><API key></span></a> </li> <li type="circle">org.cripac.isee.vpe.common.<a href="../../../../../../../org/cripac/isee/vpe/common/SparkStreamingApp.html" title="class in org.cripac.isee.vpe.common"><span class="typeNameLink">SparkStreamingApp</span></a> (implements java.io.<a href="http://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>) <ul> <li type="circle">org.cripac.isee.vpe.alg.pedestrian.attr.<a href="../../../../../../../org/cripac/isee/vpe/alg/pedestrian/attr/<API key>.html" title="class in org.cripac.isee.vpe.alg.pedestrian.attr"><span class="typeNameLink"><API key></span></a> </li> </ul> </li> <li type="circle">org.cripac.isee.vpe.common.<a href="../../../../../../../org/cripac/isee/vpe/common/Stream.html" title="class in org.cripac.isee.vpe.common"><span class="typeNameLink">Stream</span></a> (implements java.io.<a href="http://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>) <ul> <li type="circle">org.cripac.isee.vpe.alg.pedestrian.attr.<a href="../../../../../../../org/cripac/isee/vpe/alg/pedestrian/attr/<API key>.RecogStream.html" title="class in org.cripac.isee.vpe.alg.pedestrian.attr"><span class="typeNameLink"><API key>.RecogStream</span></a> </li> </ul> </li> <li type="circle">org.cripac.isee.vpe.ctrl.<a href="../../../../../../../org/cripac/isee/vpe/ctrl/<API key>.html" title="class in org.cripac.isee.vpe.ctrl"><span class="typeNameLink"><API key></span></a> (implements java.io.<a href="http://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>) <ul> <li type="circle">org.cripac.isee.vpe.alg.pedestrian.attr.<a href="../../../../../../../org/cripac/isee/vpe/alg/pedestrian/attr/<API key>.AppPropertyCenter.html" title="class in org.cripac.isee.vpe.alg.pedestrian.attr"><span class="typeNameLink"><API key>.AppPropertyCenter</span></a> </li> </ul> </li> </ul> </li> </ul> <h2 title="Enum Hierarchy">Enum Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Enum</span></a>&lt;E&gt; (implements java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html?is-external=true" title="class or interface in java.lang">Comparable</a>&lt;T&gt;, java.io.<a href="http://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>) <ul> <li type="circle">org.cripac.isee.vpe.alg.pedestrian.attr.<a href="../../../../../../../org/cripac/isee/vpe/alg/pedestrian/attr/<API key>.Algorithm.html" title="enum in org.cripac.isee.vpe.alg.pedestrian.attr"><span class="typeNameLink"><API key>.Algorithm</span></a> </li> </ul> </li> </ul> </li> </ul> </div> <div class="bottomNav"><a name="navbar.bottom"> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../../org/cripac/isee/vpe/alg/package-tree.html">Prev</a></li> <li><a href="../../../../../../../org/cripac/isee/vpe/alg/pedestrian/reid/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/cripac/isee/vpe/alg/pedestrian/attr/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if (window == top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.bottom"> </a></div> </body> </html>
<?php class <API key> extends <API key> { /** * Display the "Server Configuration" form. */ public function serverAction() { $form = new <API key>(); // If a valid form was submitted. if ($this->_request->isPost() && $form->isValid($_POST)) { // Set the options. foreach ($form->getValues() as $option => $value) { set_option($option, $value); } } // Are the current parameters valid? if (<API key>::pingSolrServer()) { // Notify valid connection. $this->_helper->flashMessenger( __('Solr connection is valid.'), 'success' ); } // Notify invalid connection. else $this->_helper->flashMessenger( __('Solr connection is invalid.'), 'error' ); $this->view->form = $form; } /** * Display the "Collection Configuration" form. * * @return void * @author Eric Rochester <erochest@virginia.edu> **/ public function collectionsAction() { if ($this->_request->isPost()) { $this->_updateCollections($this->_request->getPost()); } $this->view->form = $this->_collectionsForm(); } public function <API key>() { $this->view->status = <API key>::getStatusViaHandler(); } /** * This updates the excluded collections. * * @param array $post The post data to update from. * @return void * @author Eric Rochester <erochest@virginia.edu> **/ protected function _updateCollections($post) { $etable = $this->_helper->db->getTable('SolrSearchExclude'); $etable->query("DELETE FROM {$etable->getTableName()};"); $c = 0; if (isset($post['solrexclude'])) { foreach ($post['solrexclude'] as $exc) { $exclude = new SolrSearchExclude(); $exclude->collection_id = $exc; $exclude->save(); $c += 1; } } $this->_helper->_flashMessenger("$c collection(s) excluded."); } /** * This returns the form for the collections. * * @return Zend_Form * @author Eric Rochester <erochest@virginia.edu> **/ protected function _collectionsForm() { $ctable = $this->_helper->db->getTable('Collection'); $collections = $ctable->findBy(array('public' => 1)); $form = new Zend_Form(); $form->setAction(url('solr-search/collections'))->setMethod('post'); $collbox = new <API key>('solrexclude'); $form->addElement($collbox); foreach ($collections as $c) { $title = metadata($c, array('Dublin Core', 'Title')); $collbox->addMultiOption("{$c->id}", $title); } $etable = $this->_helper->db->getTable('SolrSearchExclude'); $excludes = array(); foreach ($etable->findAll() as $exclude) { $excludes[] = "{$exclude->collection_id}"; } $collbox->setValue($excludes); $form->addElement('submit', 'Exclude'); return $form; } /** * Display the "Field Configuration" form. */ public function fieldsAction() { // Get the facet mapping table. $fieldTable = $this->_helper->db->getTable('SolrSearchField'); // If the form was submitted. if ($this->_request->isPost()) { // Gather the POST arguments. $post = $this->_request->getPost(); // Save the facets. foreach ($post['facets'] as $name => $data) { // Were "Is Indexed?" and "Is Facet?" checked? $indexed = array_key_exists('is_indexed', $data) ? 1 : 0; $faceted = array_key_exists('is_facet', $data) ? 1 : 0; // Load the facet mapping. $facet = $fieldTable->findBySlug($name); // Apply the updated values. $facet->label = $data['label']; $facet->is_indexed = $indexed; $facet->is_facet = $faceted; $facet->save(); } // Flash success. $this->_helper->flashMessenger( __('Fields successfully updated! Be sure to reindex.'), 'success' ); } // Assign the facet groups. $this->view->groups = $fieldTable->groupByElementSet(); } /** * Display the "Results Configuration" form. */ public function resultsAction() { $form = new <API key>(); // If a valid form was submitted. if ($this->_request->isPost() && $form->isValid($_POST)) { // Set the options. foreach ($form->getValues() as $option => $value) { set_option($option, $value); } // Flash success. $this->_helper->flashMessenger( __('Highlighting options successfully saved!'), 'success' ); } $this->view->form = $form; } /** * Display the "Index Items" form. */ public function reindexAction() { $form = new <API key>(); if ($this->_request->isPost()) { try { // Clear and reindex. Zend_Registry::get('job_dispatcher')->sendLongRunning( '<API key>' ); } catch (Exception $err) { } } $totalDocumentCount = $this->_helper->db->getTable('<API key>')->count(); $this->view->form = $form; $this->view->totalDocumentCount = $totalDocumentCount; } }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="fr"> <head> <!-- Generated by javadoc (version 1.7.0_21) on Fri Feb 07 15:34:51 CET 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Interface fr.ece.ostis.<API key></title> <meta name="date" content="2014-02-07"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface fr.ece.ostis.<API key>"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../fr/ece/ostis/<API key>.html" title="interface in fr.ece.ostis">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?fr/ece/ostis/class-use/<API key>.html" target="_top">Frames</a></li> <li><a href="<API key>.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h2 title="Uses of Interface fr.ece.ostis.<API key>" class="title">Uses of Interface<br>fr.ece.ostis.<API key></h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../fr/ece/ostis/<API key>.html" title="interface in fr.ece.ostis"><API key></a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#fr.ece.ostis">fr.ece.ostis</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#fr.ece.ostis.ui">fr.ece.ostis.ui</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="fr.ece.ostis"> </a> <h3>Uses of <a href="../../../../fr/ece/ostis/<API key>.html" title="interface in fr.ece.ostis"><API key></a> in <a href="../../../../fr/ece/ostis/package-summary.html">fr.ece.ostis</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../fr/ece/ostis/package-summary.html">fr.ece.ostis</a> with type parameters of type <a href="../../../../fr/ece/ostis/<API key>.html" title="interface in fr.ece.ostis"><API key></a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>protected <a href="file:/C:/Program Files Indie/Android/SDK/docs/reference/java/util/ArrayList.html?is-external=true" title="class or interface in java.util">ArrayList</a>&lt;<a href="../../../../fr/ece/ostis/<API key>.html" title="interface in fr.ece.ostis"><API key></a>&gt;</code></td> <td class="colLast"><span class="strong">OstisService.</span><code><strong><a href="../../../../fr/ece/ostis/OstisService.html#<API key>"><API key></a></strong></code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../fr/ece/ostis/package-summary.html">fr.ece.ostis</a> with parameters of type <a href="../../../../fr/ece/ostis/<API key>.html" title="interface in fr.ece.ostis"><API key></a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="strong">OstisService.</span><code><strong><a href="../../../../fr/ece/ostis/OstisService.html#<API key>(fr.ece.ostis.<API key>)"><API key></a></strong>(<a href="../../../../fr/ece/ostis/<API key>.html" title="interface in fr.ece.ostis"><API key></a>&nbsp;listener)</code> <div class="block">Registers a <API key> listener.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="strong">OstisService.</span><code><strong><a href="../../../../fr/ece/ostis/OstisService.html#<API key>(fr.ece.ostis.<API key>)"><API key></a></strong>(<a href="../../../../fr/ece/ostis/<API key>.html" title="interface in fr.ece.ostis"><API key></a>&nbsp;listener)</code> <div class="block">Unregisters a <API key> listener.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="fr.ece.ostis.ui"> </a> <h3>Uses of <a href="../../../../fr/ece/ostis/<API key>.html" title="interface in fr.ece.ostis"><API key></a> in <a href="../../../../fr/ece/ostis/ui/package-summary.html">fr.ece.ostis.ui</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../fr/ece/ostis/ui/package-summary.html">fr.ece.ostis.ui</a> that implement <a href="../../../../fr/ece/ostis/<API key>.html" title="interface in fr.ece.ostis"><API key></a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../fr/ece/ostis/ui/FlyActivity.html" title="class in fr.ece.ostis.ui">FlyActivity</a></strong></code> <div class="block">TODO</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../fr/ece/ostis/ui/<API key>.html" title="class in fr.ece.ostis.ui"><API key></a></strong></code> <div class="block">TODO</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../fr/ece/ostis/<API key>.html" title="interface in fr.ece.ostis">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?fr/ece/ostis/class-use/<API key>.html" target="_top">Frames</a></li> <li><a href="<API key>.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> </body> </html>
import re import traceback from urllib.parse import quote from requests.utils import dict_from_cookiejar from sickchill import logger from sickchill.helper.common import convert_size, try_int from sickchill.oldbeard import tvcache from sickchill.oldbeard.bs4_parser import BS4Parser from sickchill.providers.torrent.TorrentProvider import TorrentProvider class Provider(TorrentProvider): def __init__(self): super().__init__("Pretome") self.username = None self.password = None self.pin = None self.minseed = 0 self.minleech = 0 self.urls = { "base_url": "https://pretome.info", "login": "https://pretome.info/takelogin.php", "detail": "https://pretome.info/details.php?id=%s", "search": "https://pretome.info/browse.php?search=%s%s", "download": "https://pretome.info/download.php/%s/%s.torrent", } self.url = self.urls["base_url"] self.categories = "&st=1&cat%5B%5D=7" self.proper_strings = ["PROPER", "REPACK"] self.cache = tvcache.TVCache(self) def _check_auth(self): if not self.username or not self.password or not self.pin: logger.warning("Invalid username or password or pin. Check your settings") return True def login(self): if any(dict_from_cookiejar(self.session.cookies).values()): return True login_params = {"username": self.username, "password": self.password, "login_pin": self.pin} response = self.get_url(self.urls["login"], post_data=login_params, returns="text") if not response: logger.warning("Unable to connect to provider") return False if re.search("Username or password incorrect", response): logger.warning("Invalid username or password. Check your settings") return False return True def search(self, search_params, age=0, ep_obj=None): results = [] if not self.login(): return results for mode in search_params: items = [] logger.debug(_("Search Mode: {mode}".format(mode=mode))) for search_string in search_params[mode]: if mode != "RSS": logger.debug(_("Search String: {search_string}".format(search_string=search_string))) search_url = self.urls["search"] % (quote(search_string), self.categories) data = self.get_url(search_url, returns="text") if not data: continue try: with BS4Parser(data, "html5lib") as html: # Continue only if one Release is found empty = html.find("h2", text="No .torrents fit this filter criteria") if empty: logger.debug("Data returned from provider does not contain any torrents") continue torrent_table = html.find("table", style="border: none; width: 100%;") if not torrent_table: logger.exception("Could not find table of torrents") continue torrent_rows = torrent_table("tr", class_="browse") for result in torrent_rows: cells = result("td") size = None link = cells[1].find("a", style="font-size: 1.25em; font-weight: bold;") torrent_id = link["href"].replace("details.php?id=", "") try: if link.get("title", ""): title = link["title"] else: title = link.contents[0] download_url = self.urls["download"] % (torrent_id, link.contents[0]) seeders = int(cells[9].contents[0]) leechers = int(cells[10].contents[0]) # Need size for failed downloads handling if size is None: torrent_size = cells[7].text size = convert_size(torrent_size) or -1 except (AttributeError, TypeError): continue if not all([title, download_url]): continue # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: if mode != "RSS": logger.debug( "Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format( title, seeders, leechers ) ) continue item = {"title": title, "link": download_url, "size": size, "seeders": seeders, "leechers": leechers, "hash": ""} if mode != "RSS": logger.debug("Found result: {0} with {1} seeders and {2} leechers".format(title, seeders, leechers)) items.append(item) except Exception: logger.exception("Failed parsing provider. Traceback: {0}".format(traceback.format_exc())) # For each search mode sort all the items by seeders if available items.sort(key=lambda d: try_int(d.get("seeders", 0)), reverse=True) results += items return results
/* General Demo Style */ @import url(https://fonts.googleapis.com/css?family=Lato:300,400,700); *, *:after, *:before { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; padding: 0; margin: 0; } .clearfix:before, .clearfix:after { content: " "; display: table; } .clearfix:after { clear: both; } .clearfix { *zoom: 1; } a { color: #555; text-decoration: none; } .container { width: 100%; position: relative; } .main, .container > header { width: 90%; max-width: 960px; margin: 0 auto; position: relative; padding: 0 10px; } .container > header { padding: 40px 10px 50px; border-bottom: 1px solid #ddd; box-shadow: 0 1px rgba(255,255,255,0.8); margin-bottom: 30px; } .container > header h1 { font-size: 34px; line-height: 38px; margin: 0; font-weight: 700; color: #333; float: left; } .container > header h1 span { display: block; font-size: 20px; font-weight: 300; } .fleft { float: left; width: 49%; min-width: 300px; } .main p { color: #AAA; padding: 20px 30px 0px 0px; font-size: 20px; line-height: 34px; font-weight: 300; text-shadow: 0 1px 1px rgba(255, 255, 255, 0.8); } /* Header Style */ .codrops-top { line-height: 24px; font-size: 11px; background: #fff; background: rgba(255, 255, 255, 0.5); text-transform: uppercase; z-index: 9999; position: relative; box-shadow: 1px 0px 2px rgba(0,0,0,0.2); } .codrops-top a { padding: 0px 10px; letter-spacing: 1px; color: #333; display: inline-block; } .codrops-top a:hover { background: rgba(255,255,255,0.8); color: #000; } .codrops-top span.right { float: right; } .codrops-top span.right a { float: left; display: block; } /* Demo Buttons Style */ .codrops-demos { float: right; padding-top: 10px; } .codrops-demos a { display: inline-block; margin: 10px; color: #666; font-weight: 700; line-height: 30px; border-bottom: 4px solid transparent; } .codrops-demos a:hover { color: #000; border-color: #000; } .codrops-demos a.current-demo, .codrops-demos a.current-demo:hover { color: #aaa; border-color: #aaa; } @media screen and (max-width: 730px){ .fleft { width: 100%; float: none; text-align: center; } }
package uk.ac.rdg.resc.edal.coverage.domain; import java.util.List; import org.opengis.referencing.crs.<API key>; /** * A geospatial/temporal domain: defines the set of points for which a {@link DiscreteCoverage} * is defined. The domain is comprised of a set of unique domain objects in a * defined order. The domain therefore has the semantics of both a {@link Set} * and a {@link List} of domain objects. * @param <DO> The type of the domain object * @author Jon */ public interface Domain<DO> { /** * Gets the coordinate reference system to which objects in this domain are * referenced. Returns null if the domain objects cannot be referenced * to an external coordinate reference system. * @return the coordinate reference system to which objects in this domain are * referenced, or null if the domain objects are not externally referenced. */ public <API key> <API key>(); /** * Returns the {@link List} of domain objects that comprise this domain. * @todo There may be issues for large grids if the number of domain objects * is greater than Integer.MAX_VALUE, as the size of this list will be recorded * incorrectly. This will only happen for very large domains (e.g. large grids). */ public List<DO> getDomainObjects(); /** * <p>Returns the number of domain objects in the domain.</p> * <p>This is a long integer because grids can grow very large, beyond the * range of a 4-byte integer.</p> */ public long size(); }
package org.cgiar.ccafs.marlo.data.manager.impl; import org.cgiar.ccafs.marlo.data.dao.<API key>; import org.cgiar.ccafs.marlo.data.manager.<API key>; import org.cgiar.ccafs.marlo.data.model.<API key>; import java.util.List; import javax.inject.Inject; import javax.inject.Named; /** * @author CCAFS */ @Named public class <API key> implements <API key> { private <API key> <API key>; // Managers @Inject public <API key>(<API key> <API key>) { this.<API key> = <API key>; } @Override public void <API key>(long <API key>) { <API key>.<API key>(<API key>); } @Override public boolean <API key>(long <API key>) { return <API key>.<API key>(<API key>); } @Override public List<<API key>> findAll() { return <API key>.findAll(); } @Override public <API key> <API key>(long <API key>) { return <API key>.find(<API key>); } @Override public <API key> <API key>(<API key> <API key>) { return <API key>.save(<API key>); } }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_51) on Mon Mar 17 10:31:37 CDT 2014 --> <title><API key> (Trove 3.1a1)</title> <meta name="date" content="2014-03-17"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="<API key> (Trove 3.1a1)"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><a href="http://trove4j.sourceforge.net/">GNU Trove</a></em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../gnu/trove/decorator/<API key>.html" title="class in gnu.trove.decorator"><span class="strong">Prev Class</span></a></li> <li><a href="../../../gnu/trove/decorator/TIntIntMapDecorator.html" title="class in gnu.trove.decorator"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?gnu/trove/decorator/<API key>.html" target="_top">Frames</a></li> <li><a href="<API key>.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#<API key>.util.AbstractMap">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <div class="subTitle">gnu.trove.decorator</div> <h2 title="Class <API key>" class="title">Class <API key></h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</li> <li> <ul class="inheritance"> <li>gnu.trove.decorator.<API key></li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.io.Externalizable, java.io.Serializable, java.lang.Cloneable, java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</dd> </dl> <hr> <br> <pre>public class <span class="strong"><API key></span> extends java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt; implements java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;, java.io.Externalizable, java.lang.Cloneable</pre> <div class="block">Wrapper class to make a TIntFloatMap conform to the <tt>java.util.Map</tt> API. This class simply decorates an underlying TIntFloatMap and translates the Object-based APIs into their Trove primitive analogs. <p/> Note that wrapping and unwrapping primitive values is extremely inefficient. If possible, users of this class should override the appropriate methods in this class and use a table of canonical values. <p/> Created: Mon Sep 23 22:07:40 PDT 2002</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../serialized-form.html#gnu.trove.decorator.<API key>">Serialized Form</a></dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="<API key>"> </a> <h3>Nested Class Summary</h3> <ul class="blockList"> <li class="blockList"><a name="<API key>.util.AbstractMap"> </a> <h3>Nested classes/interfaces inherited from class&nbsp;java.util.AbstractMap</h3> <code>java.util.AbstractMap.SimpleEntry&lt;K,V&gt;, java.util.AbstractMap.<API key>&lt;K,V&gt;</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="<API key>.util.Map"> </a> <h3>Nested classes/interfaces inherited from interface&nbsp;java.util.Map</h3> <code>java.util.Map.Entry&lt;K,V&gt;</code></li> </ul> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="field_summary"> </a> <h3>Field Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../gnu/trove/map/TIntFloatMap.html" title="interface in gnu.trove.map">TIntFloatMap</a></code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/<API key>.html#_map">_map</a></strong></code> <div class="block">the wrapped primitive map</div> </td> </tr> </table> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../gnu/trove/decorator/<API key>.html#<API key>()"><API key></a></strong>()</code> <div class="block">FOR EXTERNALIZATION ONLY!!</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../gnu/trove/decorator/<API key>.html#<API key>(gnu.trove.map.TIntFloatMap)"><API key></a></strong>(<a href="../../../gnu/trove/map/TIntFloatMap.html" title="interface in gnu.trove.map">TIntFloatMap</a>&nbsp;map)</code> <div class="block">Creates a wrapper that decorates the specified primitive map.</div> </td> </tr> </table> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="method_summary"> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/<API key>.html#clear()">clear</a></strong>()</code> <div class="block">Empties the map.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/<API key>.html#containsKey(java.lang.Object)">containsKey</a></strong>(java.lang.Object&nbsp;key)</code> <div class="block">Checks for the present of <tt>key</tt> in the keys of the map.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/<API key>.html#containsValue(java.lang.Object)">containsValue</a></strong>(java.lang.Object&nbsp;val)</code> <div class="block">Checks for the presence of <tt>val</tt> in the values of the map.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.util.Set&lt;java.util.Map.Entry&lt;java.lang.Integer,java.lang.Float&gt;&gt;</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/<API key>.html#entrySet()">entrySet</a></strong>()</code> <div class="block">Returns a Set view on the entries of the map.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.Float</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/<API key>.html#get(java.lang.Object)">get</a></strong>(java.lang.Object&nbsp;key)</code> <div class="block">Retrieves the value for <tt>key</tt></div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../gnu/trove/map/TIntFloatMap.html" title="interface in gnu.trove.map">TIntFloatMap</a></code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/<API key>.html#getMap()">getMap</a></strong>()</code> <div class="block">Returns a reference to the map wrapped by this decorator.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/<API key>.html#isEmpty()">isEmpty</a></strong>()</code> <div class="block">Indicates whether map has any entries.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.Float</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/<API key>.html#put(java.lang.Integer, java.lang.Float)">put</a></strong>(java.lang.Integer&nbsp;key, java.lang.Float&nbsp;value)</code> <div class="block">Inserts a key/value pair into the map.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/<API key>.html#putAll(java.util.Map)">putAll</a></strong>(java.util.Map&lt;? extends java.lang.Integer,? extends java.lang.Float&gt;&nbsp;map)</code> <div class="block">Copies the key/value mappings in <tt>map</tt> into this map.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/<API key>.html#readExternal(java.io.ObjectInput)">readExternal</a></strong>(java.io.ObjectInput&nbsp;in)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.Float</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/<API key>.html#remove(java.lang.Object)">remove</a></strong>(java.lang.Object&nbsp;key)</code> <div class="block">Deletes a key/value pair from the map.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/<API key>.html#size()">size</a></strong>()</code> <div class="block">Returns the number of entries in the map.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected int</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/<API key>.html#unwrapKey(java.lang.Object)">unwrapKey</a></strong>(java.lang.Object&nbsp;key)</code> <div class="block">Unwraps a key</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected float</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/<API key>.html#unwrapValue(java.lang.Object)">unwrapValue</a></strong>(java.lang.Object&nbsp;value)</code> <div class="block">Unwraps a value</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected java.lang.Integer</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/<API key>.html#wrapKey(int)">wrapKey</a></strong>(int&nbsp;k)</code> <div class="block">Wraps a key</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected java.lang.Float</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/<API key>.html#wrapValue(float)">wrapValue</a></strong>(float&nbsp;k)</code> <div class="block">Wraps a value</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/<API key>.html#writeExternal(java.io.ObjectOutput)">writeExternal</a></strong>(java.io.ObjectOutput&nbsp;out)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="<API key>.util.AbstractMap"> </a> <h3>Methods inherited from class&nbsp;java.util.AbstractMap</h3> <code>clone, equals, hashCode, keySet, toString, values</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="<API key>.lang.Object"> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>finalize, getClass, notify, notifyAll, wait, wait, wait</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="<API key>.util.Map"> </a> <h3>Methods inherited from interface&nbsp;java.util.Map</h3> <code>equals, hashCode, keySet, values</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="field_detail"> </a> <h3>Field Detail</h3> <a name="_map"> </a> <ul class="blockListLast"> <li class="blockList"> <h4>_map</h4> <pre>protected&nbsp;<a href="../../../gnu/trove/map/TIntFloatMap.html" title="interface in gnu.trove.map">TIntFloatMap</a> _map</pre> <div class="block">the wrapped primitive map</div> </li> </ul> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> </a> <h3>Constructor Detail</h3> <a name="<API key>()"> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>public&nbsp;<API key>()</pre> <div class="block">FOR EXTERNALIZATION ONLY!!</div> </li> </ul> <a name="<API key>(gnu.trove.map.TIntFloatMap)"> </a> <ul class="blockListLast"> <li class="blockList"> <h4><API key></h4> <pre>public&nbsp;<API key>(<a href="../../../gnu/trove/map/TIntFloatMap.html" title="interface in gnu.trove.map">TIntFloatMap</a>&nbsp;map)</pre> <div class="block">Creates a wrapper that decorates the specified primitive map.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>map</code> - the <tt>TIntFloatMap</tt> to wrap.</dd></dl> </li> </ul> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="method_detail"> </a> <h3>Method Detail</h3> <a name="getMap()"> </a> <ul class="blockList"> <li class="blockList"> <h4>getMap</h4> <pre>public&nbsp;<a href="../../../gnu/trove/map/TIntFloatMap.html" title="interface in gnu.trove.map">TIntFloatMap</a>&nbsp;getMap()</pre> <div class="block">Returns a reference to the map wrapped by this decorator.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>the wrapped <tt>TIntFloatMap</tt> instance.</dd></dl> </li> </ul> <a name="put(java.lang.Integer, java.lang.Float)"> </a> <ul class="blockList"> <li class="blockList"> <h4>put</h4> <pre>public&nbsp;java.lang.Float&nbsp;put(java.lang.Integer&nbsp;key, java.lang.Float&nbsp;value)</pre> <div class="block">Inserts a key/value pair into the map.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>put</code>&nbsp;in interface&nbsp;<code>java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><strong>Overrides:</strong></dt> <dd><code>put</code>&nbsp;in class&nbsp;<code>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>key</code> - an <code>Object</code> value</dd><dd><code>value</code> - an <code>Object</code> value</dd> <dt><span class="strong">Returns:</span></dt><dd>the previous value associated with <tt>key</tt>, or Float(0) if none was found.</dd></dl> </li> </ul> <a name="get(java.lang.Object)"> </a> <ul class="blockList"> <li class="blockList"> <h4>get</h4> <pre>public&nbsp;java.lang.Float&nbsp;get(java.lang.Object&nbsp;key)</pre> <div class="block">Retrieves the value for <tt>key</tt></div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>get</code>&nbsp;in interface&nbsp;<code>java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><strong>Overrides:</strong></dt> <dd><code>get</code>&nbsp;in class&nbsp;<code>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>key</code> - an <code>Object</code> value</dd> <dt><span class="strong">Returns:</span></dt><dd>the value of <tt>key</tt> or null if no such mapping exists.</dd></dl> </li> </ul> <a name="clear()"> </a> <ul class="blockList"> <li class="blockList"> <h4>clear</h4> <pre>public&nbsp;void&nbsp;clear()</pre> <div class="block">Empties the map.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>clear</code>&nbsp;in interface&nbsp;<code>java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><strong>Overrides:</strong></dt> <dd><code>clear</code>&nbsp;in class&nbsp;<code>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> </dl> </li> </ul> <a name="remove(java.lang.Object)"> </a> <ul class="blockList"> <li class="blockList"> <h4>remove</h4> <pre>public&nbsp;java.lang.Float&nbsp;remove(java.lang.Object&nbsp;key)</pre> <div class="block">Deletes a key/value pair from the map.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>remove</code>&nbsp;in interface&nbsp;<code>java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><strong>Overrides:</strong></dt> <dd><code>remove</code>&nbsp;in class&nbsp;<code>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>key</code> - an <code>Object</code> value</dd> <dt><span class="strong">Returns:</span></dt><dd>the removed value, or null if it was not found in the map</dd></dl> </li> </ul> <a name="entrySet()"> </a> <ul class="blockList"> <li class="blockList"> <h4>entrySet</h4> <pre>public&nbsp;java.util.Set&lt;java.util.Map.Entry&lt;java.lang.Integer,java.lang.Float&gt;&gt;&nbsp;entrySet()</pre> <div class="block">Returns a Set view on the entries of the map.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>entrySet</code>&nbsp;in interface&nbsp;<code>java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><strong>Specified by:</strong></dt> <dd><code>entrySet</code>&nbsp;in class&nbsp;<code>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><span class="strong">Returns:</span></dt><dd>a <code>Set</code> value</dd></dl> </li> </ul> <a name="containsValue(java.lang.Object)"> </a> <ul class="blockList"> <li class="blockList"> <h4>containsValue</h4> <pre>public&nbsp;boolean&nbsp;containsValue(java.lang.Object&nbsp;val)</pre> <div class="block">Checks for the presence of <tt>val</tt> in the values of the map.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>containsValue</code>&nbsp;in interface&nbsp;<code>java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><strong>Overrides:</strong></dt> <dd><code>containsValue</code>&nbsp;in class&nbsp;<code>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>val</code> - an <code>Object</code> value</dd> <dt><span class="strong">Returns:</span></dt><dd>a <code>boolean</code> value</dd></dl> </li> </ul> <a name="containsKey(java.lang.Object)"> </a> <ul class="blockList"> <li class="blockList"> <h4>containsKey</h4> <pre>public&nbsp;boolean&nbsp;containsKey(java.lang.Object&nbsp;key)</pre> <div class="block">Checks for the present of <tt>key</tt> in the keys of the map.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>containsKey</code>&nbsp;in interface&nbsp;<code>java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><strong>Overrides:</strong></dt> <dd><code>containsKey</code>&nbsp;in class&nbsp;<code>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>key</code> - an <code>Object</code> value</dd> <dt><span class="strong">Returns:</span></dt><dd>a <code>boolean</code> value</dd></dl> </li> </ul> <a name="size()"> </a> <ul class="blockList"> <li class="blockList"> <h4>size</h4> <pre>public&nbsp;int&nbsp;size()</pre> <div class="block">Returns the number of entries in the map.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>size</code>&nbsp;in interface&nbsp;<code>java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><strong>Overrides:</strong></dt> <dd><code>size</code>&nbsp;in class&nbsp;<code>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><span class="strong">Returns:</span></dt><dd>the map's size.</dd></dl> </li> </ul> <a name="isEmpty()"> </a> <ul class="blockList"> <li class="blockList"> <h4>isEmpty</h4> <pre>public&nbsp;boolean&nbsp;isEmpty()</pre> <div class="block">Indicates whether map has any entries.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>isEmpty</code>&nbsp;in interface&nbsp;<code>java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><strong>Overrides:</strong></dt> <dd><code>isEmpty</code>&nbsp;in class&nbsp;<code>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><span class="strong">Returns:</span></dt><dd>true if the map is empty</dd></dl> </li> </ul> <a name="putAll(java.util.Map)"> </a> <ul class="blockList"> <li class="blockList"> <h4>putAll</h4> <pre>public&nbsp;void&nbsp;putAll(java.util.Map&lt;? extends java.lang.Integer,? extends java.lang.Float&gt;&nbsp;map)</pre> <div class="block">Copies the key/value mappings in <tt>map</tt> into this map. Note that this will be a <b>deep</b> copy, as storage is by primitive value.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>putAll</code>&nbsp;in interface&nbsp;<code>java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><strong>Overrides:</strong></dt> <dd><code>putAll</code>&nbsp;in class&nbsp;<code>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>map</code> - a <code>Map</code> value</dd></dl> </li> </ul> <a name="wrapKey(int)"> </a> <ul class="blockList"> <li class="blockList"> <h4>wrapKey</h4> <pre>protected&nbsp;java.lang.Integer&nbsp;wrapKey(int&nbsp;k)</pre> <div class="block">Wraps a key</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>k</code> - key in the underlying map</dd> <dt><span class="strong">Returns:</span></dt><dd>an Object representation of the key</dd></dl> </li> </ul> <a name="unwrapKey(java.lang.Object)"> </a> <ul class="blockList"> <li class="blockList"> <h4>unwrapKey</h4> <pre>protected&nbsp;int&nbsp;unwrapKey(java.lang.Object&nbsp;key)</pre> <div class="block">Unwraps a key</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>key</code> - wrapped key</dd> <dt><span class="strong">Returns:</span></dt><dd>an unwrapped representation of the key</dd></dl> </li> </ul> <a name="wrapValue(float)"> </a> <ul class="blockList"> <li class="blockList"> <h4>wrapValue</h4> <pre>protected&nbsp;java.lang.Float&nbsp;wrapValue(float&nbsp;k)</pre> <div class="block">Wraps a value</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>k</code> - value in the underlying map</dd> <dt><span class="strong">Returns:</span></dt><dd>an Object representation of the value</dd></dl> </li> </ul> <a name="unwrapValue(java.lang.Object)"> </a> <ul class="blockList"> <li class="blockList"> <h4>unwrapValue</h4> <pre>protected&nbsp;float&nbsp;unwrapValue(java.lang.Object&nbsp;value)</pre> <div class="block">Unwraps a value</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>value</code> - wrapped value</dd> <dt><span class="strong">Returns:</span></dt><dd>an unwrapped representation of the value</dd></dl> </li> </ul> <a name="readExternal(java.io.ObjectInput)"> </a> <ul class="blockList"> <li class="blockList"> <h4>readExternal</h4> <pre>public&nbsp;void&nbsp;readExternal(java.io.ObjectInput&nbsp;in) throws java.io.IOException, java.lang.<API key></pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>readExternal</code>&nbsp;in interface&nbsp;<code>java.io.Externalizable</code></dd> <dt><span class="strong">Throws:</span></dt> <dd><code>java.io.IOException</code></dd> <dd><code>java.lang.<API key></code></dd></dl> </li> </ul> <a name="writeExternal(java.io.ObjectOutput)"> </a> <ul class="blockListLast"> <li class="blockList"> <h4>writeExternal</h4> <pre>public&nbsp;void&nbsp;writeExternal(java.io.ObjectOutput&nbsp;out) throws java.io.IOException</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>writeExternal</code>&nbsp;in interface&nbsp;<code>java.io.Externalizable</code></dd> <dt><span class="strong">Throws:</span></dt> <dd><code>java.io.IOException</code></dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><a href="http://trove4j.sourceforge.net/">GNU Trove</a></em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../gnu/trove/decorator/<API key>.html" title="class in gnu.trove.decorator"><span class="strong">Prev Class</span></a></li> <li><a href="../../../gnu/trove/decorator/TIntIntMapDecorator.html" title="class in gnu.trove.decorator"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?gnu/trove/decorator/<API key>.html" target="_top">Frames</a></li> <li><a href="<API key>.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#<API key>.util.AbstractMap">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> </a></div> </body> </html>
/*jshint expr:true */ describe("Services: Core System Messages", function() { beforeEach(module("risevision.core.systemmessages")); beforeEach(module(function ($provide) { //stub services $provide.service("$q", function() {return Q;}); $provide.value("userState", { isRiseVisionUser: function () {return true; } }); })); it("should exist", function() { inject(function(<API key>) { expect(<API key>).be.defined; }); }); });
{% load i18n %} <table class="tabledisplay"> <tbody><tr><th>{% trans 'Vraag' %}</th><th>{% trans 'Antwoord' %}</th></tr> <tr><td colspan="2"><h5><i>Algemeen</i></h5></td></tr> <tr><td>{% trans 'Beoordeling algemene gezondheid' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Beoordeling algemene gezondheid in vergelijking met vorig jaar' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td colspan="2"><h5><i>Inspanningen</i></h5></td></tr> <tr><td>{% trans 'Forse inspanning zoals hardlopen, zware voorwerpen tillen, inspannend sporten' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Matige inspanning zoals het verplaatsen van een tafel, stofzuigen, fietsen' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Tillen of boodschappen doen' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Een paar trappen lopen' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Een trap lopen' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Buigen, knielen of bukken' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Meer dan een kilometer lopen' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Een halve kilometer lopen' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Honderd meter lopen' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Wassen of aankleden' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td colspan="2"><h5><i>Fysieke problemen</i></h5></td></tr> <tr><td>{% trans 'Minder tijd kunnen besteden aan werk of andere bezigheden' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Minder bereikt dan u zou willen' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Beperkt in het soort werk of het soort bezigheden' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Moeite met het werk of andere bezigheden' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td colspan="2"><h5><i>Emotionele problemen</i></h5></td></tr> <tr><td>{% trans 'Minder tijd kunnen besteden aan werk of andere bezigheden' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Minder bereikt dan u zou willen' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Het werk of andere bezigheden niet zo zorgvuldig gedaan als u gewend bent' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td colspan="2"><h5><i>Sociale en pijn impact</i></h5></td></tr> <tr><td>{% trans 'Heeft u lichamelijke of hebben uw emotionele problemen u de afgelopen 4 weken belemmerd in uw normale sociale bezigheden met gezin, vrienden, buren of anderen' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Hoeveel pijn had u de afgelopen 4 weken' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Heeft pijn u in de afgelopen 4 weken belemmerd bij uw normale werkzaamheden' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td colspan="2"><h5><i>Gevoel</i></h5></td></tr> <tr><td>{% trans 'Voelde u zich levenslustig' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Voelde u zich zenuwachtig' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Zat u zo in de put dat niets u kon opvrolijken' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Voelde u zich kalm en rustig' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Voelde u zich energiek' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Voelde u zich neerslachtig en somber' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Voelde u zich uitgeblust' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Voelde u zich gelukkig' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Voelde u zich moe' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td colspan="2"><h5><i>Sociaal</i></h5></td></tr> <tr><td>{% trans 'Hoe vaak uw lichamelijke gezondheid of uw emotionele problemen gedurende de afgelopen 4 weken uw sociale activiteiten (bijv. bezoek vrienden, familie) belemmerd' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td colspan="2"><h5><i>Relativatie</i></h5></td></tr> <tr><td>{% trans 'Ik lijk gemakkelijker ziek te worden dan andere mensen' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Ik ben net zo gezond als andere mensen die ik ken' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Ik verwacht dat mijn gezondheid achteruit zal gaan' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> <tr><td>{% trans 'Mijn gezondheid is uitstekend' %}</td><td>{{ questionnaire.<API key>|default:"-" }}</td></tr> </tbody></table>
<reference path="grid_astar.ts" /> // create abstract grid representation (no nodes here) var grid = [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]; var tileSize = 20; var start = [5,4]; var goal1 = [19,11]; var goal2 = [10,13]; window.onload = function() { var canvas = document.getElementById("gridCanvas"); canvas.addEventListener("mousedown", function(event) { var x = event.pageX - canvas.offsetLeft; var y = event.pageY - canvas.offsetTop; var cellX = Math.floor(x / tileSize); var cellY = Math.floor(y / tileSize); toggleGridCell(cellX, cellY); testEuclidean(); }, false); testEuclidean(); }; function toggleGridCell(x, y) { if ((x === start[0] && y === start[1]) || (x === goal1[0] && y === goal1[1]) || (x === goal2[0] && y === goal2[1])) { return; } if (grid[y][x] === 0) { grid[y][x] = 1; } else { grid[y][x] = 0; } } function drawGrid(path, visited) { var canvas = <HTMLCanvasElement>document.getElementById("gridCanvas"); var context = canvas.getContext("2d"); var h = grid.length; var w = grid[0].length; for (var x = 0; x < w; x++) { for (var y = 0; y < h; y++) { if (grid[y][x] == 0) { context.fillStyle = "#999"; } else { context.fillStyle = "black"; } context.fillRect(x*tileSize, y*tileSize, tileSize-1, tileSize-1); } } for (var i = 0; i < visited.length; i++) { var current = visited[i]; context.fillStyle = "lightgreen"; context.fillRect(current.x*tileSize, current.y*tileSize, tileSize-1, tileSize-1) } for (var i = 0; i < path.length; i++) { var current = path[i]; context.fillStyle = "green"; context.fillRect(current.x*tileSize, current.y*tileSize, tileSize-1, tileSize-1) } context.fillStyle = "yellow"; context.fillRect(start[0]*tileSize, start[1]*tileSize, tileSize-1, tileSize-1); context.fillStyle = "red"; context.fillRect(goal1[0]*tileSize, goal1[1]*tileSize, tileSize-1, tileSize-1); context.fillRect(goal2[0]*tileSize, goal2[1]*tileSize, tileSize-1, tileSize-1); } function testHeuristic(heuristic) { var graphGoal = new grid_astar.MultipleGoals([goal1,goal2]); var graph = new astar.Graph(heuristic, graphGoal); var graphStart = new grid_astar.Node(grid,start[0],start[1]); var result = graph.searchPath(graphStart); drawGrid(result.path, result.visited); var resultString = document.getElementById("info"); if (result.found) { resultString.innerHTML = "Length of path found: " + result.path.length; } else { resultString.innerHTML = "No path found."; } } function testDijkstra(){ //test graph with no heuristics testHeuristic(new grid_astar.DijkstraHeuristic()); } function testEuclidean(){ //test graph with Euclidean distance testHeuristic(new grid_astar.EuclidianHeuristic()); } function testManhattan(){ //test graph with Manhattan distance testHeuristic(new grid_astar.ManhattanHeuristic()); }
// Use of this source code is governed by a BSD-style package gonum import ( "gonum.org/v1/gonum/blas" "gonum.org/v1/gonum/lapack" ) // of plane rotations is implicitly represented by a matrix P. P is multiplied // by a depending on the value of side -- A = P * A if side == lapack.Left, // A = A * P^T if side == lapack.Right. //The exact value of P depends on the value of pivot, but in all cases P is // rotation matrix k are defined by s[k] and c[k] // R(k) = [ c[k] s[k]] // [-s[k] s[k]] // If direct == lapack.Forward, the rotation matrices are applied as // P = P(z-1) * ... * P(2) * P(1), while if direct == lapack.Backward they are // applied as P = P(1) * P(2) * ... * P(n). // pivot defines the mapping of the elements in R(k) to P(k). // If pivot == lapack.Variable, the rotation is performed for the (k, k+1) plane. // P(k) = [1 ] // [ c[k] s[k] ] // [ -s[k] c[k] ] // if pivot == lapack.Top, the rotation is performed for the (1, k+1) plane, // P(k) = [c[k] s[k] ] // [-s[k] c[k] ] // and if pivot == lapack.Bottom, the rotation is performed for the (k, z) plane. // P(k) = [1 ] // [ c[k] s[k]] // [ -s[k] c[k]] // s and c have length m - 1 if side == blas.Left, and n - 1 if side == blas.Right. // Dlasr is an internal routine. It is exported for testing purposes. func (impl Implementation) Dlasr(side blas.Side, pivot lapack.Pivot, direct lapack.Direct, m, n int, c, s, a []float64, lda int) { checkMatrix(m, n, a, lda) if side != blas.Left && side != blas.Right { panic(badSide) } if pivot != lapack.Variable && pivot != lapack.Top && pivot != lapack.Bottom { panic(badPivot) } if direct != lapack.Forward && direct != lapack.Backward { panic(badDirect) } if side == blas.Left { if len(c) < m-1 { panic(badSlice) } if len(s) < m-1 { panic(badSlice) } } else { if len(c) < n-1 { panic(badSlice) } if len(s) < n-1 { panic(badSlice) } } if m == 0 || n == 0 { return } if side == blas.Left { if pivot == lapack.Variable { if direct == lapack.Forward { for j := 0; j < m-1; j++ { ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < n; i++ { tmp2 := a[j*lda+i] tmp := a[(j+1)*lda+i] a[(j+1)*lda+i] = ctmp*tmp - stmp*tmp2 a[j*lda+i] = stmp*tmp + ctmp*tmp2 } } } return } for j := m - 2; j >= 0; j ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < n; i++ { tmp2 := a[j*lda+i] tmp := a[(j+1)*lda+i] a[(j+1)*lda+i] = ctmp*tmp - stmp*tmp2 a[j*lda+i] = stmp*tmp + ctmp*tmp2 } } } return } else if pivot == lapack.Top { if direct == lapack.Forward { for j := 1; j < m; j++ { ctmp := c[j-1] stmp := s[j-1] if ctmp != 1 || stmp != 0 { for i := 0; i < n; i++ { tmp := a[j*lda+i] tmp2 := a[i] a[j*lda+i] = ctmp*tmp - stmp*tmp2 a[i] = stmp*tmp + ctmp*tmp2 } } } return } for j := m - 1; j >= 1; j ctmp := c[j-1] stmp := s[j-1] if ctmp != 1 || stmp != 0 { for i := 0; i < n; i++ { ctmp := c[j-1] stmp := s[j-1] if ctmp != 1 || stmp != 0 { for i := 0; i < n; i++ { tmp := a[j*lda+i] tmp2 := a[i] a[j*lda+i] = ctmp*tmp - stmp*tmp2 a[i] = stmp*tmp + ctmp*tmp2 } } } } } return } if direct == lapack.Forward { for j := 0; j < m-1; j++ { ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < n; i++ { tmp := a[j*lda+i] tmp2 := a[(m-1)*lda+i] a[j*lda+i] = stmp*tmp2 + ctmp*tmp a[(m-1)*lda+i] = ctmp*tmp2 - stmp*tmp } } } return } for j := m - 2; j >= 0; j ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < n; i++ { tmp := a[j*lda+i] tmp2 := a[(m-1)*lda+i] a[j*lda+i] = stmp*tmp2 + ctmp*tmp a[(m-1)*lda+i] = ctmp*tmp2 - stmp*tmp } } } return } if pivot == lapack.Variable { if direct == lapack.Forward { for j := 0; j < n-1; j++ { ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < m; i++ { tmp := a[i*lda+j+1] tmp2 := a[i*lda+j] a[i*lda+j+1] = ctmp*tmp - stmp*tmp2 a[i*lda+j] = stmp*tmp + ctmp*tmp2 } } } return } for j := n - 2; j >= 0; j ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < m; i++ { tmp := a[i*lda+j+1] tmp2 := a[i*lda+j] a[i*lda+j+1] = ctmp*tmp - stmp*tmp2 a[i*lda+j] = stmp*tmp + ctmp*tmp2 } } } return } else if pivot == lapack.Top { if direct == lapack.Forward { for j := 1; j < n; j++ { ctmp := c[j-1] stmp := s[j-1] if ctmp != 1 || stmp != 0 { for i := 0; i < m; i++ { tmp := a[i*lda+j] tmp2 := a[i*lda] a[i*lda+j] = ctmp*tmp - stmp*tmp2 a[i*lda] = stmp*tmp + ctmp*tmp2 } } } return } for j := n - 1; j >= 1; j ctmp := c[j-1] stmp := s[j-1] if ctmp != 1 || stmp != 0 { for i := 0; i < m; i++ { tmp := a[i*lda+j] tmp2 := a[i*lda] a[i*lda+j] = ctmp*tmp - stmp*tmp2 a[i*lda] = stmp*tmp + ctmp*tmp2 } } } return } if direct == lapack.Forward { for j := 0; j < n-1; j++ { ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < m; i++ { tmp := a[i*lda+j] tmp2 := a[i*lda+n-1] a[i*lda+j] = stmp*tmp2 + ctmp*tmp a[i*lda+n-1] = ctmp*tmp2 - stmp*tmp } } } return } for j := n - 2; j >= 0; j ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < m; i++ { tmp := a[i*lda+j] tmp2 := a[i*lda+n-1] a[i*lda+j] = stmp*tmp2 + ctmp*tmp a[i*lda+n-1] = ctmp*tmp2 - stmp*tmp } } } }
#include "../serials/sread.h" CML_Error CML_SerialsReadINT8(CML_Bytes * bytes, uint32_t * bpos, int8_t * result) { if (*bpos + sizeof(int8_t) > bytes->size) return <API key>; *result = bytes->data[*bpos]; *bpos += 1; /* Need to reverse signed char */ /* It's a perl thing */ *result ^= 1 << 7; return CML_ERROR_SUCCESS; } CML_Error <API key>(CML_Bytes * bytes, uint32_t * bpos, uint8_t * result) { if (*bpos + sizeof(uint8_t) > bytes->size) return <API key>; *result = bytes->data[*bpos]; *bpos += 1; return CML_ERROR_SUCCESS; } CML_Error <API key>(CML_Bytes * bytes, uint32_t * bpos, int32_t * result) { if (*bpos + sizeof(int32_t) > bytes->size) return <API key>; union { int32_t res; uint8_t bytes[sizeof(int32_t)]; } conv; uint32_t i; for (i = 0; i < sizeof(int32_t); i++, *bpos += 1) conv.bytes[3 - i] = bytes->data[*bpos]; *result = conv.res; return CML_ERROR_SUCCESS; } CML_Error <API key>(CML_Bytes * bytes, uint32_t * bpos, uint32_t * result) { if (*bpos + sizeof(uint32_t) > bytes->size) return <API key>; union { uint32_t res; uint8_t bytes[sizeof(uint32_t)]; } conv; uint32_t i; for (i = 0; i < sizeof(uint32_t); i++, *bpos += 1) conv.bytes[3 - i] = bytes->data[*bpos]; *result = conv.res; return CML_ERROR_SUCCESS; } CML_Error CML_SerialsReadDATA(CML_Bytes * bytes, uint32_t * bpos, uint8_t * result, uint32_t length) { if (*bpos + length > bytes->size) return <API key>; uint32_t i; for (i = 0; i < length; i++, *bpos += 1) result[i] = bytes->data[*bpos]; result[i] = '\0'; return CML_ERROR_SUCCESS; }
package com.entrepidea.jvm; import java.util.ArrayList; import java.util.List; public class <API key> { public static void main(String[] args){ List<String> l = new ArrayList<>(); int i=0; while(true){ l.add(String.valueOf(i++).intern()); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using LobbyClient; using PlasmaShared; using ZkData; namespace ZeroKWeb.SpringieInterface { public class StartSetup { static bool <API key> = false; // may cause bugs <summary> Sets up all the things that Springie needs to know for the battle: how to balance, who to get extra commanders, what PlanetWars structures to create, etc. </summary> public static <API key> <API key>(BattleContext context) { try { AutohostMode mode = context.GetMode(); var ret = new <API key>(); if (mode == AutohostMode.Planetwars) { ret.BalanceTeamsResult = Balancer.BalanceTeams(context, true,null, null); context.Players = ret.BalanceTeamsResult.Players; } var commanderTypes = new LuaTable(); var db = new ZkDataContext(); // calculate to whom to send extra comms var <API key> = new List<int>(); if (mode == AutohostMode.Planetwars || mode == AutohostMode.Generic || mode == AutohostMode.GameFFA || mode == AutohostMode.Teams) { IOrderedEnumerable<IGrouping<int, PlayerTeam>> groupedByTeam = context.Players.Where(x => !x.IsSpectator).GroupBy(x => x.AllyID).OrderByDescending(x => x.Count()); IGrouping<int, PlayerTeam> biggest = groupedByTeam.FirstOrDefault(); if (biggest != null) { foreach (var other in groupedByTeam.Skip(1)) { int cnt = biggest.Count() - other.Count(); if (cnt > 0) { foreach (Account a in other.Select(x => db.Accounts.First(y => y.AccountID == x.LobbyID)).OrderByDescending(x => x.Elo*x.EloWeight).Take( cnt)) <API key>.Add(a.AccountID); } } } } bool is1v1 = context.Players.Where(x => !x.IsSpectator).ToList().Count == 2 && context.Bots.Count == 0; // write Planetwars details to modoptions (for widget) Faction attacker = null; Faction defender = null; Planet planet = null; if (mode == AutohostMode.Planetwars) { planet = db.Galaxies.First(x => x.IsDefault).Planets.First(x => x.Resource.InternalName == context.Map); attacker = context.Players.Where(x => x.AllyID == 0 && !x.IsSpectator) .Select(x => db.Accounts.First(y => y.AccountID == x.LobbyID)) .Where(x => x.Faction != null) .Select(x => x.Faction) .First(); defender = planet.Faction; if (attacker == defender) defender = null; ret.ModOptions.Add(new <API key>.ScriptKeyValuePair { Key = "attackingFaction", Value = attacker.Shortcut }); if (defender != null) ret.ModOptions.Add(new <API key>.ScriptKeyValuePair { Key = "defendingFaction", Value = defender.Shortcut }); ret.ModOptions.Add(new <API key>.ScriptKeyValuePair { Key = "planet", Value = planet.Name }); } // write player custom keys (level, elo, is muted, etc.) foreach (PlayerTeam p in context.Players) { Account user = db.Accounts.Find(p.LobbyID); if (user != null) { var userParams = new List<<API key>.ScriptKeyValuePair>(); ret.UserParameters.Add(new <API key>.<API key> { LobbyID = p.LobbyID, Parameters = userParams }); bool userBanMuted = user.<API key>.Any(x => !x.IsExpired && x.BanMute); if (userBanMuted) userParams.Add(new <API key>.ScriptKeyValuePair { Key = "muted", Value = "1" }); userParams.Add(new <API key>.ScriptKeyValuePair { Key = "faction", Value = user.Faction != null ? user.Faction.Shortcut : "" }); userParams.Add(new <API key>.ScriptKeyValuePair { Key = "clan", Value = user.Clan != null ? user.Clan.Shortcut : "" }); userParams.Add(new <API key>.ScriptKeyValuePair { Key = "level", Value = user.Level.ToString() }); double elo = mode == AutohostMode.Planetwars ? user.EffectivePwElo : (is1v1 ? user.Effective1v1Elo : user.EffectiveElo); userParams.Add(new <API key>.ScriptKeyValuePair { Key = "elo", Value = Math.Round(elo).ToString() }); // elo for ingame is just ordering for auto /take userParams.Add(new <API key>.ScriptKeyValuePair { Key = "avatar", Value = user.Avatar }); userParams.Add(new <API key>.ScriptKeyValuePair { Key = "admin", Value = (user.IsZeroKAdmin ? "1" : "0") }); if (!p.IsSpectator) { // set valid PW structure attackers if (mode == AutohostMode.Planetwars) { bool allied = user.Faction != null && defender != null && user.Faction != defender && defender.HasTreatyRight(user.Faction, x => x.<API key> == true, planet); if (!allied && user.Faction != null && (user.Faction == attacker || user.Faction == defender)) { userParams.Add(new <API key>.ScriptKeyValuePair { Key = "<API key>", Value = "1" }); } } var pu = new LuaTable(); bool userUnlocksBanned = user.<API key>.Any(x => !x.IsExpired && x.BanUnlocks); bool <API key> = user.<API key>.Any(x => !x.IsExpired && x.BanCommanders); if (!userUnlocksBanned) { if (mode != AutohostMode.Planetwars || user.Faction == null) foreach (Unlock unlock in user.AccountUnlocks.Select(x => x.Unlock)) pu.Add(unlock.Code); else { foreach (Unlock unlock in user.AccountUnlocks.Select(x => x.Unlock).Union(user.Faction.GetFactionUnlocks().Select(x => x.Unlock)).Where(x => x.UnlockType == UnlockTypes.Unit)) pu.Add(unlock.Code); } } userParams.Add(new <API key>.ScriptKeyValuePair { Key = "unlocks", Value = pu.ToBase64String() }); if (<API key>.Contains(user.AccountID)) userParams.Add(new <API key>.ScriptKeyValuePair { Key = "extracomm", Value = "1" }); var pc = new LuaTable(); if (!<API key>) { // set up commander data foreach (Commander c in user.Commanders.Where(x => x.Unlock != null && x.ProfileNumber <= GlobalConst.<API key>)) { try { if (string.IsNullOrEmpty(c.Name) || c.Name.Any(x => x == '"') ) { c.Name = c.CommanderID.ToString(); } LuaTable morphTable = new LuaTable(); pc["[\"" + c.Name + "\"]"] = morphTable; // process decoration icons LuaTable decorations = new LuaTable(); foreach (Unlock d in c.<API key>.Where(x => x.Unlock != null).OrderBy( x => x.SlotID).Select(x => x.Unlock)) { <API key> iconData = db.<API key>.FirstOrDefault(x => x.DecorationUnlockID == d.UnlockID); if (iconData != null) { string iconName = null, iconPosition = null; // FIXME: handle avatars and preset/custom icons if (iconData.IconType == (int)DecorationIconTypes.Faction) { iconName = user.Faction != null ? user.Faction.Shortcut : null; } else if (iconData.IconType == (int)DecorationIconTypes.Clan) { iconName = user.Clan != null ? user.Clan.Shortcut : null; } if (iconName != null) { iconPosition = CommanderDecoration.GetIconPosition(d); LuaTable entry = new LuaTable(); entry.Add("image", iconName); decorations.Add("icon_" + iconPosition.ToLower(), entry); } } else decorations.Add(d.Code); } string prevKey = null; for (int i = 0; i <= GlobalConst.NumCommanderLevels; i++) { string key = string.Format("c{0}_{1}_{2}", user.AccountID, c.ProfileNumber, i); morphTable.Add(key); // TODO: maybe don't specify morph series in player data, only starting unit var comdef = new LuaTable(); commanderTypes[key] = comdef; comdef["chassis"] = c.Unlock.Code + i; var modules = new LuaTable(); comdef["modules"] = modules; comdef["decorations"] = decorations; comdef["name"] = c.Name.Substring(0, Math.Min(25, c.Name.Length)) + " level " + i; //if (i < GlobalConst.NumCommanderLevels) // comdef["next"] = string.Format("c{0}_{1}_{2}", user.AccountID, c.ProfileNumber, i+1); //comdef["owner"] = user.Name; if (i > 0) { comdef["cost"] = c.<API key>(i); if (<API key>) { if (prevKey != null) comdef["prev"] = prevKey; prevKey = key; foreach (Unlock m in c.CommanderModules.Where(x => x.CommanderSlot.MorphLevel == i && x.Unlock != null).OrderBy( x => x.Unlock.UnlockType).ThenBy(x => x.SlotID).Select(x => x.Unlock)) modules.Add(m.Code); } else { foreach (Unlock m in c.CommanderModules.Where(x => x.CommanderSlot.MorphLevel <= i && x.Unlock != null).OrderBy( x => x.Unlock.UnlockType).ThenBy(x => x.SlotID).Select(x => x.Unlock)) modules.Add(m.Code); } } } } catch (Exception ex) { Trace.TraceError(ex.ToString()); throw new <API key>( string.Format("Error processing commander: {0} - {1} of player {2} - {3}", c.CommanderID, c.Name, user.AccountID, user.Name), ex); } } } else userParams.Add(new <API key>.ScriptKeyValuePair { Key = "jokecomm", Value = "1" }); userParams.Add(new <API key>.ScriptKeyValuePair { Key = "commanders", Value = pc.ToBase64String() }); } } } ret.ModOptions.Add(new <API key>.ScriptKeyValuePair { Key = "commanderTypes", Value = commanderTypes.ToBase64String() }); // set PW structures if (mode == AutohostMode.Planetwars) { string owner = planet.Faction != null ? planet.Faction.Shortcut : ""; var pwStructures = new LuaTable(); foreach (PlanetStructure s in planet.PlanetStructures.Where(x => x.StructureType!= null && !string.IsNullOrEmpty(x.StructureType.IngameUnitName))) { pwStructures.Add("s" + s.StructureTypeID, new LuaTable { { "unitname", s.StructureType.IngameUnitName }, //{ "isDestroyed", s.IsDestroyed ? true : false }, { "name", string.Format("{0} {1} ({2})", owner, s.StructureType.Name, s.Account!= null ? s.Account.Name:"unowned") }, { "description", s.StructureType.Description } }); } ret.ModOptions.Add(new <API key>.ScriptKeyValuePair { Key = "<API key>", Value = pwStructures.ToBase64String() }); } return ret; } catch (Exception ex) { Trace.TraceError(ex.ToString()); throw; } } } }
package com.kimkha.finanvita.ui; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.util.SparseBooleanArray; import android.view.*; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ListView; import com.kimkha.finanvita.R; import com.kimkha.finanvita.adapters.<API key>; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public abstract class ItemListFragment extends BaseFragment implements AdapterView.OnItemClickListener, LoaderManager.LoaderCallbacks<Cursor> { public static final String <API key> = ItemListFragment.class.getName() + ".<API key>"; public static final String <API key> = ItemListFragment.class.getName() + ".<API key>"; public static final int SELECTION_TYPE_NONE = 0; public static final int <API key> = 1; public static final int <API key> = 2; protected static final String ARG_SELECTION_TYPE = "ARG_SELECTION_TYPE"; protected static final String ARG_ITEM_IDS = "ARG_ITEM_IDS"; protected static final String <API key> = "<API key>"; protected static final String <API key> = "<API key>"; protected static final int LOADER_ITEMS = 1468; protected ListView list_V; protected View create_V; protected <API key> adapter; protected int selectionType; public static Bundle makeArgs(int selectionType, long[] itemIDs) { return makeArgs(selectionType, itemIDs, false); } public static Bundle makeArgs(int selectionType, long[] itemIDs, boolean isOpenDrawerLayout) { final Bundle args = new Bundle(); args.putInt(ARG_SELECTION_TYPE, selectionType); args.putLongArray(ARG_ITEM_IDS, itemIDs); args.putBoolean(<API key>, isOpenDrawerLayout); return args; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); // Get arguments final Bundle args = getArguments(); selectionType = args != null ? args.getInt(ARG_SELECTION_TYPE, SELECTION_TYPE_NONE) : SELECTION_TYPE_NONE; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_items_list, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Get views list_V = (ListView) view.findViewById(R.id.list_V); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Setup if (selectionType == SELECTION_TYPE_NONE) { create_V = LayoutInflater.from(getActivity()).inflate(R.layout.li_create_new, list_V, false); list_V.addFooterView(create_V); } adapter = createAdapter(getActivity()); list_V.setAdapter(adapter); list_V.<API key>(this); if (getArguments().getBoolean(<API key>, false)) { final int paddingHorizontal = getResources().<API key>(R.dimen.<API key>); list_V.setPadding(paddingHorizontal, list_V.getPaddingTop(), paddingHorizontal, list_V.getPaddingBottom()); } if (selectionType == <API key>) { list_V.setChoiceMode(AbsListView.<API key>); if (savedInstanceState != null) { final ArrayList<Integer> selectedPositions = savedInstanceState.getIntegerArrayList(<API key>); list_V.setTag(selectedPositions); } else { final long[] selectedIDs = getArguments().getLongArray(ARG_ITEM_IDS); list_V.setTag(selectedIDs); } } // Loader getLoaderManager().initLoader(LOADER_ITEMS, null, this); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (selectionType == <API key>) { final ArrayList<Integer> selectedPositions = new ArrayList<Integer>(); final SparseBooleanArray listPositions = list_V.<API key>(); if (listPositions != null) { for (int i = 0; i < listPositions.size(); i++) { if (listPositions.get(listPositions.keyAt(i))) selectedPositions.add(listPositions.keyAt(i)); } } outState.putIntegerArrayList(<API key>, selectedPositions); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.items_list, menu); } @Override public boolean <API key>(MenuItem item) { switch (item.getItemId()) { case R.id.action_create: startItemCreate(getActivity(), item.getActionView()); return true; } return super.<API key>(item); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle bundle) { switch (id) { case LOADER_ITEMS: return createItemsLoader(); } return null; } @Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { switch (cursorLoader.getId()) { case LOADER_ITEMS: bindItems(cursor); break; } } @Override public void onLoaderReset(Loader<Cursor> cursorLoader) { switch (cursorLoader.getId()) { case LOADER_ITEMS: bindItems(null); break; } } @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { switch (selectionType) { case SELECTION_TYPE_NONE: if (position == adapter.getCount()) startItemCreate(getActivity(), view); else startItemDetails(getActivity(), id, position, adapter, adapter.getCursor(), view); break; case <API key>: // Prepare extras final Bundle extras = new Bundle(); onItemSelected(id, adapter, adapter.getCursor(), extras); Intent data = new Intent(); data.putExtra(<API key>, id); data.putExtras(extras); getActivity().setResult(Activity.RESULT_OK, data); getActivity().finish(); break; case <API key>: adapter.setSelectedIDs(list_V.getCheckedItemIds()); break; } } protected abstract <API key> createAdapter(Context context); protected abstract Loader<Cursor> createItemsLoader(); /** * Called when item id along with extras should be returned to another activity. If only item id is necessary, you don't need to do anything. Just extra values should be put in outExtras. * * @param itemId Id of selected item. You don't need to put it to extras. This will be done automatically. * @param adapter Adapter for convenience. * @param c Cursor. * @param outExtras Put all additional data in here. */ protected abstract void onItemSelected(long itemId, <API key> adapter, Cursor c, Bundle outExtras); /** * Called when you should start item detail activity * * @param context Context. * @param itemId Id of selected item. * @param position Selected position. * @param adapter Adapter for convenience. * @param c Cursor. * @param view */ protected abstract void startItemDetails(Context context, long itemId, int position, <API key> adapter, Cursor c, View view); /** * Start item create activity here. */ protected abstract void startItemCreate(Context context, View view); public long[] getSelectedItemIDs() { return list_V.getCheckedItemIds(); } protected void bindItems(Cursor c) { boolean <API key> = adapter.getCount() == 0 && selectionType == <API key>; adapter.swapCursor(c); if (<API key> && list_V.getTag() != null) { final Object tag = list_V.getTag(); if (tag instanceof ArrayList) { //noinspection unchecked final ArrayList<Integer> selectedPositions = (ArrayList<Integer>) tag; list_V.setTag(selectedPositions); //noinspection <API key> for (int i = 0; i < selectedPositions.size(); i++) list_V.setItemChecked(selectedPositions.get(i), true); } else if (tag instanceof long[]) { final long[] selectedIDs = (long[]) tag; final Set<Long> selectedIDsSet = new HashSet<Long>(); //noinspection <API key> for (int i = 0; i < selectedIDs.length; i++) selectedIDsSet.add(selectedIDs[i]); long itemId; for (int i = 0; i < adapter.getCount(); i++) { itemId = list_V.getItemIdAtPosition(i); if (selectedIDsSet.contains(itemId)) { selectedIDsSet.remove(itemId); list_V.setItemChecked(i, true); if (selectedIDsSet.size() == 0) break; } } } adapter.setSelectedIDs(list_V.getCheckedItemIds()); } } }
#ifndef __LINUX_VIDEODEV_H #define __LINUX_VIDEODEV_H /* $XFree86: xc/programs/Xserver/hw/xfree86/drivers/v4l/videodev.h,v 1.8 2001/03/03 22:46:31 tsi Exp $ */ #include "Xmd.h" #define VID_TYPE_CAPTURE 1 /* Can capture */ #define VID_TYPE_TUNER 2 /* Can tune */ #define VID_TYPE_TELETEXT 4 /* Does teletext */ #define VID_TYPE_OVERLAY 8 /* Overlay onto frame buffer */ #define VID_TYPE_CHROMAKEY 16 /* Overlay by chromakey */ #define VID_TYPE_CLIPPING 32 /* Can clip */ #define VID_TYPE_FRAMERAM 64 /* Uses the frame buffer memory */ #define VID_TYPE_SCALES 128 /* Scalable */ #define VID_TYPE_MONOCHROME 256 /* Monochrome only */ #define VID_TYPE_SUBCAPTURE 512 /* Can capture subareas of the image */ struct video_capability { char name[32]; int type; int channels; /* Num channels */ int audios; /* Num audio devices */ int maxwidth; /* Supported width */ int maxheight; /* And height */ int minwidth; /* Supported width */ int minheight; /* And height */ }; struct video_channel { int channel; char name[32]; int tuners; CARD32 flags; #define VIDEO_VC_TUNER 1 /* Channel has a tuner */ #define VIDEO_VC_AUDIO 2 /* Channel has audio */ CARD16 type; #define VIDEO_TYPE_TV 1 #define VIDEO_TYPE_CAMERA 2 CARD16 norm; /* Norm set by channel */ }; struct video_tuner { int tuner; char name[32]; unsigned long rangelow, rangehigh; /* Tuner range */ CARD32 flags; #define VIDEO_TUNER_PAL 1 #define VIDEO_TUNER_NTSC 2 #define VIDEO_TUNER_SECAM 4 #define VIDEO_TUNER_LOW 8 /* Uses KHz not MHz */ #define VIDEO_TUNER_NORM 16 /* Tuner can set norm */ #define <API key> 128 /* Tuner is seeing stereo */ CARD16 mode; /* PAL/NTSC/SECAM/OTHER */ #define VIDEO_MODE_PAL 0 #define VIDEO_MODE_NTSC 1 #define VIDEO_MODE_SECAM 2 #define VIDEO_MODE_AUTO 3 CARD16 signal; /* Signal strength 16bit scale */ }; struct video_picture { CARD16 brightness; CARD16 hue; CARD16 colour; CARD16 contrast; CARD16 whiteness; /* Black and white only */ CARD16 depth; /* Capture depth */ CARD16 palette; /* Palette in use */ #define VIDEO_PALETTE_GREY 1 /* Linear greyscale */ #define VIDEO_PALETTE_HI240 2 /* High 240 cube (BT848) */ #define <API key> 3 /* 565 16 bit RGB */ #define VIDEO_PALETTE_RGB24 4 /* 24bit RGB */ #define VIDEO_PALETTE_RGB32 5 /* 32bit RGB */ #define <API key> 6 /* 555 15bit RGB */ #define <API key> 7 /* YUV422 capture */ #define VIDEO_PALETTE_YUYV 8 #define VIDEO_PALETTE_UYVY 9 /* The great thing about standards is ... */ #define <API key> 10 #define <API key> 11 /* YUV411 capture */ #define VIDEO_PALETTE_RAW 12 /* RAW capture (BT848) */ #define <API key> 13 /* YUV 4:2:2 Planar */ #define <API key> 14 /* YUV 4:1:1 Planar */ #define <API key> 15 /* YUV 4:2:0 Planar */ #define <API key> 16 /* YUV 4:1:0 Planar */ #define <API key> 13 /* start of planar entries */ #define <API key> 7 /* start of component entries */ }; struct video_audio { int audio; /* Audio channel */ CARD16 volume; /* If settable */ CARD16 bass, treble; CARD32 flags; #define VIDEO_AUDIO_MUTE 1 #define VIDEO_AUDIO_MUTABLE 2 #define VIDEO_AUDIO_VOLUME 4 #define VIDEO_AUDIO_BASS 8 #define VIDEO_AUDIO_TREBLE 16 char name[16]; #define VIDEO_SOUND_MONO 1 #define VIDEO_SOUND_STEREO 2 #define VIDEO_SOUND_LANG1 4 #define VIDEO_SOUND_LANG2 8 CARD16 mode; CARD16 balance; /* Stereo balance */ CARD16 step; /* Step actual volume uses */ }; struct video_clip { INT32 x,y; INT32 width, height; struct video_clip *next; /* For user use/driver use only */ }; struct video_window { CARD32 x,y; /* Position of window */ CARD32 width,height; /* Its size */ CARD32 chromakey; CARD32 flags; struct video_clip *clips; /* Set only */ int clipcount; #define <API key> 1 #define VIDEO_CLIP_BITMAP -1 /* bitmap is 1024x625, a '1' bit represents a clipped pixel */ #define VIDEO_CLIPMAP_SIZE (128 * 625) }; struct video_capture { CARD32 x,y; /* Offsets into image */ CARD32 width, height; /* Area to capture */ CARD16 decimation; /* Decimation divder */ CARD16 flags; /* Flags for capture */ #define VIDEO_CAPTURE_ODD 0 /* Temporal */ #define VIDEO_CAPTURE_EVEN 1 }; struct video_buffer { void *base; int height,width; int depth; int bytesperline; }; struct video_mmap { unsigned int frame; /* Frame (0 - n) for double buffer */ int height,width; unsigned int format; /* should be VIDEO_PALETTE_* */ }; struct video_key { CARD8 key[8]; CARD32 flags; }; #define VIDEO_MAX_FRAME 32 struct video_mbuf { int size; /* Total memory to map */ int frames; /* Frames */ int offsets[VIDEO_MAX_FRAME]; }; #define VIDEO_NO_UNIT (-1) struct video_unit { int video; /* Video minor */ int vbi; /* VBI minor */ int radio; /* Radio minor */ int audio; /* Audio minor */ int teletext; /* Teletext minor */ }; #define VIDIOCGCAP _IOR('v',1,struct video_capability) /* Get capabilities */ #define VIDIOCGCHAN _IOWR('v',2,struct video_channel) /* Get channel info (sources) */ #define VIDIOCSCHAN _IOW('v',3,struct video_channel) /* Set channel */ #define VIDIOCGTUNER _IOWR('v',4,struct video_tuner) /* Get tuner abilities */ #define VIDIOCSTUNER _IOW('v',5,struct video_tuner) /* Tune the tuner for the current channel */ #define VIDIOCGPICT _IOR('v',6,struct video_picture) /* Get picture properties */ #define VIDIOCSPICT _IOW('v',7,struct video_picture) /* Set picture properties */ #define VIDIOCCAPTURE _IOW('v',8,int) /* Start, end capture */ #define VIDIOCGWIN _IOR('v',9, struct video_window) /* Set the video overlay window */ #define VIDIOCSWIN _IOW('v',10, struct video_window) /* Set the video overlay window - passes clip list for hardware smarts , chromakey etc */ #define VIDIOCGFBUF _IOR('v',11, struct video_buffer) /* Get frame buffer */ #define VIDIOCSFBUF _IOW('v',12, struct video_buffer) /* Set frame buffer - root only */ #define VIDIOCKEY _IOR('v',13, struct video_key) /* Video key event - to dev 255 is to all - cuts capture on all DMA windows with this key (0xFFFFFFFF == all) */ #define VIDIOCGFREQ _IOR('v',14, unsigned long) /* Set tuner */ #define VIDIOCSFREQ _IOW('v',15, unsigned long) /* Set tuner */ #define VIDIOCGAUDIO _IOR('v',16, struct video_audio) /* Get audio info */ #define VIDIOCSAUDIO _IOW('v',17, struct video_audio) /* Audio source, mute etc */ #define VIDIOCSYNC _IOW('v',18, int) /* Sync with mmap grabbing */ #define VIDIOCMCAPTURE _IOW('v',19, struct video_mmap) /* Grab frames */ #define VIDIOCGMBUF _IOR('v', 20, struct video_mbuf) /* Memory map buffer info */ #define VIDIOCGUNIT _IOR('v', 21, struct video_unit) /* Get attached units */ #define VIDIOCGCAPTURE _IOR('v',22, struct video_capture) /* Get frame buffer */ #define VIDIOCSCAPTURE _IOW('v',23, struct video_capture) /* Set frame buffer - root only */ #define BASE_VIDIOCPRIVATE 192 /* 192-255 are private */ #define VID_HARDWARE_BT848 1 #define <API key> 2 #define VID_HARDWARE_PMS 3 #define VID_HARDWARE_QCAM_C 4 #define VID_HARDWARE_PSEUDO 5 #define <API key> 6 #define VID_HARDWARE_AZTECH 7 #define VID_HARDWARE_SF16MI 8 #define VID_HARDWARE_RTRACK 9 #define <API key> 10 #define <API key> 11 #define VID_HARDWARE_VIDEUM 12 /* Reserved for Winnov videum */ #define <API key> 13 #define <API key> 14 /* Reserved for Permedia2 */ #define <API key> 15 /* Reserved for RIVA 128 */ #define VID_HARDWARE_PLANB 16 /* PowerMac motherboard video-in */ #define <API key> 17 /* Broadway project */ #define VID_HARDWARE_GEMTEK 18 #define <API key> 19 #define VID_HARDWARE_VINO 20 /* Reserved for SGI Indy Vino */ /* * Initialiser list */ struct video_init { char *name; int (*init)(struct video_init *); }; #endif
# List of contents * [User guide](@ref axo_gui) * [Compiling from source](@ref compile) * [Getting started](@ref getting_started) </br> * [For developers] (@ref developers) * [Updating the firmware] (@ref updating_firmware) * [Directory structure] (@ref directory_structure) * [For PureData users] (@ref pd_user) </br> * [Roadmap] (@ref roadmap)
// This file is part of Mox, a card game simulator. // Mox is free software: you can redistribute it and/or modify // Mox is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the using System; using Mox.Events; using Mox.Flow; namespace Mox.Database.Library { public abstract class <API key> : TriggeredAbility, IEventHandler<ZoneChangeEvent> { #region Inner Types protected class ZoneChangeContext { public readonly Resolvable<Card> Card; public ZoneChangeContext(Card card) { Card = card; } } #endregion #region Methods <summary> Returns true if the card can trigger the ability. </summary> <remarks> By default, checks if the card is the source. </remarks> <param name="card"></param> <returns></returns> protected virtual bool IsValidCard(Card card) { return card == Source; } <summary> Returns true if this is the zone from which the card should come from. </summary> <param name="zone"></param> <returns></returns> protected virtual bool <API key>(Zone zone) { return true; } private bool <API key>(Game game, ZoneChangeContext zoneChangeContext) { return zoneChangeContext.Card.Resolve(game).Zone.ZoneId == TriggerZone; } public override bool CanPushOnStack(Game game, object zoneChangeContext) { return <API key>(game, (ZoneChangeContext) zoneChangeContext); } public override sealed void Play(Spell spell) { ZoneChangeContext zoneChangeContext = (ZoneChangeContext)spell.Context; Play(spell, zoneChangeContext.Card); } protected internal override void ResolveSpellEffect(Part.Context context, Spell spell) { if (<API key>(context.Game, (ZoneChangeContext)spell.Context)) { base.ResolveSpellEffect(context, spell); } } protected abstract void Play(Spell spell, Resolvable<Card> card); void IEventHandler<ZoneChangeEvent>.HandleEvent(Game game, ZoneChangeEvent e) { if (IsValidCard(e.Card) && <API key>(e.OldZone) && e.NewZone.ZoneId == TriggerZone) { Trigger(new ZoneChangeContext(e.Card)); } } #endregion } }
package com.thomasjensen.checkstyle.addons.checks; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import net.jcip.annotations.Immutable; /** * Represents a Java binary class name for reference types, in the form of its fragments. This is the only way to tell * the difference between a class called <code>A$B</code> and a class called <code>A</code> that has an inner class * <code>B</code>. */ @Immutable public final class BinaryName { private final String pkg; private final List<String> cls; /** * Constructor. * * @param pPkg package name * @param pOuterCls outer class simple name * @param pInnerCls inner class simple names in descending order of their nesting */ public BinaryName(@Nullable final String pPkg, @Nonnull final String pOuterCls, @Nullable final String... pInnerCls) { pkg = pPkg; List<String> nameList = new ArrayList<>(); if (pOuterCls != null) { nameList.add(pOuterCls); } else { throw new <API key>("pOuterCls was null"); } if (pInnerCls != null) { for (final String inner : pInnerCls) { nameList.add(inner); } } cls = Collections.unmodifiableList(nameList); } /** * Constructor. * * @param pPkg package name * @param pClsNames class simple names in descending order of their nesting */ public BinaryName(@Nullable final String pPkg, @Nonnull final Collection<String> pClsNames) { pkg = pPkg; if (pClsNames.size() == 0) { throw new <API key>("pClsNames is empty"); } cls = Collections.unmodifiableList(new ArrayList<>(pClsNames)); } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (pkg != null) { sb.append(pkg); sb.append('.'); } for (final Iterator<String> iter = cls.iterator(); iter.hasNext();) { sb.append(iter.next()); if (iter.hasNext()) { sb.append('$'); } } return sb.toString(); } @Override public boolean equals(final Object pOther) { if (this == pOther) { return true; } if (pOther == null || getClass() != pOther.getClass()) { return false; } BinaryName other = (BinaryName) pOther; if (pkg != null ? !pkg.equals(other.pkg) : other.pkg != null) { return false; } if (!cls.equals(other.cls)) { return false; } return true; } @Override public int hashCode() { int result = pkg != null ? pkg.hashCode() : 0; result = 31 * result + cls.hashCode(); return result; } public String getPackage() { return pkg; } /** * Getter. * * @return the simple name of the outer class (even if this binary name represents an inner class) */ public String getOuterSimpleName() { return cls.get(0); } /** * Getter. * * @return the simple name of the inner class represented by this binary name. <code>null</code> if this binary name * does not represent an inner class */ public String getInnerSimpleName() { return cls.size() > 1 ? cls.get(cls.size() - 1) : null; } /** * The fully qualified name of the outer class. * * @return that, or <code>null</code> if the simple name of the outer class is unknown */ @CheckForNull public String getOuterFqcn() { return (pkg != null ? (pkg + ".") : "") + getOuterSimpleName(); } }
#include "Board.h" #include <iostream> using namespace std; void Board::enumExts( ) { if(ptester-><API key>()) { for( int i = 1; i <= nrows; i++ ) if( PiecesInRow[i] > 1 ) { cout << 0 << endl; return; } } _enumExts(); } void Board::_enumExts( ) { Place P(1,1); if( n() != 0 ) { P = top(); if( PiecesInOrBelowRow[P.row] == n() ) { P.row++; P.col = 1; } } while( P.col <= ncols ) { if( ! IsAttacked(P) ) { push(P); if( n() == npieces ) report( ); else _enumExts( ); pop(); } P.col++; } if( n() == 0 ) cout << sol_count << endl; } void Board::print( ) { int row, col; for( row = nrows; row > 0; row { for( col = 1; col <= ncols; col++) // if(in(row,col)) cout << '*'; else cout << '0'; if(in(row,col)) cout << '#'; else cout << 'O'; cout << endl; } cout << endl; } void Board::report( ) { sol_count++; if( show_boards ) { cout << "Board " << sol_count << ':' << endl; print( ); } } #include "AttackTester.h" static void useage() { cerr << "Options:\n\ --show-boards\n\ --pieces-per-row n1,n2,n3,...nr [default 1,1,1,...]\n\ --nrows m [default 4]\n\ --ncols n [default 4]\n\ --piece queen [default]\n\ --piece king\n\ --piece rook or others added" << endl; exit( 1 ); } int main(int argc, char *argv[]) { int nrows=4; int ncols=4; bool show_boards = false; int A[Board::Maxrows]; bool piecesPerRowGiven = false; AttackTester *ptester = getp("queen"); argc argv++; while( argc { if(!strcmp(*argv,"--show-boards")) { show_boards = true; argv++; continue; } if(!strcmp(*argv,"--pieces-per-row")) { char *p = *(++argv); int i; for(i = 0; (i < Board::Maxrows) && *p!='\0'; i++ ) { A[i] = strtol(p,&p,0); if( *p == ',' ) p++; else if( *p != '\0' ) useage(); } for( ; i < Board::Maxrows; i++ ) A[i] = 1; piecesPerRowGiven = true; argv++; argc continue; } if(!strcmp(*argv,"--nrows")) { argv++; argc nrows=strtol(*(argv++),NULL,0); continue; } if(!strcmp(*argv,"--ncols")) { argv++; argc ncols=strtol(*(argv++),NULL,0); continue; } if(!strcmp(*argv,"--piece")) { argv++; argc ptester = getp(*(argv++)); if( !ptester ) { cerr << "Unimplemented Piece:" << *(argv - 1) << endl; exit ( 1 ); } continue; } } if(piecesPerRowGiven) { Board myBoard(nrows, ncols, ptester, show_boards, A); myBoard.enumExts( ); } else { Board myBoard(nrows, ncols, ptester, show_boards, NULL ); myBoard.enumExts( ); } return 0; }
package com.idega.data.query; import java.util.HashSet; import java.util.Set; import com.idega.data.query.output.Output; import com.idega.data.query.output.Outputable; import com.idega.data.query.output.ToStringer; public class LeftJoin implements Outputable { private Column left, right; public LeftJoin(Column left, Column right) { this.left = left; this.right = right; } public Column getLeftColumn() { return this.left; } public Column getRightColumn() { return this.right; } @Override public void write(Output out) { out.print(this.left.getTable()) .print(" left join ") .print(this.right.getTable()) .print(" on ") .print(this.left) .print(" = ") .print(this.right); } public Set<Table> getTables(){ Set<Table> s = new HashSet<Table>(); s.add(this.left.getTable()); s.add(this.right.getTable()); return s; } @Override public String toString() { return ToStringer.toString(this); } }
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class fAwards Inherits System.Windows.Forms.Form 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.components = New System.ComponentModel.Container() Me.Timer1 = New System.Windows.Forms.Timer(Me.components) Me.ListBox3 = New System.Windows.Forms.ListBox() Me.lst_Awards = New System.Windows.Forms.ListBox() Me.SlcTheme1 = New dsTycoon.SLCTheme() Me.GroupBox1 = New System.Windows.Forms.GroupBox() Me.Label1 = New System.Windows.Forms.Label() Me.Button2 = New dsTycoon.SLCbtn() Me.SlcTheme1.SuspendLayout() Me.GroupBox1.SuspendLayout() Me.SuspendLayout() ' 'Timer1 ' ' 'ListBox3 ' Me.ListBox3.FormattingEnabled = True Me.ListBox3.Location = New System.Drawing.Point(565, 430) Me.ListBox3.Name = "ListBox3" Me.ListBox3.Size = New System.Drawing.Size(97, 56) Me.ListBox3.TabIndex = 12 Me.ListBox3.Visible = False ' 'lst_Awards ' Me.lst_Awards.FormattingEnabled = True Me.lst_Awards.Location = New System.Drawing.Point(12, 430) Me.lst_Awards.Name = "lst_Awards" Me.lst_Awards.Size = New System.Drawing.Size(59, 30) Me.lst_Awards.TabIndex = 109 Me.lst_Awards.Visible = False ' 'SlcTheme1 ' Me.SlcTheme1.BackColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(57, Byte), Integer), CType(CType(72, Byte), Integer)) Me.SlcTheme1.BorderStyle = System.Windows.Forms.FormBorderStyle.None Me.SlcTheme1.Controls.Add(Me.GroupBox1) Me.SlcTheme1.Controls.Add(Me.Button2) Me.SlcTheme1.Controls.Add(Me.ListBox3) Me.SlcTheme1.Customization = "JRIV/zYjIP82IyD/JRIV/w==" Me.SlcTheme1.Dock = System.Windows.Forms.DockStyle.Fill Me.SlcTheme1.Font = New System.Drawing.Font("Verdana", 8.0!) Me.SlcTheme1.Image = Nothing Me.SlcTheme1.Location = New System.Drawing.Point(0, 0) Me.SlcTheme1.Movable = True Me.SlcTheme1.Name = "SlcTheme1" Me.SlcTheme1.NoRounding = False Me.SlcTheme1.Sizable = True Me.SlcTheme1.Size = New System.Drawing.Size(681, 472) Me.SlcTheme1.SmartBounds = True Me.SlcTheme1.StartPosition = System.Windows.Forms.FormStartPosition.<API key> Me.SlcTheme1.TabIndex = 110 Me.SlcTheme1.TransparencyKey = System.Drawing.Color.Fuchsia Me.SlcTheme1.Transparent = False ' 'GroupBox1 ' Me.GroupBox1.BackColor = System.Drawing.Color.WhiteSmoke Me.GroupBox1.BackgroundImage = Global.dsTycoon.My.Resources.Resources.gameawards1 Me.GroupBox1.Controls.Add(Me.Label1) Me.GroupBox1.Location = New System.Drawing.Point(32, 24) Me.GroupBox1.Name = "GroupBox1" Me.GroupBox1.Size = New System.Drawing.Size(630, 400) Me.GroupBox1.TabIndex = 13 Me.GroupBox1.TabStop = False ' 'Label1 ' Me.Label1.Location = New System.Drawing.Point(6, 379) Me.Label1.Name = "Label1" Me.Label1.Size = New System.Drawing.Size(402, 357) Me.Label1.TabIndex = 0 Me.Label1.Text = "Label1" ' 'Button2 ' Me.Button2.Colors = New dsTycoon.Bloom(-1) {} Me.Button2.Customization = "" Me.Button2.Font = New System.Drawing.Font("Verdana", 8.0!) Me.Button2.Image = Nothing Me.Button2.Location = New System.Drawing.Point(313, 430) Me.Button2.Name = "Button2" Me.Button2.NoRounding = False Me.Button2.Size = New System.Drawing.Size(78, 22) Me.Button2.TabIndex = 10 Me.Button2.Text = " Accept" Me.Button2.Transparent = False ' 'fAwards ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.BackColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(57, Byte), Integer), CType(CType(72, Byte), Integer)) Me.ClientSize = New System.Drawing.Size(681, 472) Me.Controls.Add(Me.lst_Awards) Me.Controls.Add(Me.SlcTheme1) Me.DoubleBuffered = True Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None Me.MaximizeBox = False Me.Name = "fAwards" Me.Text = "Dev Studio Tycoon Awards" Me.TransparencyKey = System.Drawing.Color.Fuchsia Me.SlcTheme1.ResumeLayout(False) Me.GroupBox1.ResumeLayout(False) Me.ResumeLayout(False) End Sub Friend WithEvents Timer1 As System.Windows.Forms.Timer Friend WithEvents ListBox3 As System.Windows.Forms.ListBox Friend WithEvents lst_Awards As System.Windows.Forms.ListBox Friend WithEvents SlcTheme1 As dsTycoon.SLCTheme Friend WithEvents Button2 As dsTycoon.SLCbtn Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox Friend WithEvents Label1 As System.Windows.Forms.Label End Class
title: "मेरा इस्तीफा राफेल को लेकर हुआ है : तारिक अनवर" layout: item category: ["politics"] date: 2018-09-29T04:19:03.930Z image: 1538214543927tariq.jpg <p>नई दिल्ली: राष्ट्रवादी कांग्रेस पार्टी (एनसीपी) और लोकसभा सदस्यता से इस्तीफा दे चुके वरिष्ठ नेता तारिक अनवर का कहना है कि & <p>तारिक अनवर से जब पूछा गया कि अब एनसीपी कह रही है कि पवार साहब का इंटरव्यू तोड़मरोड़ के दिखाया गया? तो अनवर ने कहा कि यह क्लेरिफिकेशन देने में एनसीपी ने बहुत देर कर दी है. अब मैं अपना फैसला ले चुका हूं.</p> <p>कयास लग रहे हैं कि आप कांग्रेस में जा रहे हैं? इस सवाल पर तारिक अनवर ने कहा कि अभी कुछ कहना जल्दबाज़ी होगी. मैं दिल्ली आया हूं, कार्यकर्ताओं से बात करूंगा. पर जो करूंगा वह बीजेपी के खिलाफ होगा.</p> <p>जब उनसे पूछा कि महागठबंधन में भी क्या आपकी कोई भूमिका रहेगी अब? तो तारिक अनवर ने कहा कि हां मेरी सारी लाइक माइंडेड पार्टियों को साथ लेने की कोशिश रहेगी. राफेल देश में बड़ा घोटाला है.</p>
package it.emarolab.owloop.descriptor.utility.classDescriptor; import it.emarolab.amor.owlInterface.OWLReferences; import it.emarolab.owloop.descriptor.construction.descriptorEntitySet.Individuals; import it.emarolab.owloop.descriptor.construction.<API key>.ClassExpression; import it.emarolab.owloop.descriptor.construction.descriptorGround.ClassGround; import it.emarolab.owloop.descriptor.utility.<API key>.LinkIndividualDesc; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLNamedIndividual; import java.util.List; public class InstanceClassDesc extends ClassGround implements ClassExpression.Instance<LinkIndividualDesc> { private Individuals individuals = new Individuals(); /* Constructors from class: ClassGround */ public InstanceClassDesc(OWLClass instance, OWLReferences onto) { super(instance, onto); } public InstanceClassDesc(String instanceName, OWLReferences onto) { super(instanceName, onto); } public InstanceClassDesc(OWLClass instance, String ontoName) { super(instance, ontoName); } public InstanceClassDesc(OWLClass instance, String ontoName, String filePath, String iriPath) { super(instance, ontoName, filePath, iriPath); } public InstanceClassDesc(OWLClass instance, String ontoName, String filePath, String iriPath, boolean bufferingChanges) { super(instance, ontoName, filePath, iriPath, bufferingChanges); } public InstanceClassDesc(String instanceName, String ontoName) { super(instanceName, ontoName); } public InstanceClassDesc(String instanceName, String ontoName, String filePath, String iriPath) { super(instanceName, ontoName, filePath, iriPath); } public InstanceClassDesc(String instanceName, String ontoName, String filePath, String iriPath, boolean bufferingChanges) { super(instanceName, ontoName, filePath, iriPath, bufferingChanges); } /* Overriding methods in class: ClassGround */ // To read axioms from an ontology @Override public List<MappingIntent> readAxioms() { return Instance.super.readAxioms(); } // To write axioms to an ontology @Override public List<MappingIntent> writeAxioms() { return Instance.super.writeAxioms(); } /* Overriding methods in classes: Class and ClassExpression */ // Is used by the descriptors's build() method. It's possible to change the return type based on need. @Override public LinkIndividualDesc <API key>(OWLNamedIndividual instance, OWLReferences ontology) { return new LinkIndividualDesc( instance, ontology); } // It returns Individuals from the EntitySet (after being read from the ontology) @Override public Individuals getIndividuals() { return individuals; } /* Overriding method in class: Object */ // To show internal state of the Descriptor @Override public String toString() { return getClass().getSimpleName() + "{" + "\n" + "\n" + "\t" + getGround() + ":" + "\n" + "\n" + "\t\t⇐ " + individuals + "\n" + "}" + "\n"; } }
// -*- Mode: Go; indent-tabs-mode: t -*- package store import ( "io" "net/http" "net/url" "github.com/juju/ratelimit" "golang.org/x/net/context" "gopkg.in/retry.v1" "github.com/snapcore/snapd/overlord/auth" "github.com/snapcore/snapd/progress" "github.com/snapcore/snapd/snap" "github.com/snapcore/snapd/testutil" ) var ( HardLinkCount = hardLinkCount ApiURL = apiURL Download = download UseDeltas = useDeltas ApplyDelta = applyDelta AuthLocation = authLocation AuthURL = authURL StoreURL = storeURL StoreDeveloperURL = storeDeveloperURL MustBuy = mustBuy <API key> = <API key> DischargeAuthCaveat = dischargeAuthCaveat <API key> = <API key> <API key> = <API key> <API key> = <API key> LoginCaveatID = loginCaveatID JsonContentType = jsonContentType SnapActionFields = snapActionFields ) // <API key> mocks the retry strategy used by several store requests func <API key>(t *testutil.BaseTest, strategy retry.Strategy) { <API key> := <API key> <API key> = strategy t.AddCleanup(func() { <API key> = <API key> }) } func <API key>(t *testutil.BaseTest, strategy retry.Strategy) { <API key> := connCheckStrategy connCheckStrategy = strategy t.AddCleanup(func() { connCheckStrategy = <API key> }) } func (cm *CacheManager) CacheDir() string { return cm.cacheDir } func (cm *CacheManager) Cleanup() error { return cm.cleanup() } func (cm *CacheManager) Count() int { return cm.count() } func MockOsRemove(f func(name string) error) func() { oldOsRemove := osRemove osRemove = f return func() { osRemove = oldOsRemove } } func MockDownload(f func(ctx context.Context, name, sha3_384, downloadURL string, user *auth.UserState, s *Store, w io.ReadWriteSeeker, resume int64, pbar progress.Meter, dlOpts *DownloadOptions) error) (restore func()) { origDownload := download download = f return func() { download = origDownload } } func MockApplyDelta(f func(name string, deltaPath string, deltaInfo *snap.DeltaInfo, targetPath string, targetSha3_384 string) error) (restore func()) { origApplyDelta := applyDelta applyDelta = f return func() { applyDelta = origApplyDelta } } func (sto *Store) MockCacher(obs downloadCache) (restore func()) { oldCacher := sto.cacher sto.cacher = obs return func() { sto.cacher = oldCacher } } func (sto *Store) SetDeltaFormat(dfmt string) { sto.deltaFormat = dfmt } func (sto *Store) DownloadDelta(deltaName string, downloadInfo *snap.DownloadInfo, w io.ReadWriteSeeker, pbar progress.Meter, user *auth.UserState) error { return sto.downloadDelta(deltaName, downloadInfo, w, pbar, user) } func (sto *Store) DoRequest(ctx context.Context, client *http.Client, reqOptions *requestOptions, user *auth.UserState) (*http.Response, error) { return sto.doRequest(ctx, client, reqOptions, user) } func (sto *Store) Client() *http.Client { return sto.client } func (sto *Store) DetailFields() []string { return sto.detailFields } func (sto *Store) DecorateOrders(snaps []*snap.Info, user *auth.UserState) error { return sto.decorateOrders(snaps, user) } func (cfg *Config) SetBaseURL(u *url.URL) error { return cfg.setBaseURL(u) } func NewHashError(name, sha3_384, targetSha3_384 string) HashError { return HashError{name, sha3_384, targetSha3_384} } func NewRequestOptions(mth string, url *url.URL) *requestOptions { return &requestOptions{ Method: mth, URL: url, } } func MockRatelimitReader(f func(r io.Reader, bucket *ratelimit.Bucket) io.Reader) (restore func()) { oldRatelimitReader := ratelimitReader ratelimitReader = f return func() { ratelimitReader = oldRatelimitReader } }
using System; using System.Threading; using System.Windows.Input; namespace WpfAsyncPack.Internal { internal sealed class CancelAsyncCommand : ICommand { private <API key> <API key> = new <API key>(); private bool _isCommandExecuting; public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public CancellationToken Token => <API key>.Token; void ICommand.Execute(object parameter) { <API key>.Cancel(); <API key>(); } bool ICommand.CanExecute(object parameter) { return _isCommandExecuting && !<API key>.<API key>; } public void <API key>() { _isCommandExecuting = true; if (<API key>.<API key>) { <API key> = new <API key>(); <API key>(); } } public void <API key>() { _isCommandExecuting = false; <API key>(); } private static void <API key>() { CommandManager.<API key>(); } } }
<template name="views_contracts"> <div class="dapp-container"> <h1>{{i18n "wallet.contracts.contractTitle"}}</h1> <a href="{{pathFor route='deployContract'}}" class="wallet-box create"> <div class="account-pattern"> + </div> <h3>{{i18n "wallet.contracts.deployNewContract"}}</h3> </a> <h2>{{i18n "wallet.contracts.customContracts"}}</h2> <p>{{i18n "wallet.contracts.description" }}</p> <div class="dapp-clear-fix"></div> <div class="wallet-box-list"> {{#each customContracts}} {{> elements_account account=_id isContract=true}} {{/each}} </div> <button class="wallet-box create add-contract"> <div class="account-pattern"> + </div> <h3>{{i18n "wallet.contracts.addCustomContract"}}</h3> </button> <div class="dapp-clear-fix"></div> <br><br> <h2>{{{i18n "wallet.tokens.title"}}}</h2> <p> {{{i18n "wallet.tokens.description"}}} </p> <div class="dapp-clear-fix"></div> <div class="wallet-box-list"> {{#each tokens}} {{> elements_tokenBox}} {{/each}} </div> <button class="wallet-box create add-token"> <div class="account-pattern"> + </div> <h3>{{i18n "wallet.app.buttons.addToken"}}</h3> </button> </div> </template>
<?php /** * The core plugin class. * * This is used to define <API key>, admin-specific hooks, and * public-facing site hooks. * * Also maintains the unique identifier of this plugin as well as the current * version of the plugin. * * @since 1.0.0 * @package <API key> * @subpackage <API key>/includes * @author Stephane Tauziede <stauziede@gmail.com> */ class <API key> { /** * The loader that's responsible for maintaining and registering all hooks that power * the plugin. * * @since 1.0.0 * @access protected * @var <API key> $loader Maintains and registers all hooks for the plugin. */ protected $loader; /** * The unique identifier of this plugin. * * @since 1.0.0 * @access protected * @var string $plugin_name The string used to uniquely identify this plugin. */ protected $plugin_name; /** * The current version of the plugin. * * @since 1.0.0 * @access protected * @var string $version The current version of the plugin. */ protected $version; /** * Define the core functionality of the plugin. * * Set the plugin name and the plugin version that can be used throughout the plugin. * Load the dependencies, define the locale, and set the hooks for the admin area and * the public-facing side of the site. * * @since 1.0.0 */ public function __construct() { $this->plugin_name = '<API key>'; $this->version = '1.0.0'; $this->load_dependencies(); $this->set_locale(); $this->define_admin_hooks(); $this->define_public_hooks(); } /** * Load the required dependencies for this plugin. * * Include the following files that make up the plugin: * * - <API key>. Orchestrates the hooks of the plugin. * - <API key>. Defines <API key> functionality. * - <API key>. Defines all hooks for the admin area. * - <API key>. Defines all hooks for the public side of the site. * * Create an instance of the loader which will be used to register the hooks * with WordPress. * * @since 1.0.0 * @access private */ private function load_dependencies() { /** * The class responsible for orchestrating the actions and filters of the * core plugin. */ require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/<API key>.php'; /** * The class responsible for defining <API key> functionality * of the plugin. */ require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/<API key>.php'; /** * The class responsible for defining all actions that occur in the admin area. */ require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/<API key>.php'; /** * The class responsible for PR options page in the admin area. */ require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/<API key>.php'; /** * The class responsible for defining all actions that occur in the public-facing * side of the site. */ require_once plugin_dir_path( dirname( __FILE__ ) ) . 'public/<API key>.php'; $this->loader = new <API key>(); // Required files for registering the post type and taxonomies. require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/<API key>.php'; require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/<API key>.php'; // Instantiate registration class, so we can add it as a dependency to main plugin class. $<API key> = new <API key>; // Register callback that is fired when the plugin is activated. <API key>( __FILE__, array( $post_type, 'activate' ) ); // Initialize registrations for post-activation requests. $<API key>->init(); // Initialize metaboxes //$post_type_metaboxes = new PR_Meta_Box; //$post_type_metaboxes->init(); } /** * Define the locale for this plugin for <API key>. * * Uses the <API key> class in order to set the domain and to register the hook * with WordPress. * * @since 1.0.0 * @access private */ private function set_locale() { $plugin_i18n = new <API key>(); $this->loader->add_action( 'plugins_loaded', $plugin_i18n, '<API key>' ); } /** * Register all of the hooks related to the admin area functionality * of the plugin. * * @since 1.0.0 * @access private */ private function define_admin_hooks() { $plugin_admin = new <API key>( $this->get_plugin_name(), $this->get_version() ); $this->loader->add_action( '<API key>', $plugin_admin, 'enqueue_styles' ); $this->loader->add_action( '<API key>', $plugin_admin, 'enqueue_scripts' ); } /** * Register all of the hooks related to the public-facing functionality * of the plugin. * * @since 1.0.0 * @access private */ private function define_public_hooks() { $plugin_public = new <API key>( $this->get_plugin_name(), $this->get_version() ); $this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_styles' ); $this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_scripts' ); } /** * Run the loader to execute all of the hooks with WordPress. * * @since 1.0.0 */ public function run() { $this->loader->run(); } /** * The name of the plugin used to uniquely identify it within the context of * WordPress and to define <API key> functionality. * * @since 1.0.0 * @return string The name of the plugin. */ public function get_plugin_name() { return $this->plugin_name; } /** * The reference to the class that orchestrates the hooks with the plugin. * * @since 1.0.0 * @return <API key> Orchestrates the hooks of the plugin. */ public function get_loader() { return $this->loader; } /** * Retrieve the version number of the plugin. * * @since 1.0.0 * @return string The version number of the plugin. */ public function get_version() { return $this->version; } }
drop table if exists users; create table users ( id serial primary key, username varchar(128) not null, password varchar(128) not null, favorites text not null, minute integer, disabled boolean not null); drop table if exists messages; create table messages ( id serial primary key, user_id integer references users (id), message text not null, created_at timestamp not null);
#ifndef <API key> #define <API key> // LOVE #include "common/config.h" #include "Joystick.h" #include "common/runtime.h" namespace love { namespace joystick { Joystick *luax_checkjoystick(lua_State *L, int idx); int <API key>(lua_State *L); int w_Joystick_getName(lua_State *L); int w_Joystick_getID(lua_State *L); int w_Joystick_getGUID(lua_State *L); int <API key>(lua_State *L); int <API key>(lua_State *L); int <API key>(lua_State *L); int w_Joystick_getAxis(lua_State *L); int w_Joystick_getAxes(lua_State *L); int w_Joystick_getHat(lua_State *L); int w_Joystick_isDown(lua_State *L); int <API key>(lua_State *L); int <API key>(lua_State *L); int <API key>(lua_State *L); int <API key>(lua_State *L); int <API key>(lua_State *L); int <API key>(lua_State *L); extern "C" int luaopen_joystick(lua_State *L); } // joystick } // love #endif // <API key>
#ifndef _ETH2_PDML_H #define _ETH2_PDML_H #include "pdmlprotocol.h" class PdmlEthProtocol : public PdmlProtocol { public: static PdmlProtocol* createInstance(); virtual void unknownFieldHandler(QString name, int pos, int size, const <API key> &attributes, OstProto::Protocol *pbProto, OstProto::Stream *stream); virtual void postProtocolHandler(OstProto::Protocol *pbProto, OstProto::Stream *stream); protected: PdmlEthProtocol(); }; #endif
/* * Compatibility support to bridge old pe_arm_xxx api and new * AWESOME SOC DISPATCH STUFF. */ #include <mach/mach_types.h> #include <pexpert/pexpert.h> #include <pexpert/arm/protos.h> #include <pexpert/arm/boot.h> #include <machine/machine_routines.h> #include <kern/debug.h> /** * <API key> * * Initialize the SoC dependent interrrupt controller. */ uint32_t <API key>(__unused void *args) { if (gPESocDispatch.interrupt_init == NULL) panic("gPESocDispatch.interrupt_init was null, did you forget to set up the table?"); gPESocDispatch.interrupt_init(); return 0; } /** * <API key> * * Initialize the SoC dependent timebase. */ uint32_t <API key>(__unused void *args) { if (gPESocDispatch.timebase_init == NULL) panic("gPESocDispatch.timebase_init was null, did you forget to set up the table?"); gPESocDispatch.timebase_init(); return 0; } /** * <API key> * * Dispatch IRQ requests to the SoC specific handler. */ boolean_t <API key>(void *context) { if (gPESocDispatch.handle_interrupt == NULL) panic("gPESocDispatch.handle_interrupt was null, did you forget to set up the table?"); gPESocDispatch.handle_interrupt(context); return TRUE; } /** * pe_arm_get_timebase * * Get current system timebase from the SoC handler. */ uint64_t pe_arm_get_timebase(__unused void *args) { if (gPESocDispatch.get_timebase == NULL) panic("gPESocDispatch.get_timebase was null, did you forget to set up the table?"); return gPESocDispatch.get_timebase(); } /** * <API key> * * Set platform timer enabled status. */ void <API key>(boolean_t enable) { if (gPESocDispatch.timer_enabled == NULL) panic("gPESocDispatch.timer_enabled was null, did you forget to set up the table?"); gPESocDispatch.timer_enabled(enable); } /* * iOS like functionality. */ uint32_t debug_enabled = 1; uint32_t <API key>(uint32_t * pe_debug) { if (pe_debug) { if (debug_enabled) *pe_debug = 1; else *pe_debug = 0; } return debug_enabled; } uint32_t <API key>(void) { return 0; }
<?php namespace Ajgl\Csv\Rfc\Tests\Spl; use Ajgl\Csv\Rfc\Spl\SplFileObject; class SplFileObjectTest extends <API key> { protected function buildFileObject() { return new SplFileObject('php://temp', 'w+'); } }
package com.example.habitup.View; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.example.habitup.Model.Attributes; import com.example.habitup.Model.Habit; import com.example.habitup.R; import java.util.ArrayList; /** * This is the adapter for creating the habit list, which displays the habit name, and * it's schedule. * * @author Shari Barboza */ public class HabitListAdapter extends ArrayAdapter<Habit> { // The habits array private ArrayList<Habit> habits; public HabitListAdapter(Context context, int resource, ArrayList<Habit> habits) { super(context, resource, habits); this.habits = habits; } @Override public View getView(int position, View view, ViewGroup viewGroup) { View v = view; // Inflate a new view if (v == null) { LayoutInflater inflater = LayoutInflater.from(getContext()); v = inflater.inflate(R.layout.habit_list_item, null); } // Get the habit Habit habit = habits.get(position); String attributeName = habit.getHabitAttribute(); String attributeColour = Attributes.getColour(attributeName); // Set the name of the habit TextView habitNameView = v.findViewById(R.id.habit_name); habitNameView.setText(habit.getHabitName()); habitNameView.setTextColor(Color.parseColor(attributeColour)); // Get habit schedule boolean[] schedule = habit.getHabitSchedule(); View monView = v.findViewById(R.id.mon_box); View tueView = v.findViewById(R.id.tue_box); View wedView = v.findViewById(R.id.wed_box); View thuView = v.findViewById(R.id.thu_box); View friView = v.findViewById(R.id.fri_box); View satView = v.findViewById(R.id.sat_box); View sunView = v.findViewById(R.id.sun_box); View[] textViews = {monView, tueView, wedView, thuView, friView, satView, sunView}; // Display days of the month for the habit's schedule for (int i = 1; i < schedule.length; i++) { if (schedule[i]) { textViews[i-1].setVisibility(View.VISIBLE); } else { textViews[i-1].setVisibility(View.GONE); } } return v; } }
#include <stdio.h> #include <string.h> #include "stdbool.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" #include "esp_log.h" #include "bt.h" #define GATTS_TAG "MAIN" #define <API key> (4) /* HCI Command opcode group field(OGF) */ #define <API key> (0x03 << 10) /* 0x0C00 */ #define HCI_GRP_BLE_CMDS (0x08 << 10) #define HCI_RESET (0x0003 | <API key>) #define <API key> (0x000A | HCI_GRP_BLE_CMDS) #define <API key> (0x0006 | HCI_GRP_BLE_CMDS) #define <API key> (0x0008 | HCI_GRP_BLE_CMDS) #define <API key> (1) #define <API key> (15) #define <API key> (31) #define BD_ADDR_LEN (6) /* Device address length */ typedef uint8_t bd_addr_t[BD_ADDR_LEN]; /* Device address */ #define UINT16_TO_STREAM(p, u16) {*(p)++ = (uint8_t)(u16); *(p)++ = (uint8_t)((u16) >> 8);} #define UINT8_TO_STREAM(p, u8) {*(p)++ = (uint8_t)(u8);} #define BDADDR_TO_STREAM(p, a) {int ijk; for (ijk = 0; ijk < BD_ADDR_LEN; ijk++) *(p)++ = (uint8_t) a[BD_ADDR_LEN - 1 - ijk];} #define ARRAY_TO_STREAM(p, a, len) {int ijk; for (ijk = 0; ijk < len; ijk++) *(p)++ = (uint8_t) a[ijk];} enum { H4_TYPE_COMMAND = 1, H4_TYPE_ACL = 2, H4_TYPE_SCO = 3, H4_TYPE_EVENT = 4 }; static uint8_t hci_cmd_buf[128]; /* * @brief: BT controller callback function, used to notify the upper layer that * controller is ready to receive command */ static void <API key>(void) { printf("controller rcv pkt ready\n"); } /* * @brief: BT controller callback function, to transfer data packet to upper * controller is ready to receive command */ static int host_rcv_pkt(uint8_t *data, uint16_t len) { printf("host rcv pkt: "); for (uint16_t i=0; i<len; i++) printf("%02x", data[i]); printf("\n"); return 0; } static <API key> vhci_host_cb = { <API key>, host_rcv_pkt }; static uint16_t make_cmd_reset(uint8_t *buf) { UINT8_TO_STREAM (buf, H4_TYPE_COMMAND); UINT16_TO_STREAM (buf, HCI_RESET); UINT8_TO_STREAM (buf, 0); return <API key>; } static uint16_t <API key> (uint8_t *buf, uint8_t adv_enable) { UINT8_TO_STREAM (buf, H4_TYPE_COMMAND); UINT16_TO_STREAM (buf, <API key>); UINT8_TO_STREAM (buf, <API key>); UINT8_TO_STREAM (buf, adv_enable); return <API key> + <API key>; } static uint16_t <API key> (uint8_t *buf, uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type, uint8_t addr_type_own, uint8_t addr_type_dir, bd_addr_t direct_bda, uint8_t channel_map, uint8_t adv_filter_policy) { UINT8_TO_STREAM (buf, H4_TYPE_COMMAND); UINT16_TO_STREAM (buf, <API key>); UINT8_TO_STREAM (buf, <API key> ); UINT16_TO_STREAM (buf, adv_int_min); UINT16_TO_STREAM (buf, adv_int_max); UINT8_TO_STREAM (buf, adv_type); UINT8_TO_STREAM (buf, addr_type_own); UINT8_TO_STREAM (buf, addr_type_dir); BDADDR_TO_STREAM (buf, direct_bda); UINT8_TO_STREAM (buf, channel_map); UINT8_TO_STREAM (buf, adv_filter_policy); return <API key> + <API key>; } static uint16_t <API key>(uint8_t *buf, uint8_t data_len, uint8_t *p_data) { UINT8_TO_STREAM (buf, H4_TYPE_COMMAND); UINT16_TO_STREAM (buf, <API key>); UINT8_TO_STREAM (buf, <API key> + 1); memset(buf, 0, <API key>); if (p_data != NULL && data_len > 0) { if (data_len > <API key>) { data_len = <API key>; } UINT8_TO_STREAM (buf, data_len); ARRAY_TO_STREAM (buf, p_data, data_len); } return <API key> + <API key> + 1; } static void hci_cmd_send_reset(void) { uint16_t sz = make_cmd_reset (hci_cmd_buf); <API key>(hci_cmd_buf, sz); } static void <API key>(void) { uint16_t sz = <API key> (hci_cmd_buf, 1); <API key>(hci_cmd_buf, sz); } static void <API key>(void) { uint16_t adv_intv_min = 256; // 160ms uint16_t adv_intv_max = 256; // 160ms uint8_t adv_type = 0; // connectable undirected advertising (ADV_IND) uint8_t own_addr_type = 0; // Public Device Address uint8_t peer_addr_type = 0; // Public Device Address uint8_t peer_addr[6] = {0x80, 0x81, 0x82, 0x83, 0x84, 0x85}; uint8_t adv_chn_map = 0x07; // 37, 38, 39 uint8_t adv_filter_policy = 0; // Process All Conn and Scan uint16_t sz = <API key>(hci_cmd_buf, adv_intv_min, adv_intv_max, adv_type, own_addr_type, peer_addr_type, peer_addr, adv_chn_map, adv_filter_policy); <API key>(hci_cmd_buf, sz); } static void <API key>(void) { uint8_t adv_data[31]; uint8_t adv_data_len; adv_data[0] = 2; // Len adv_data[1] = 0x01; // Type Flags adv_data[2] = 0x06; // GENERAL_DISC_MODE 0x02 | <API key> 0x04 adv_data[3] = 3; // Len adv_data[4] = 0x03; // Type 16-Bit UUID adv_data[5] = 0xAA; // Eddystone UUID 2 -> 0xFEAA LSB adv_data[6] = 0xFE; // Eddystone UUID 1 MSB adv_data[7] = 19; // Length of Beacon Data adv_data[8] = 0x16; // Type Service Data adv_data[9] = 0xAA; // Eddystone UUID 2 -> 0xFEAA LSB adv_data[10] = 0xFE; // Eddystone UUID 1 MSB adv_data[11] = 0x10; // Eddystone Frame Type adv_data[12] = 0x20; // Beacons TX power at 0m adv_data[13] = 0x03; adv_data[14] = 0x67; // URL add 1 'g' adv_data[15] = 0x6F; // URL add 2 'o' adv_data[16] = 0x6F; // URL add 3 'o' adv_data[17] = 0x2E; // URL add 4 '.' adv_data[18] = 0x67; // URL add 5 'g' adv_data[19] = 0x6C; // URL add 6 'l' adv_data[20] = 0x2F; // URL add 7 '/' adv_data[21] = 0x32; // URL add 8 '2' adv_data[22] = 0x79; // URL add 9 'y' adv_data[23] = 0x43; // URL add 10 'C' adv_data[24] = 0x36; // URL add 11 '6' adv_data[25] = 0x4B; // URL add 12 'K' adv_data[26] = 0x58; // URL add 13 'X' adv_data_len = 27; printf("Eddystone adv_data [%d]=",adv_data_len); for (int i=0; i<adv_data_len; i++) { printf("%02x",adv_data[i]); } printf("\n"); uint16_t sz = <API key>(hci_cmd_buf, adv_data_len, (uint8_t *)adv_data); <API key>(hci_cmd_buf, sz); } /* * @brief: send HCI commands to perform BLE advertising; */ void bleAdvtTask(void *pvParameters) { int cmd_cnt = 0; bool send_avail = false; <API key>(&vhci_host_cb); printf("BLE advt task start\n"); while (1) { vTaskDelay(5000 / portTICK_PERIOD_MS); send_avail = <API key>(); if (send_avail) { switch (cmd_cnt) { case 0: hci_cmd_send_reset(); ++cmd_cnt; break; case 1: <API key>(); ++cmd_cnt; break; case 2: <API key>(); ++cmd_cnt; break; case 3: <API key>(); ++cmd_cnt; break; } } printf("BLE Advertise, flag_send_avail: %d, cmd_sent: %d\n", send_avail, cmd_cnt); } } int app_main() { esp_err_t ret; <API key> bt_cfg = <API key>(); ret = <API key>(&bt_cfg); if (ret) { ESP_LOGE(GATTS_TAG, "%s initialize controller failed\n", __func__); return 1; } ret = <API key>(ESP_BT_MODE_BTDM); if (ret) { ESP_LOGE(GATTS_TAG, "%s enable controller failed\n", __func__); return 1; } <API key>(&bleAdvtTask, "bleAdvtTask", 2048, NULL, 5, NULL, 0); return 0; }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="ro"> <head> <!-- Generated by javadoc (version 1.7.0_80) on Mon Jun 20 18:37:10 EEST 2016 --> <title>JRPropertiesUtil.PropertySuffix (JasperReports 6.3.0 API)</title> <meta name="date" content="2016-06-20"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="JRPropertiesUtil.PropertySuffix (JasperReports 6.3.0 API)"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/JRPropertiesUtil.PropertySuffix.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.html" title="class in net.sf.jasperreports.engine"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../net/sf/jasperreports/engine/<API key>.html" title="interface in net.sf.jasperreports.engine"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?net/sf/jasperreports/engine/JRPropertiesUtil.PropertySuffix.html" target="_top">Frames</a></li> <li><a href="JRPropertiesUtil.PropertySuffix.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <div class="subTitle">net.sf.jasperreports.engine</div> <h2 title="Class JRPropertiesUtil.PropertySuffix" class="title">Class JRPropertiesUtil.PropertySuffix</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>net.sf.jasperreports.engine.JRPropertiesUtil.PropertySuffix</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.html" title="class in net.sf.jasperreports.engine">JRPropertiesUtil</a></dd> </dl> <hr> <br> <pre>public static class <span class="strong">JRPropertiesUtil.PropertySuffix</span> extends java.lang.Object</pre> <div class="block">Class used by <a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.html#getProperties(java.lang.String)"><code>JRPropertiesUtil.getProperties(String)</code></a>.</div> <dl><dt><span class="strong">Author:</span></dt> <dd>Lucian Chirita</dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="field_summary"> </a> <h3>Field Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>protected java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.PropertySuffix.html#key">key</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.PropertySuffix.html#suffix">suffix</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.PropertySuffix.html#value">value</a></strong></code>&nbsp;</td> </tr> </table> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.PropertySuffix.html#JRPropertiesUtil.PropertySuffix(java.lang.String,%20java.lang.String,%20java.lang.String)">JRPropertiesUtil.PropertySuffix</a></strong>(java.lang.String&nbsp;key, java.lang.String&nbsp;suffix, java.lang.String&nbsp;value)</code>&nbsp;</td> </tr> </table> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="method_summary"> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.PropertySuffix.html#getKey()">getKey</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.PropertySuffix.html#getSuffix()">getSuffix</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.PropertySuffix.html#getValue()">getValue</a></strong>()</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="<API key>.lang.Object"> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="field_detail"> </a> <h3>Field Detail</h3> <a name="key"> </a> <ul class="blockList"> <li class="blockList"> <h4>key</h4> <pre>protected final&nbsp;java.lang.String key</pre> </li> </ul> <a name="suffix"> </a> <ul class="blockList"> <li class="blockList"> <h4>suffix</h4> <pre>protected final&nbsp;java.lang.String suffix</pre> </li> </ul> <a name="value"> </a> <ul class="blockListLast"> <li class="blockList"> <h4>value</h4> <pre>protected final&nbsp;java.lang.String value</pre> </li> </ul> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> </a> <h3>Constructor Detail</h3> <a name="JRPropertiesUtil.PropertySuffix(java.lang.String, java.lang.String, java.lang.String)"> </a> <ul class="blockListLast"> <li class="blockList"> <h4>JRPropertiesUtil.PropertySuffix</h4> <pre>public&nbsp;JRPropertiesUtil.PropertySuffix(java.lang.String&nbsp;key, java.lang.String&nbsp;suffix, java.lang.String&nbsp;value)</pre> </li> </ul> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="method_detail"> </a> <h3>Method Detail</h3> <a name="getKey()"> </a> <ul class="blockList"> <li class="blockList"> <h4>getKey</h4> <pre>public&nbsp;java.lang.String&nbsp;getKey()</pre> </li> </ul> <a name="getSuffix()"> </a> <ul class="blockList"> <li class="blockList"> <h4>getSuffix</h4> <pre>public&nbsp;java.lang.String&nbsp;getSuffix()</pre> </li> </ul> <a name="getValue()"> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getValue</h4> <pre>public&nbsp;java.lang.String&nbsp;getValue()</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/JRPropertiesUtil.PropertySuffix.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.html" title="class in net.sf.jasperreports.engine"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../net/sf/jasperreports/engine/<API key>.html" title="interface in net.sf.jasperreports.engine"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?net/sf/jasperreports/engine/JRPropertiesUtil.PropertySuffix.html" target="_top">Frames</a></li> <li><a href="JRPropertiesUtil.PropertySuffix.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> </a></div> <p class="legalCopy"><small> <span style="font-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:8pt;font-style:normal;color: </small></p> </body> </html>
if(NOT DEFINED IMP_TIMEOUT_FACTOR) if(${CMAKE_BUILD_TYPE} MATCHES "Debug") set(IMP_TIMEOUT_FACTOR 3 CACHE INT "A scaling factor for test timeouts") else() set(IMP_TIMEOUT_FACTOR 1 CACHE INT "A scaling factor for test timeouts") endif() endif() set(IMP_CHEAP_TIMEOUT 5 CACHE INT "Timeout for cheap tests") set(IMP_MEDIUM_TIMEOUT 15 CACHE INT "Timeout for medium tests") set(<API key> 120 CACHE INT "Timeout for expensive tests") set(IMP_CHEAP_COST 1 CACHE INTERNAL "") set(IMP_MEDIUM_COST 2 CACHE INTERNAL "") set(IMP_EXPENSIVE_COST 3 CACHE INTERNAL "") function(<API key> modulename length type) set(modulename ${ARGV0}) set(length ${ARGV1}) set(ttype ${ARGV2}) list(REMOVE_AT ARGV 0) list(REMOVE_AT ARGV 0) list(REMOVE_AT ARGV 0) math(EXPR timeout "${IMP_TIMEOUT_FACTOR} * ${IMP_${length}_TIMEOUT}") foreach (test ${ARGV}) <API key>(path ${test} ABSOLUTE) <API key>(name ${test} NAME) add_test("${modulename}-${name}" ${IMP_TEST_SETUP} python ${path} ${IMP_TEST_ARGUMENTS}) <API key>("${modulename}-${name}" PROPERTIES LABELS "${modulename}-${ttype}-python-${length}") <API key>("${modulename}-${name}" PROPERTIES TIMEOUT ${timeout}) <API key>("${modulename}-${name}" PROPERTIES COST ${IMP_${length}_COST}) if(DEFINED <API key>) <API key>("${modulename}-${name}" PROPERTIES ${<API key>}) endif() endforeach(test) endfunction(<API key>) function(imp_add_cpp_tests modulename length output target_list type) set(modulename ${ARGV0}) set(length ${ARGV1}) set(output ${ARGV2}) set(target_list ${ARGV3}) set(ttype ${ARGV4}) list(REMOVE_AT ARGV 0) list(REMOVE_AT ARGV 0) list(REMOVE_AT ARGV 0) list(REMOVE_AT ARGV 0) list(REMOVE_AT ARGV 0) math(EXPR timeout "${IMP_TIMEOUT_FACTOR} * ${IMP_${length}_TIMEOUT}") foreach (test ${ARGV}) <API key>(name ${test} NAME) <API key>(name_we ${test} NAME_WE) add_executable("${modulename}-${name}" ${test}) <API key>("${modulename}-${name}" ${IMP_LINK_LIBRARIES}) <API key>("${modulename}-${name}" PROPERTIES <API key> "${output}" OUTPUT_NAME ${name_we}) set_property(TARGET "${modulename}-${name}" PROPERTY FOLDER "${modulename}") add_test("${modulename}-${name}" ${IMP_TEST_SETUP} ${output}/${name_we}${<API key>} ${IMP_TEST_ARGUMENTS}) <API key>("${modulename}-${name}" PROPERTIES LABELS "${modulename}-${ttype}-cpp-${length}") if(DEFINED <API key>) <API key>("${modulename}-${name}" PROPERTIES ${<API key>}) endif() <API key>("${modulename}-${name}" PROPERTIES TIMEOUT ${timeout}) <API key>("${modulename}-${name}" PROPERTIES COST ${IMP_${length}_COST}) set(${target_list} ${${target_list}} "${modulename}-${name}" CACHE INTERNAL "" FORCE) endforeach(test) endfunction(imp_add_cpp_tests) function(imp_add_tests modulename output target_list ttype) set(modulename ${ARGV0}) set(output ${ARGV1}) set(target_list ${ARGV2}) set(ttype ${ARGV3}) list(REMOVE_AT ARGV 0) list(REMOVE_AT ARGV 0) list(REMOVE_AT ARGV 0) list(REMOVE_AT ARGV 0) foreach (test ${ARGV}) <API key>(name ${test} NAME) <API key>(extension ${test} EXT) if("${extension}" MATCHES ".*py") set(type "py") else() set(type "cpp") endif() if(${name} MATCHES "^test_.*") set(cost "cheap") elseif(${name} MATCHES "^medium_test_.*") set(cost "medium") else() set(cost "expensive") endif() set(${type}_${cost} ${${type}_${cost}} ${test}) endforeach(test) <API key>(${modulename} "CHEAP" ${ttype} "${py_cheap}") <API key>(${modulename} "MEDIUM" ${ttype} "${py_medium}") <API key>(${modulename} "EXPENSIVE" ${ttype} "${py_expensive}") imp_add_cpp_tests(${modulename} "CHEAP" ${output} ${target_list} ${ttype} "${cpp_cheap}") imp_add_cpp_tests(${modulename} "MEDIUM" ${output} ${target_list} ${ttype} "${cpp_medium}") imp_add_cpp_tests(${modulename} "EXPENSIVE" ${output} ${target_list} ${ttype} "${cpp_expensive}") endfunction(imp_add_tests)
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_14) on Fri Jun 18 18:05:18 BST 2010 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class gr.forth.ics.graph.layout.forces2d.Forces.FRSpring (FlexiGraph Reference) </TITLE> <META NAME="date" CONTENT="2010-06-18"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class gr.forth.ics.graph.layout.forces2d.Forces.FRSpring (FlexiGraph Reference)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <A NAME="navbar_top"></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../gr/forth/ics/graph/layout/forces2d/Forces.FRSpring.html" title="class in gr.forth.ics.graph.layout.forces2d"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?gr/forth/ics/graph/layout/forces2d/\class-useForces.FRSpring.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Forces.FRSpring.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <HR> <CENTER> <H2> <B>Uses of Class<br>gr.forth.ics.graph.layout.forces2d.Forces.FRSpring</B></H2> </CENTER> No usage of gr.forth.ics.graph.layout.forces2d.Forces.FRSpring <P> <HR> <A NAME="navbar_bottom"></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="<API key>"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../gr/forth/ics/graph/layout/forces2d/Forces.FRSpring.html" title="class in gr.forth.ics.graph.layout.forces2d"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?gr/forth/ics/graph/layout/forces2d/\class-useForces.FRSpring.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Forces.FRSpring.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <HR> </BODY> </HTML>
#include "FilesystemCache.h" #include "Utility/Directory.h" #include "Utility/Endianness.h" using namespace std; using namespace Kompas::Utility; using namespace Kompas::Core; namespace Kompas { namespace Plugins { PLUGIN_REGISTER(Kompas::Plugins::FilesystemCache, "cz.mosra.Kompas.Core.AbstractCache/0.2") bool FilesystemCache::initializeCache(const std::string& url) { if(!_url.empty()) finalizeCache(); _url = url; string _file = Directory::join(_url, "index.kps"); if(Directory::fileExists(_file)) { ifstream file(_file, ios::binary); if(!file.good()) { Error() << "Cannot open cache index" << _file; return false; } char* buffer = new char[4]; /* Check file signature */ file.get(buffer, 4); if(string(buffer) != "CCH") { Error() << "Unknown Kompas cache signature" << buffer << "in" << _file; return false; } /* Check file version */ file.read(buffer, 1); if(buffer[0] != 1) { Error() << "Unsupported Kompas cache version" << buffer[0] << "in" << _file; return false; } /* Block size */ file.read(buffer, 4); _blockSize = Endianness::littleEndian(*reinterpret_cast<unsigned int*>(buffer)); /* Block count */ file.read(buffer, 4); _maxBlockCount = Endianness::littleEndian(*reinterpret_cast<unsigned int*>(buffer)); /* Count of all entries */ file.read(buffer, 4); unsigned int count = Endianness::littleEndian(*reinterpret_cast<unsigned int*>(buffer)); _entries.reserve(count); /* Populate the hash table with entries */ for(unsigned int i = 0; i != count; ++i) { if(!file.good()) { Error() << "Incomplete cache index" << _file; return false; } Entry* entry = new Entry(); /* SHA-1, file size, key size and usage */ file.read(reinterpret_cast<char*>(&entry->sha1), 20); file.read(buffer, 4); entry->size = Endianness::littleEndian(*reinterpret_cast<unsigned int*>(buffer)); file.read(buffer, 4); file.read(reinterpret_cast<char*>(&entry->usage), 1); /* Key */ unsigned int keySize = Endianness::littleEndian(*reinterpret_cast<unsigned int*>(buffer)); char* key = new char[keySize]; file.read(key, keySize); entry->key = string(key, keySize); delete[] key; /* Find hash of the file, if it already exists, increase usage count */ unordered_map<Sha1::Digest, unsigned int>::iterator it = _files.find(entry->sha1); if(it != _files.end()) ++it->second; /* If it doesn't exist, add the hash and increase used size */ else { _files.insert(pair<Sha1::Digest, unsigned int>(entry->sha1, 1u)); _usedBlockCount += blockCount(entry->size); } /* Add entry to entries table */ set(entry); } file.close(); } Debug() << "Initialized cache with block size" << _blockSize << "B," << _maxBlockCount << "blocks, containing" << _entries.size() << "entries of size" << _usedBlockCount << "blocks."; return true; } void FilesystemCache::finalizeCache() { if(_url.empty()) return; string _file = Directory::join(_url, "index.kps"); Directory::mkpath(Directory::path(_file)); ofstream file(_file.c_str(), ios::binary); if(!file.good()) { Error() << "Cannot write cache index" << _file; /* Avoid memory leak */ for(unordered_map<string, Entry*>::const_iterator it = _entries.begin(); it != _entries.end(); ++it) delete it->second; return; } unsigned int buffer; /* Write file signature, version, block size, block count and entry count */ file.write("CCH", 3); file.write("\1", 1); buffer = Endianness::littleEndian(static_cast<unsigned int>(_blockSize)); file.write(reinterpret_cast<const char*>(&buffer), 4); buffer = Endianness::littleEndian(static_cast<unsigned int>(_maxBlockCount)); file.write(reinterpret_cast<const char*>(&buffer), 4); buffer = Endianness::littleEndian(static_cast<unsigned int>(_entries.size())); file.write(reinterpret_cast<const char*>(&buffer), 4); /* Foreach all entries and write them to index */ if(_position != 0) { Entry* entry = _position; do { file.write(reinterpret_cast<const char*>(&entry->sha1), Sha1::DigestSize); buffer = Endianness::littleEndian<unsigned int>(entry->size); file.write(reinterpret_cast<const char*>(&buffer), 4); buffer = Endianness::littleEndian<unsigned int>(entry->key.size()); file.write(reinterpret_cast<const char*>(&buffer), 4); file.write(reinterpret_cast<const char*>(&entry->usage), 1); file.write(entry->key.c_str(), entry->key.size()); entry = entry->next; delete entry->previous; } while(entry != _position); } file.close(); _position = 0; _usedBlockCount = 0; _entries.clear(); _files.clear(); _url.clear(); } void FilesystemCache::setBlockSize(size_t size) { _blockSize = size; if(_entries.size() == 0) return; /* Rebuild files map */ _files.clear(); _usedBlockCount = 0; Entry* entry = _position; do { /* Find hash of the file, if it already exists, increase usage count */ unordered_map<Sha1::Digest, unsigned int>::iterator it = _files.find(entry->sha1); if(it != _files.end()) ++it->second; /* If it doesn't exist, add the hash and increase used size */ else { _files.insert(pair<Sha1::Digest, unsigned int>(entry->sha1, 1u)); _usedBlockCount += blockCount(entry->size); } entry = entry->next; } while(entry != _position); } void FilesystemCache::purge() { Debug() << "Cleaning cache."; for(unordered_map<Sha1::Digest, unsigned int>::iterator it = _files.begin(); it != _files.end(); ++it) Directory::rm(fileUrl(it->first)); _entries.clear(); _files.clear(); _position = 0; _usedBlockCount = 0; optimize(); } void FilesystemCache::optimize() { size_t orphanEntryCount = 0; size_t orphanFileCount = 0; size_t <API key> = 0; /* Remove entries without files */ if(_position != 0) { Entry* entry = _position; do { Entry* next = entry->next; /* If the file doesn't exist, remove entry */ if(!Directory::fileExists(fileUrl(entry->sha1))) { ++orphanEntryCount; remove(_entries.find(entry->key)); } entry = next; } while(_position == 0 || entry != _position); } /* Delete files which are not in the file table */ Directory d(_url, Directory::SkipDotAndDotDot); for(Directory::const_iterator it = d.begin(); it != d.end(); ++it) { if(*it == "index.kps") continue; /* Subdirectory, open it and look */ if(it->size() == 2) { string subdir = Directory::join(_url, *it); bool used = false; Directory sd(subdir, Directory::SkipDotAndDotDot); /* Remove unused files */ for(Directory::const_iterator sit = sd.begin(); sit != sd.end(); ++sit) { if(sit->size() == 38) { Sha1::Digest sha1 = Sha1::Digest::fromHexString(*it + *sit); if(sha1 != Sha1::Digest() && _files.find(sha1) == _files.end()) { if(Directory::rm(Directory::join(subdir, *sit))) ++orphanFileCount; continue; } } used = true; } if(!used) { if(Directory::rm(subdir)) ++<API key>; } } } Debug() << "Optimization removed" << orphanEntryCount << "orphan entries," << orphanFileCount << "orphan files and" << <API key> << "orphan directories."; } string FilesystemCache::get(const std::string& key) { ++_getCount; /* Find the key in entry table */ unordered_map<string, Entry*>::iterator eit = _entries.find(key); if(eit == _entries.end()) { Debug() << "Cache miss."; return string(); } Entry* entry = eit->second; /* Hash found, open the file */ string _file = fileUrl(entry->sha1); ifstream file(_file, ios::binary); if(!file.is_open()) { Error() << "Cannot open cached file" << _file; return string(); } /* Increase usage count and return file contents */ ++entry->usage; char* buffer = new char[entry->size]; file.read(buffer, entry->size); string s(buffer, entry->size); delete[] buffer; ++_hitCount; Debug() << "Retrieved entry" << entry->sha1.hexString() << "from cache. Hit rate:" << ((double) _hitCount)/_getCount; return s; } bool FilesystemCache::set(const std::string& key, const std::string& data) { if(_url.empty()) return false; /* Hash of the data */ Sha1::Digest sha1 = Sha1::digest(data); /* Add the entry */ Entry* entry = new Entry(); entry->key = key; entry->sha1 = sha1; entry->size = data.size(); entry->usage = 0; /* Find the hash in file table, if it exists, increase usage count */ unordered_map<Sha1::Digest, unsigned int>::iterator it = _files.find(sha1); if(it != _files.end()) { ++it->second; Debug() << "Entry" << sha1.hexString() << "already exists in cache."; /* If it doesn't exists, prepare free space and insert it */ } else { if(!reserveSpace(data.size())) return false; _usedBlockCount += blockCount(data.size()); _files.insert(pair<Sha1::Digest, unsigned int>(sha1, 1u)); if(!Directory::mkpath(filePath(sha1))) return false; string _file = fileUrl(sha1); ofstream file(_file, ios::binary); if(!file.good()) { Error() << "Cannot write cache file" << _file; return false; } file.write(data.c_str(), data.size()); file.close(); Debug() << "Added entry" << sha1.hexString() << "to cache."; } set(entry); return true; } void FilesystemCache::set(Entry* entry) { /* Find the key in entry table and remove it if it already exists */ unordered_map<string, Entry*>::iterator eit = _entries.find(entry->key); if(eit != _entries.end()) remove(eit); /* First item in the cache, initialize circular linked list */ if(_position == 0) { entry->next = entry; entry->previous = entry; _position = entry; } else { entry->next = _position; entry->previous = _position->previous; _position->previous->next = entry; _position->previous = entry; } _entries.insert(pair<string, Entry*>(entry->key, entry)); } void FilesystemCache::remove(const unordered_map<string, Entry*>::iterator& eit) { Entry* entry = eit->second; /* Disconnect the entry from circular linked list and remove it from the table */ if(entry->next == entry) _position = 0; else { entry->next->previous = entry->previous; entry->previous->next = entry->next; if(_position == entry) _position = _position->next; } _entries.erase(eit); /* Find the hash in file table, decrease usage count */ unordered_map<Sha1::Digest, unsigned int>::iterator it = _files.find(entry->sha1); /* If the file is not used anymore, remove it and decrease used size */ if(it != _files.end() && --it->second == 0) { Directory::rm(fileUrl(entry->sha1)); Directory::rm(filePath(entry->sha1)); _files.erase(it); _usedBlockCount -= blockCount(entry->size); } Debug() << "Removed entry" << entry->sha1.hexString() << "from cache, freed" << blockCount(entry->size) << "blocks."; delete entry; } bool FilesystemCache::reserveSpace(int required) { /* If we need more space than is available, don't do anything */ if(blockCount(required) > _maxBlockCount) { Error() << "Cannot reserve" << blockCount(required) << "blocks in cache of" << _maxBlockCount << "blocks."; return false; } /* Go through the cycle and exponentially decrease usage count */ while(_usedBlockCount+blockCount(required) > _maxBlockCount) { _position->usage >>= 1; /* If the usage decreased to zero, remove the entry */ if(_position->usage == 0) remove(_entries.find(_position->key)); /* Otherwise advance to next entry */ else _position = _position->next; } Debug() << "Reserved" << blockCount(required) << "blocks in cache of" << _maxBlockCount << "blocks."; return true; } string FilesystemCache::filePath(const Sha1::Digest& sha1) const { return Directory::join(_url, sha1.hexString().substr(0, 2)); } string FilesystemCache::fileUrl(const Sha1::Digest& sha1) const { return Directory::join(filePath(sha1), sha1.hexString().substr(2)); } }}
package org.elsys.InternetProgramming; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; public class ServerHandler { private Socket socket; public ServerHandler(String serverHost, int serverPort) { try { this.socket = new Socket(serverHost, serverPort); } catch (IOException e) { e.printStackTrace(); } } public void sendDateToServer(String date) { try { final OutputStream outputStream = this.socket.getOutputStream(); final PrintWriter out = new PrintWriter(outputStream); out.println(date); out.flush(); } catch (IOException e) { e.printStackTrace(); } } public int getCountFromServer() { try { final InputStream inputStream = this.socket.getInputStream(); final InputStreamReader inputStreamReader = new InputStreamReader(inputStream); final BufferedReader reader = new BufferedReader(inputStreamReader); final String line = reader.readLine(); final int result = Integer.parseInt(line); return result; } catch (IOException e) { e.printStackTrace(); } return 0; } public void closeConnection() { try { this.socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
import sys, math from test import goertzel import wave import pyaudio import Queue import numpy as np if len(sys.argv) < 2: print "Usage: %s <filename> " % sys.argv[0] sys.exit(1) filename = sys.argv[1] w = wave.open(filename) fs = w.getframerate() width = w.getsampwidth() chunkDuration = .2 #.2 second chunks chunk = int(chunkDuration*fs) window = np.blackman(chunk) p = pyaudio.PyAudio() stream = p.open(format = p.<API key>(w.getsampwidth()), channels = w.getnchannels(),rate = fs, output=True) #read .2 second chunk data = w.readframes(chunk) chunk_data = [] #find the frequencies of each chunk print "Running calculations on wav file" num = 0 while data != '': print "Calculating Chunk " + str(num) stream.write(data) indata = np.array(wave.struct.unpack("%dh"%(len(data)/width),\ data)) freqs , results = goertzel(indata,fs, (1036,1058), (1567,1569), (2082,2104)) chunk_data.append((freqs,results)) data = w.readframes(chunk) num+=.2 stream.close() p.terminate() #finished getting data from chunks, now to parse the data hi = [] lo = [] mid = [] #average first second of audio to get frequency baselines for i in range (5): a = chunk_data[i][0] b = chunk_data[i][1] for j in range(len(a)): if a[j] > 1700: hi.append(b[j]) elif a[j] < 1300: lo.append(b[j]) else: mid.append(b[j]) hi_average = sum(hi)/float(len(hi)) lo_average = sum(lo)/float(len(lo)) mid_average = sum(mid)/float(len(mid)) """ Determine the frequency in each .2 second chunk that has the highest amplitude increase from its average, then determine the frequency of that second of data by the median frequency of its 5 chunks """ #looks for start signal in last 3 seconds of audio def signal_found(arr): lst = arr[-15:] first = 0 second = 0 third = 0 for i in range(0,5): if lst[i]=="mid": first += 1 for i in range(5,10): if lst[i]=="mid": second += 1 for i in range(10,15): if lst[i]=="mid": third += 1 if first >= 5 and second >= 5 and third >= 5: return True else: return False #gets freq of 1 second of audio def get_freq(arr): lo_count = 0 hi_count = 0 mid_count = 0 for i in arr: if i=="lo": lo_count+=1 if i=="hi": hi_count+=1 if i=="mid": mid_count+=1 if mid_count > hi_count and mid_count > lo_count: return 2 if lo_count>hi_count: return 0 else: return 1 start = False freq_list = [] offset = 0 bits = [] for i in range(5,len(chunk_data)): a = chunk_data[i][0] b = chunk_data[i][1] hi_amp = [] lo_amp = [] mid_amp = [] #get averages for each freq for j in range(len(a)): if a[j] > 1700: hi_amp.append(b[j]) elif a[j] < 1300: lo_amp.append(b[j]) else: mid_amp.append(b[j]) hi_av = sum(hi_amp)/float(len(hi_amp)) lo_av = sum(lo_amp)/float(len(lo_amp)) mid_av = sum(mid_amp)/float(len(mid_amp)) #get freq of this chunk diff = [lo_av-lo_average,mid_av-mid_average,hi_av-hi_average] index = diff.index(max(diff)) if(index==0): freq_list.append("lo") if(index==1): freq_list.append("mid") if(index==2): freq_list.append("hi") print(freq_list[len(freq_list)-1]) if len(freq_list) > 5: if start: if len(freq_list)%5 == offset: bit = get_freq(freq_list[-5:]) if bit != 2: bits.append(bit) else: print "Stop Signal Detected" break elif len(freq_list) >= 15: if signal_found(freq_list): print "signal found" start = True offset = len(freq_list)%5 print bits
// Decompiled with JetBrains decompiler // Type: <API key> // Assembly: Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // MVID: <API key> // Assembly location: C:\Users\CGA Computer\Desktop\LEGO Universe Stuff\LOCO Server\Unity Web Player Extractor\Saved Files\LOCO Server.unity3d_unpacked\Assembly-CSharp.dll using System.Collections; using System.Diagnostics; using UnityEngine; public class <API key> : MonoBehaviour { public WBSpriteText LoadingString; public <API key>() { base.\u002Ector(); } [DebuggerHidden] private IEnumerator Start() { // ISSUE: object of a compiler-generated type is created return (IEnumerator) new <API key>.\u003CStart\u003Ec__Iterator95() { \u003C\u003Ef__this = this }; } }
using System; using System.Collections.Generic; using System.Linq; using Minedrink_UWP.View; using Windows.ApplicationModel; using Windows.Foundation; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Automation; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Navigation; using System.Diagnostics; using Windows.ApplicationModel.Core; using Windows.Networking; using Minedrink_UWP.Model; using Windows.Networking.Connectivity; using Windows.Networking.Sockets; using System.IO; using Windows.Storage.Streams; using System.Threading.Tasks; namespace Minedrink_UWP { <summary> Frame </summary> public sealed partial class MainPage : Page { public Rect <API key> { get; private set; } private bool isPaddingAdd = false; private List<NavMenuItem> navlist = new List<NavMenuItem>( new[] { new NavMenuItem() { Symbol = Symbol.Globe, Label = "", DestPage = typeof(OverviewPage), }, new NavMenuItem() { Symbol = Symbol.Admin, Label = "", DestPage = typeof(ConfigPage), }, new NavMenuItem() { Symbol = Symbol.PhoneBook, Label = "", DestPage = typeof(MonitorPage), } }); public static MainPage Current = null; public MainPage() { this.InitializeComponent(); this.Loaded += (sender, args) => { Current = this; this.<API key>(); var titleBar = Windows.ApplicationModel.Core.CoreApplication.GetCurrentView().TitleBar; titleBar.IsVisibleChanged += <API key>; }; this.RootSplitView.<API key>(SplitView.DisplayModeProperty, (s, a) => { //SplitViewTogglePaneButton this.<API key>(); }); <API key>.GetForCurrentView().BackRequested += <API key>; <API key>.GetForCurrentView().<API key> = <API key>.Visible; NavMenuList.ItemsSource = navlist; } private void <API key>(object sender, <API key> e) { bool handle = e.Handled; this.BackRequested(ref handle); e.Handled = handle; } <summary> </summary> <param name="handle"></param> private void BackRequested(ref bool handle) { if (this.AppFrame == null) { return; } if (this.AppFrame.CanGoBack && !handle) { handle = true; this.AppFrame.GoBack(); } } <summary> Loading Apptop padding Invoked when window title bar visibility changes, such as after loading or in tablet mode Ensures correct padding at window top, between title bar and app content </summary> <param name="sender"></param> <param name="args"></param> private void <API key>(Windows.ApplicationModel.Core.<API key> sender, object args) { if (!this.isPaddingAdd && sender.IsVisible) { //Padding double extraPadding = (Double)App.Current.Resources["<API key>"]; this.isPaddingAdd = true; Thickness margin = NavMenuList.Margin; NavMenuList.Margin = new Thickness(margin.Left, margin.Top + extraPadding, margin.Right, margin.Bottom); margin = AppFrame.Margin; //AppFrame.Margin = new Thickness(margin.Left, margin.Top + extraPadding, margin.Right, margin.Bottom); margin = TogglePaneButton.Margin; TogglePaneButton.Margin = new Thickness(margin.Left, margin.Top + extraPadding, margin.Right, margin.Bottom); } } <summary> Check for the conditions where the navigation pane does not occupy the space under the floating hamburger button and trigger the event. </summary> private void <API key>() { if (RootSplitView.DisplayMode == <API key>.Inline || RootSplitView.DisplayMode == <API key>.Overlay) { var transform = this.TogglePaneButton.TransformToVisual(this); var rect = transform.TransformBounds(new Rect(0, 0, this.TogglePaneButton.ActualWidth, this.TogglePaneButton.ActualHeight)); this.<API key> = rect; } else { this.<API key> = new Rect(); } var handler = this.<API key>; if (handler != null) { // handler(this, this.<API key>); handler.DynamicInvoke(this, this.<API key>); } } //private void MainPage_Loaded(object sender, RoutedEventArgs e) // throw new <API key>(); public Frame AppFrame { get { return this.frame; } } <summary> </summary> <param name="sender"></param> <param name="e"></param> private void MainPage_KeyDown(object sender, KeyRoutedEventArgs e) { <API key> direction = <API key>.None; switch (e.Key) { case Windows.System.VirtualKey.Left: case Windows.System.VirtualKey.GamepadDPadLeft: case Windows.System.VirtualKey.<API key>: case Windows.System.VirtualKey.NavigationLeft: direction = <API key>.Left; break; case Windows.System.VirtualKey.Right: case Windows.System.VirtualKey.GamepadDPadRight: case Windows.System.VirtualKey.<API key>: case Windows.System.VirtualKey.NavigationRight: direction = <API key>.Right; break; case Windows.System.VirtualKey.Up: case Windows.System.VirtualKey.GamepadDPadUp: case Windows.System.VirtualKey.<API key>: case Windows.System.VirtualKey.NavigationUp: direction = <API key>.Up; break; case Windows.System.VirtualKey.Down: case Windows.System.VirtualKey.GamepadDPadDown: case Windows.System.VirtualKey.<API key>: case Windows.System.VirtualKey.NavigationDown: direction = <API key>.Down; break; } if (direction != <API key>.None) { var contorl = FocusManager.<API key>(direction) as Control; if (contorl != null) { contorl.Focus(FocusState.Keyboard); e.Handled = true; } } } <summary> Hides divider when nav pane is closed. </summary> <param name="sender"></param> <param name="args"></param> private void <API key>(SplitView sender, object args) { NavPaneDivider.Visibility = Visibility.Collapsed; // Prevent focus from moving to elements when they're not visible on screen <API key>.IsTabStop = false; <API key>.IsTabStop = false; } <summary> AutomationProperties.Name Enable accessibility on each nav menu item by setting the <API key>.Name on each container using the associated Label of each item. </summary> <param name="sender"></param> <param name="args"></param> private void <API key>(ListViewBase sender, <API key> args) { if (!args.InRecycleQueue && args.Item != null && args.Item is NavMenuItem) { args.ItemContainer.SetValue(<API key>.NameProperty, ((NavMenuItem)args.Item).Label); } else { args.ItemContainer.ClearValue(<API key>.NameProperty); } } <summary> </summary> <param name="sender"></param> <param name="e"></param> private void <API key>(object sender, ListViewItem e) { foreach (var i in navlist) { i.IsSelected = false; } var item = (NavMenuItem)((NavMenuListView)sender).ItemFromContainer(e); if (item != null) { item.IsSelected = true; if (item.DestPage != null && item.DestPage != this.AppFrame.<API key>) { this.AppFrame.Navigate(item.DestPage, item.Arguments); } } } public void NavMenuList_Init() { navlist.First().IsSelected = true; } <summary> Ensures the nav menu reflects reality when navigation is triggered outside of the nav menu buttons. </summary> <param name="sender"></param> <param name="e"></param> private void frame_Navigating(object sender, <API key> e) { if (e.NavigationMode == NavigationMode.Back) { var item = (from p in this.navlist where p.DestPage == e.SourcePageType select p).SingleOrDefault(); if (item == null && this.AppFrame.BackStackDepth > 0) { // BackStack // In cases where a page drills into sub-pages then we'll highlight the most recent // navigation menu item that appears in the BackStack foreach (var entry in this.AppFrame.BackStack.Reverse()) { item = (from p in this.navlist where p.DestPage == entry.SourcePageType select p).SingleOrDefault(); if (item != null) { break; } } } foreach (var i in navlist) { i.IsSelected = false; } if (item != null) { item.IsSelected = true; } var container = (ListViewItem)NavMenuList.ContainerFromItem(item); //While updating the selection state of the item prevent it from taking keyboard focus. //If a user is invoking the back button via the keyboard causing the selected nav menu item to change then focus will remain on the back button. if (container != null) { container.IsTabStop = false; } NavMenuList.SetSelectedItem(container); if (container != null) { container.IsTabStop = true; } } } private void <API key>(object sender, RoutedEventArgs e) { this.<API key>(); } private void <API key>(object sender, RoutedEventArgs e) { NavPaneDivider.Visibility = Visibility.Visible; this.<API key>(); <API key>.IsTabStop = true; <API key>.IsTabStop = true; } //private async void StartListener() // if (CoreApplication.Properties.ContainsKey("listener")) // Debug.WriteLine(""); // return; // CoreApplication.Properties.Remove("serverAddress"); // CoreApplication.Properties.Remove("adapter"); // //LocalHostItem selectedLocalHost = null; // //selectedLocalHost = new LocalHostItem(NetworkInformation.GetHostNames().First()); // //Debug.WriteLine(":" + selectedLocalHost); // //CoreApplication.Properties.Add("serverAddress", selectedLocalHost.LocalHost.CanonicalName); // <API key> listener = new <API key>(); // listener.ConnectionReceived += <API key>; // //StreamSockets // //ConnectionReceived // //StreamSocketListenerControl'MSDN // listener.Control.KeepAlive = false; // //Socket, // CoreApplication.Properties.Add("listener", listener); // try // await listener.<API key>("8080"); // Debug.WriteLine("Listening......"); // catch (Exception) // throw; //private async void <API key>(<API key> sender, <API key> args) // //DataReader reader = new DataReader(args.Socket.InputStream); // //try // // while (true) // // // Read first 4 bytes (length of the subsequent string). // // uint sizeFieldCount = await reader.LoadAsync(sizeof(uint)); // // if (sizeFieldCount != sizeof(uint)) // // // The underlying socket was closed before we were able to read the whole data. // // return; // // // Read the string. // // uint stringLength = reader.ReadUInt32(); // // uint actualStringLength = await reader.LoadAsync(stringLength); // // if (stringLength != actualStringLength) // // // The underlying socket was closed before we were able to read the whole data. // // return; // //catch (Exception exception) // Stream inStream = args.Socket.InputStream.AsStreamForRead(); // StreamReader reader = new StreamReader(inStream); // Stream outStream = args.Socket.OutputStream.AsStreamForWrite(); // StreamWriter writer = new StreamWriter(outStream); // while (true) // string inStr = await reader.ReadLineAsync(); // string outStr = null; // Debug.WriteLine("IN:" + inStr); // if (inStr.StartsWith(" // string codeStr = inStr.Substring(0, 8); // CommCode code = CommHandle.StringConvertToEnum(codeStr); // switch (code) // case CommCode.TCPCONN: // outStr = TCPCOMMHandle(); // break; // case CommCode.AS: // break; // case CommCode.ERROR: // Debug.WriteLine(":" + codeStr); // break; // default: // break; // //TODO:System.<API key> // if (outStr != null) // await writer.WriteLineAsync(inStr); // await writer.FlushAsync(); // //await Task.Delay(100); <summary> An event to notify listeners when the hamburger button may occlude other content in the app. The custom "PageHeader" user control is using this. </summary> public event TypedEventHandler<MainPage, Rect> <API key>; <summary> Public method to allow pages to open SplitView's pane. Used for custom app shortcuts like navigating left from page's left-most item </summary> public void OpenNavePane() { TogglePaneButton.IsChecked = true; NavPaneDivider.Visibility = Visibility.Visible; } <summary> Invoked when application execution is being suspended. Application state is saved without knowing whether the application will be terminated or resumed with the contents of memory still intact. </summary> <param name="sender">The source of the suspend request.</param> <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); // Save application state and stop any background activity deferral.Complete(); } private string TCPCOMMHandle() { string result = "#TCPOK**"; return result; } } public enum NotifyType { StatusMessage, ErrorMessage }; //private void UpdateStatus(string strMessage, NotifyType type) // switch (type) // case NotifyType.StatusMessage: // StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Green); // break; // case NotifyType.ErrorMessage: // StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Red); // break; // StatusBlock.Text = strMessage; // // Collapse the StatusBlock if it has no text to conserve real estate. // StatusBorder.Visibility = (StatusBlock.Text != String.Empty) ? Visibility.Visible : Visibility.Collapsed; // if (StatusBlock.Text != String.Empty) // StatusBorder.Visibility = Visibility.Visible; // StatusPanel.Visibility = Visibility.Visible; // else // StatusBorder.Visibility = Visibility.Collapsed; // StatusPanel.Visibility = Visibility.Collapsed; }
// The LLVM Compiler Infrastructure // This file is distributed under the University of Illinois Open Source // This file implements semantic analysis for C++ expressions. #include "clang/Sema/SemaInternal.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/Initialization.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/ParsedTemplate.h" #include "clang/Sema/TemplateDeduction.h" #include "clang/AST/ASTContext.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/TypeLoc.h" #include "clang/Basic/PartialDiagnostic.h" #include "clang/Basic/TargetInfo.h" #include "clang/Lex/Preprocessor.h" #include "llvm/ADT/STLExtras.h" using namespace clang; using namespace sema; ParsedType Sema::getDestructorName(SourceLocation TildeLoc, IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectTypePtr, bool EnteringContext) { // Determine where to perform name lookup. // FIXME: This area of the standard is very messy, and the current // wording is rather unclear about which scopes we search for the // destructor name; see core issues 399 and 555. Issue 399 in // particular shows where the current description of destructor name // lookup is completely out of line with existing practice, e.g., // this appears to be ill-formed: // namespace N { // template <typename T> struct S { // void f(N::S<int>* s) { // s->N::S<int>::~S(); // See also PR6358 and PR6359. // For this reason, we're currently only doing the C++03 version of this // code; the C++0x version has to wait until we get a proper spec. QualType SearchType; DeclContext *LookupCtx = 0; bool isDependent = false; bool LookInScope = false; // If we have an object type, it's because we are in a // <API key> or a member access expression, and // we know what type we're looking for. if (ObjectTypePtr) SearchType = GetTypeFromParser(ObjectTypePtr); if (SS.isSet()) { NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); bool AlreadySearched = false; bool LookAtPrefix = true; // C++ [basic.lookup.qual]p6: // If a <API key> (5.2.4) contains a <API key>, // the type-names are looked up as types in the scope designated by the // <API key>. In a qualified-id of the form: // where the <API key> designates a namespace scope, and in // a qualified-id of the form: // the class-names are looked up as types in the scope designated by // the <API key>. // Here, we check the first case (completely) and determine whether the // code below is permitted to look at the prefix of the // <API key>. DeclContext *DC = computeDeclContext(SS, EnteringContext); if (DC && DC->isFileContext()) { AlreadySearched = true; LookupCtx = DC; isDependent = false; } else if (DC && isa<CXXRecordDecl>(DC)) LookAtPrefix = false; // The second case from the C++03 rules quoted further above. NestedNameSpecifier *Prefix = 0; if (AlreadySearched) { // Nothing left to do. } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) { CXXScopeSpec PrefixSS; PrefixSS.setScopeRep(Prefix); LookupCtx = computeDeclContext(PrefixSS, EnteringContext); isDependent = <API key>(PrefixSS); } else if (ObjectTypePtr) { LookupCtx = computeDeclContext(SearchType); isDependent = SearchType->isDependentType(); } else { LookupCtx = computeDeclContext(SS, EnteringContext); isDependent = LookupCtx && LookupCtx->isDependentContext(); } LookInScope = false; } else if (ObjectTypePtr) { // C++ [basic.lookup.classref]p3: // If the unqualified-id is ~type-name, the type-name is looked up // in the context of the entire postfix-expression. If the type T // of the object expression is of a class type C, the type-name is // also looked up in the scope of class C. At least one of the // lookups shall find a name that refers to (possibly // cv-qualified) T. LookupCtx = computeDeclContext(SearchType); isDependent = SearchType->isDependentType(); assert((isDependent || !SearchType->isIncompleteType()) && "Caller should have completed object type"); LookInScope = true; } else { // Perform lookup into the current scope (only). LookInScope = true; } LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName); for (unsigned Step = 0; Step != 2; ++Step) { // Look for the name first in the computed lookup context (if we // have one) and, if that fails to find a match, in the sope (if // we're allowed to look there). Found.clear(); if (Step == 0 && LookupCtx) LookupQualifiedName(Found, LookupCtx); else if (Step == 1 && LookInScope && S) LookupName(Found, S); else continue; // FIXME: Should we be suppressing ambiguities here? if (Found.isAmbiguous()) return ParsedType(); if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { QualType T = Context.getTypeDeclType(Type); if (SearchType.isNull() || SearchType->isDependentType() || Context.<API key>(T, SearchType)) { // We found our type! return ParsedType::make(T); } } // If the name that we found is a class template name, and it is // the same name as the template name in the last part of the // <API key> (if present) or the object type, then // this is the destructor for that class. // FIXME: This is a workaround until we get real drafting for core // issue 399, for which there isn't even an obvious direction. if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) { QualType MemberOfType; if (SS.isSet()) { if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) { // Figure out the type of the context, if it has one. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) MemberOfType = Context.getTypeDeclType(Record); } } if (MemberOfType.isNull()) MemberOfType = SearchType; if (MemberOfType.isNull()) continue; // We're referring into a class template specialization. If the // class template we found is the same as the template being // specialized, we found what we are looking for. if (const RecordType *Record = MemberOfType->getAs<RecordType>()) { if (<API key> *Spec = dyn_cast<<API key>>(Record->getDecl())) { if (Spec-><API key>()->getCanonicalDecl() == Template->getCanonicalDecl()) return ParsedType::make(MemberOfType); } continue; } // We're referring to an unresolved class template // specialization. Determine whether we class template we found // is the same as the template being specialized or, if we don't // know which template is being specialized, that it at least // has the same name. if (const <API key> *SpecType = MemberOfType->getAs<<API key>>()) { TemplateName SpecName = SpecType->getTemplateName(); // The class template we found is the same template being // specialized. if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) { if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl()) return ParsedType::make(MemberOfType); continue; } // The class template we found has the same name as the // (dependent) template name being specialized. if (<API key> *DepTemplate = SpecName.<API key>()) { if (DepTemplate->isIdentifier() && DepTemplate->getIdentifier() == Template->getIdentifier()) return ParsedType::make(MemberOfType); continue; } } } } if (isDependent) { // We didn't find our type, but that's okay: it's dependent // anyway. NestedNameSpecifier *NNS = 0; SourceRange Range; if (SS.isSet()) { NNS = (NestedNameSpecifier *)SS.getScopeRep(); Range = SourceRange(SS.getRange().getBegin(), NameLoc); } else { NNS = NestedNameSpecifier::Create(Context, &II); Range = SourceRange(NameLoc); } QualType T = CheckTypenameType(ETK_None, NNS, II, SourceLocation(), Range, NameLoc); return ParsedType::make(T); } if (ObjectTypePtr) Diag(NameLoc, diag::<API key>) << &II; else Diag(NameLoc, diag::<API key>); return ParsedType(); } \brief Build a C++ typeid expression with a type operand. ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc) { // C++ [expr.typeid]p4: // The top-level cv-qualifiers of the lvalue expression or the type-id // that is the operand of typeid are always ignored. // If the type of the type-id is a class type or a reference to a class // type, the class shall be completely-defined. Qualifiers Quals; QualType T = Context.<API key>(Operand->getType().getNonReferenceType(), Quals); if (T->getAs<RecordType>() && RequireCompleteType(TypeidLoc, T, diag::<API key>)) return ExprError(); return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand, SourceRange(TypeidLoc, RParenLoc))); } \brief Build a C++ typeid expression with an expression operand. ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *E, SourceLocation RParenLoc) { bool <API key> = true; if (E && !E->isTypeDependent()) { QualType T = E->getType(); if (const RecordType *RecordT = T->getAs<RecordType>()) { CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); // C++ [expr.typeid]p3: // [...] If the type of the expression is a class type, the class // shall be completely-defined. if (RequireCompleteType(TypeidLoc, T, diag::<API key>)) return ExprError(); // C++ [expr.typeid]p3: // When typeid is applied to an expression other than an glvalue of a // polymorphic class type [...] [the] expression is an unevaluated // operand. [...] if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) { <API key> = false; // We require a vtable to query the type at run time. MarkVTableUsed(TypeidLoc, RecordD); } } // C++ [expr.typeid]p4: // [...] If the type of the type-id is a reference to a possibly // cv-qualified type, the result of the typeid expression refers to a // std::type_info object representing the cv-unqualified referenced // type. Qualifiers Quals; QualType UnqualT = Context.<API key>(T, Quals); if (!Context.hasSameType(T, UnqualT)) { T = UnqualT; ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E)); } } // If this is an unevaluated operand, clear out the set of // declaration references we have been computing and eliminate any // temporaries introduced in its computation. if (<API key>) ExprEvalContexts.back().Context = Unevaluated; return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E, SourceRange(TypeidLoc, RParenLoc))); } <API key> - Parse typeid( type-id ) or typeid (expression); ExprResult Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc) { // Find the std::type_info type. if (!StdNamespace) return ExprError(Diag(OpLoc, diag::<API key>)); IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); LookupQualifiedName(R, getStdNamespace()); RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>(); if (!TypeInfoRecordDecl) return ExprError(Diag(OpLoc, diag::<API key>)); QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl); if (isType) { // The operand is a type; handle it as such. TypeSourceInfo *TInfo = 0; QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), &TInfo); if (T.isNull()) return ExprError(); if (!TInfo) TInfo = Context.<API key>(T, OpLoc); return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc); } // The operand is an expression. return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc); } ActOnCXXBoolLiteral - Parse {true,false} literals. ExprResult Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { assert((Kind == tok::kw_true || Kind == tok::kw_false) && "Unknown C++ Boolean value!"); return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc)); } <API key> - Parse 'nullptr'. ExprResult Sema::<API key>(SourceLocation Loc) { return Owned(new (Context) <API key>(Context.NullPtrTy, Loc)); } ActOnCXXThrow - Parse throw expressions. ExprResult Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) { if (Ex && !Ex->isTypeDependent() && <API key>(OpLoc, Ex)) return ExprError(); return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc)); } <API key> - Validate the operand of a throw. bool Sema::<API key>(SourceLocation ThrowLoc, Expr *&E) { // C++ [except.throw]p3: // A throw-expression initializes a temporary object, called the exception // object, the type of which is determined by removing any top-level // cv-qualifiers from the static type of the operand of throw and adjusting // the type from "array of T" or "function returning T" to "pointer to T" // or "pointer to function returning T", [...] if (E->getType().hasQualifiers()) ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp, CastCategory(E)); <API key>(E); // If the type of the exception would be an incomplete type or a pointer // to an incomplete type other than (cv) void the program is ill-formed. QualType Ty = E->getType(); bool isPointer = false; if (const PointerType* Ptr = Ty->getAs<PointerType>()) { Ty = Ptr->getPointeeType(); isPointer = true; } if (!isPointer || !Ty->isVoidType()) { if (RequireCompleteType(ThrowLoc, Ty, PDiag(isPointer ? diag::<API key> : diag::<API key>) << E->getSourceRange())) return true; if (<API key>(ThrowLoc, E->getType(), PDiag(diag::<API key>) << E->getSourceRange())) return true; } // Initialize the exception result. This implicitly weeds out // abstract types or types with inaccessible copy constructors. // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34. InitializedEntity Entity = InitializedEntity::InitializeException(ThrowLoc, E->getType(), /*NRVO=*/false); ExprResult Res = <API key>(Entity, SourceLocation(), Owned(E)); if (Res.isInvalid()) return true; E = Res.takeAs<Expr>(); // If the exception has class type, we need additional handling. const RecordType *RecordTy = Ty->getAs<RecordType>(); if (!RecordTy) return false; CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); // If we are throwing a polymorphic class type or pointer thereof, // exception handling will make use of the vtable. MarkVTableUsed(ThrowLoc, RD); // If the class has a non-trivial destructor, we must be able to call it. if (RD-><API key>()) return false; CXXDestructorDecl *Destructor = const_cast<CXXDestructorDecl*>(LookupDestructor(RD)); if (!Destructor) return false; <API key>(E->getExprLoc(), Destructor); <API key>(E->getExprLoc(), Destructor, PDiag(diag::<API key>) << Ty); return false; } ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) { C++ 9.3.2: In the body of a non-static member function, the keyword this is a non-lvalue expression whose value is the address of the object for which the function is called. DeclContext *DC = <API key>(); if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) if (MD->isInstance()) return Owned(new (Context) CXXThisExpr(ThisLoc, MD->getThisType(Context), /*isImplicit=*/false)); return ExprError(Diag(ThisLoc, diag::<API key>)); } <API key> - Parse construction of a specified type. Can be interpreted either as function-style casting ("int(x)") or class type construction ("ClassType(x,y,z)") or creation of a value-initialized type ("int()"). ExprResult Sema::<API key>(SourceRange TypeRange, ParsedType TypeRep, SourceLocation LParenLoc, MultiExprArg exprs, SourceLocation *CommaLocs, SourceLocation RParenLoc) { if (!TypeRep) return ExprError(); TypeSourceInfo *TInfo; QualType Ty = GetTypeFromParser(TypeRep, &TInfo); if (!TInfo) TInfo = Context.<API key>(Ty, SourceLocation()); unsigned NumExprs = exprs.size(); Expr **Exprs = (Expr**)exprs.get(); SourceLocation TyBeginLoc = TypeRange.getBegin(); SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc); if (Ty->isDependentType() || CallExpr::<API key>(Exprs, NumExprs)) { exprs.release(); return Owned(<API key>::Create(Context, TypeRange.getBegin(), Ty, LParenLoc, Exprs, NumExprs, RParenLoc)); } if (Ty->isArrayType()) return ExprError(Diag(TyBeginLoc, diag::<API key>) << FullRange); if (!Ty->isVoidType() && RequireCompleteType(TyBeginLoc, Ty, PDiag(diag::<API key>) << FullRange)) return ExprError(); if (<API key>(TyBeginLoc, Ty, diag::<API key>)) return ExprError(); // C++ [expr.type.conv]p1: // If the expression list is a single expression, the type conversion // expression is equivalent (in definedness, and if defined in meaning) to the // corresponding cast expression. if (NumExprs == 1) { CastKind Kind = CK_Unknown; CXXCastPath BasePath; if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath, /*FunctionalStyle=*/true)) return ExprError(); exprs.release(); return Owned(<API key>::Create(Context, Ty.<API key>(Context), TInfo, TyBeginLoc, Kind, Exprs[0], &BasePath, RParenLoc)); } if (Ty->isRecordType()) { InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); InitializationKind Kind = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(), LParenLoc, RParenLoc) : InitializationKind::CreateValue(TypeRange.getBegin(), LParenLoc, RParenLoc); <API key> InitSeq(*this, Entity, Kind, Exprs, NumExprs); ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs)); // FIXME: Improve AST representation? return move(Result); } // C++ [expr.type.conv]p1: // If the expression list specifies more than a single value, the type shall // be a class with a suitably declared constructor. if (NumExprs > 1) return ExprError(Diag(CommaLocs[0], diag::<API key>) << FullRange); assert(NumExprs == 0 && "Expected 0 expressions"); // C++ [expr.type.conv]p2: // The expression T(), where T is a <API key> for a non-array // complete object type or the (possibly cv-qualified) void type, creates an // rvalue of the specified type, which is value-initialized. exprs.release(); return Owned(new (Context) <API key>(Ty, TyBeginLoc, RParenLoc)); } ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.: @code new (memory) int[size][4] @endcode or @code ::new Foo(23, "hello") @endcode For the interpretation of this heap of arguments, consult the base version. ExprResult Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, SourceLocation ConstructorLParen, MultiExprArg ConstructorArgs, SourceLocation ConstructorRParen) { Expr *ArraySize = 0; // If the specified type is an array, unwrap it and save the expression. if (D.getNumTypeObjects() > 0 && D.getTypeObject(0).Kind == DeclaratorChunk::Array) { DeclaratorChunk &Chunk = D.getTypeObject(0); if (Chunk.Arr.hasStatic) return ExprError(Diag(Chunk.Loc, diag::<API key>) << D.getSourceRange()); if (!Chunk.Arr.NumElts) return ExprError(Diag(Chunk.Loc, diag::<API key>) << D.getSourceRange()); ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); D.DropFirstTypeObject(); } // Every dimension shall be of constant size. if (ArraySize) { for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) break; DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; if (Expr *NumElts = (Expr *)Array.NumElts) { if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() && !NumElts-><API key>(Context)) { Diag(D.getTypeObject(I).Loc, diag::<API key>) << NumElts->getSourceRange(); return ExprError(); } } } } //FIXME: Store TypeSourceInfo in CXXNew expression. TypeSourceInfo *TInfo = <API key>(D, /*Scope=*/0); QualType AllocType = TInfo->getType(); if (D.isInvalidType()) return ExprError(); SourceRange R = TInfo->getTypeLoc().getSourceRange(); return BuildCXXNew(StartLoc, UseGlobal, PlacementLParen, move(PlacementArgs), PlacementRParen, TypeIdParens, AllocType, D.getSourceRange().getBegin(), R, ArraySize, ConstructorLParen, move(ConstructorArgs), ConstructorRParen); } ExprResult Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, SourceLocation TypeLoc, SourceRange TypeRange, Expr *ArraySize, SourceLocation ConstructorLParen, MultiExprArg ConstructorArgs, SourceLocation ConstructorRParen) { if (CheckAllocatedType(AllocType, TypeLoc, TypeRange)) return ExprError(); // Per C++0x [expr.new]p5, the type being constructed may be a // typedef of an array type. if (!ArraySize) { if (const ConstantArrayType *Array = Context.<API key>(AllocType)) { ArraySize = IntegerLiteral::Create(Context, Array->getSize(), Context.getSizeType(), TypeRange.getEnd()); AllocType = Array->getElementType(); } } QualType ResultType = Context.getPointerType(AllocType); // C++ 5.3.4p6: "The expression in a <API key> shall have integral // or enumeration type with a non-negative value." if (ArraySize && !ArraySize->isTypeDependent()) { QualType SizeType = ArraySize->getType(); ExprResult ConvertedSize = <API key>(StartLoc, ArraySize, PDiag(diag::<API key>), PDiag(diag::<API key>) << ArraySize->getSourceRange(), PDiag(diag::<API key>), PDiag(diag::<API key>), PDiag(diag::<API key>), PDiag(diag::<API key>), PDiag(getLangOptions().CPlusPlus0x? 0 : diag::<API key>)); if (ConvertedSize.isInvalid()) return ExprError(); ArraySize = ConvertedSize.take(); SizeType = ArraySize->getType(); if (!SizeType-><API key>()) return ExprError(); // Let's see if this is a constant < 0. If so, we reject it out of hand. // We don't care about special rules, so we tell the machinery it's not // evaluated - it gives us a result in more cases. if (!ArraySize->isValueDependent()) { llvm::APSInt Value; if (ArraySize-><API key>(Value, Context, 0, false)) { if (Value < llvm::APSInt( llvm::APInt::getNullValue(Value.getBitWidth()), Value.isUnsigned())) return ExprError(Diag(ArraySize->getSourceRange().getBegin(), diag::<API key>) << ArraySize->getSourceRange()); if (!AllocType->isDependentType()) { unsigned ActiveSizeBits = ConstantArrayType::<API key>(Context, AllocType, Value); if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { Diag(ArraySize->getSourceRange().getBegin(), diag::err_array_too_large) << Value.toString(10) << ArraySize->getSourceRange(); return ExprError(); } } } else if (TypeIdParens.isValid()) { // Can't have dynamic array size when the type-id is in parentheses. Diag(ArraySize->getLocStart(), diag::<API key>) << ArraySize->getSourceRange() << FixItHint::CreateRemoval(TypeIdParens.getBegin()) << FixItHint::CreateRemoval(TypeIdParens.getEnd()); TypeIdParens = SourceRange(); } } ImpCastExprToType(ArraySize, Context.getSizeType(), CK_IntegralCast); } FunctionDecl *OperatorNew = 0; FunctionDecl *OperatorDelete = 0; Expr **PlaceArgs = (Expr**)PlacementArgs.get(); unsigned NumPlaceArgs = PlacementArgs.size(); if (!AllocType->isDependentType() && !Expr::<API key>(PlaceArgs, NumPlaceArgs) && <API key>(StartLoc, SourceRange(PlacementLParen, PlacementRParen), UseGlobal, AllocType, ArraySize, PlaceArgs, NumPlaceArgs, OperatorNew, OperatorDelete)) return ExprError(); llvm::SmallVector<Expr *, 8> AllPlaceArgs; if (OperatorNew) { // Add default arguments, if any. const FunctionProtoType *Proto = OperatorNew->getType()->getAs<FunctionProtoType>(); VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction : <API key>; if (<API key>(PlacementLParen, OperatorNew, Proto, 1, PlaceArgs, NumPlaceArgs, AllPlaceArgs, CallType)) return ExprError(); NumPlaceArgs = AllPlaceArgs.size(); if (NumPlaceArgs > 0) PlaceArgs = &AllPlaceArgs[0]; } bool Init = ConstructorLParen.isValid(); CXXConstructorDecl *Constructor = 0; Expr **ConsArgs = (Expr**)ConstructorArgs.get(); unsigned NumConsArgs = ConstructorArgs.size(); ASTOwningVector<Expr*> <API key>(*this); // Array 'new' can't have any initializers. if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) { SourceRange InitRange(ConsArgs[0]->getLocStart(), ConsArgs[NumConsArgs - 1]->getLocEnd()); Diag(StartLoc, diag::<API key>) << InitRange; return ExprError(); } if (!AllocType->isDependentType() && !Expr::<API key>(ConsArgs, NumConsArgs)) { // C++0x [expr.new]p15: // A new-expression that creates an object of type T initializes that // object as follows: InitializationKind Kind // - If the new-initializer is omitted, the object is default- // initialized (8.5); if no initialization is performed, // the object has indeterminate value = !Init? InitializationKind::CreateDefault(TypeLoc) // - Otherwise, the new-initializer is interpreted according to the // initialization rules of 8.5 for <API key>. : InitializationKind::CreateDirect(TypeLoc, ConstructorLParen, ConstructorRParen); InitializedEntity Entity = InitializedEntity::InitializeNew(StartLoc, AllocType); <API key> InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs); ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, move(ConstructorArgs)); if (FullInit.isInvalid()) return ExprError(); // FullInit is our initializer; walk through it to determine if it's a // constructor call, which CXXNewExpr handles directly. if (Expr *FullInitExpr = (Expr *)FullInit.get()) { if (<API key> *Binder = dyn_cast<<API key>>(FullInitExpr)) FullInitExpr = Binder->getSubExpr(); if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(FullInitExpr)) { Constructor = Construct->getConstructor(); for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(), AEnd = Construct->arg_end(); A != AEnd; ++A) <API key>.push_back(A->Retain()); } else { // Take the converted initializer. <API key>.push_back(FullInit.release()); } } else { // No initialization required. } // Take the converted arguments and use them for the new expression. NumConsArgs = <API key>.size(); ConsArgs = (Expr **)<API key>.take(); } // Mark the new and delete operators as referenced. if (OperatorNew) <API key>(StartLoc, OperatorNew); if (OperatorDelete) <API key>(StartLoc, OperatorDelete); // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16) PlacementArgs.release(); ConstructorArgs.release(); // FIXME: The TypeSourceInfo should also be included in CXXNewExpr. return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew, PlaceArgs, NumPlaceArgs, TypeIdParens, ArraySize, Constructor, Init, ConsArgs, NumConsArgs, OperatorDelete, ResultType, StartLoc, Init ? ConstructorRParen : TypeRange.getEnd())); } CheckAllocatedType - Checks that a type is suitable as the allocated type in a new-expression. dimension off and stores the size expression in ArraySize. bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R) { // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an // abstract class type or array thereof. if (AllocType->isFunctionType()) return Diag(Loc, diag::err_bad_new_type) << AllocType << 0 << R; else if (AllocType->isReferenceType()) return Diag(Loc, diag::err_bad_new_type) << AllocType << 1 << R; else if (!AllocType->isDependentType() && RequireCompleteType(Loc, AllocType, PDiag(diag::<API key>) << R)) return true; else if (<API key>(Loc, AllocType, diag::<API key>)) return true; return false; } \brief Determine whether the given function is a non-placement deallocation function. static bool <API key>(FunctionDecl *FD) { if (FD->isInvalidDecl()) return false; if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) return Method-><API key>(); return ((FD-><API key>() == OO_Delete || FD-><API key>() == OO_Array_Delete) && FD->getNumParams() == 1); } <API key> - Finds the overloads of operator new and delete that are appropriate for the allocation. bool Sema::<API key>(SourceLocation StartLoc, SourceRange Range, bool UseGlobal, QualType AllocType, bool IsArray, Expr **PlaceArgs, unsigned NumPlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete) { // C++ 5.3.4p8 - 14 & 18 // 1) If UseGlobal is true, only look in the global scope. Else, also look // in the scope of the allocated class. // 2) If an array size is given, look for operator new[], else look for // operator new. // 3) The first argument is always size_t. Append the arguments from the // placement form. llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs); // We don't care about the actual value of this argument. // FIXME: Should the Sema create the expression and embed it in the syntax // tree? Or should the consumer just recalculate the value? IntegerLiteral Size(Context, llvm::APInt::getNullValue( Context.Target.getPointerWidth(0)), Context.getSizeType(), SourceLocation()); AllocArgs[0] = &Size; std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1); // C++ [expr.new]p8: // If the allocated type is a non-array type, the allocation // name is operator delete. If the allocated type is an array DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( IsArray ? OO_Array_New : OO_New); DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( IsArray ? OO_Array_Delete : OO_Delete); QualType AllocElemType = Context.getBaseElementType(AllocType); if (AllocElemType->isRecordType() && !UseGlobal) { CXXRecordDecl *Record = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl()); if (<API key>(StartLoc, Range, NewName, &AllocArgs[0], AllocArgs.size(), Record, /*AllowMissing=*/true, OperatorNew)) return true; } if (!OperatorNew) { // Didn't find a member overload. Look for a global one. <API key>(); DeclContext *TUDecl = Context.<API key>(); if (<API key>(StartLoc, Range, NewName, &AllocArgs[0], AllocArgs.size(), TUDecl, /*AllowMissing=*/false, OperatorNew)) return true; } // We don't need an operator delete if we're running under // -fno-exceptions. if (!getLangOptions().Exceptions) { OperatorDelete = 0; return false; } // <API key> can change the passed in arguments, so we need to // copy them back. if (NumPlaceArgs > 0) std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs); // C++ [expr.new]p19: // If the new-expression begins with a unary :: operator, the // scope. Otherwise, if the allocated type is a class type T or an // the scope of T. If this lookup fails to find the name, or if // the allocated type is not a class type or array thereof, the LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); if (AllocElemType->isRecordType() && !UseGlobal) { CXXRecordDecl *RD = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl()); LookupQualifiedName(FoundDelete, RD); } if (FoundDelete.isAmbiguous()) return true; // FIXME: clean up expressions? if (FoundDelete.empty()) { <API key>(); LookupQualifiedName(FoundDelete, Context.<API key>()); } FoundDelete.suppressDiagnostics(); llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; if (NumPlaceArgs > 0) { // C++ [expr.new]p20: // A declaration of a placement deallocation function matches the // declaration of a placement allocation function if it has the // same number of parameters and, after parameter transformations // (8.3.5), all parameter types except the first are // identical. [...] // To perform this comparison, we compute the function type that // the deallocation function should have, and use that type both // for template argument deduction and for comparison purposes. QualType <API key>; { const FunctionProtoType *Proto = OperatorNew->getType()->getAs<FunctionProtoType>(); llvm::SmallVector<QualType, 4> ArgTypes; ArgTypes.push_back(Context.VoidPtrTy); for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I) ArgTypes.push_back(Proto->getArgType(I)); <API key> = Context.getFunctionType(Context.VoidTy, ArgTypes.data(), ArgTypes.size(), Proto->isVariadic(), 0, false, false, 0, 0, FunctionType::ExtInfo()); } for (LookupResult::iterator D = FoundDelete.begin(), DEnd = FoundDelete.end(); D != DEnd; ++D) { FunctionDecl *Fn = 0; if (<API key> *FnTmpl = dyn_cast<<API key>>((*D)->getUnderlyingDecl())) { // Perform template argument deduction to try to match the // expected function type. <API key> Info(Context, StartLoc); if (<API key>(FnTmpl, 0, <API key>, Fn, Info)) continue; } else Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); if (Context.hasSameType(Fn->getType(), <API key>)) Matches.push_back(std::make_pair(D.getPair(), Fn)); } } else { // C++ [expr.new]p20: // [...] Any non-placement deallocation function matches a // non-placement allocation function. [...] for (LookupResult::iterator D = FoundDelete.begin(), DEnd = FoundDelete.end(); D != DEnd; ++D) { if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl())) if (<API key>(Fn)) Matches.push_back(std::make_pair(D.getPair(), Fn)); } } // C++ [expr.new]p20: // [...] If the lookup finds a single matching deallocation // function, that function will be called; otherwise, no // deallocation function will be called. if (Matches.size() == 1) { OperatorDelete = Matches[0].second; // C++0x [expr.new]p20: // If the lookup finds the two-parameter form of a usual // deallocation function (3.7.4.2) and that function, considered // as a placement deallocation function, would have been // selected as a match for the allocation function, the program // is ill-formed. if (NumPlaceArgs && getLangOptions().CPlusPlus0x && <API key>(OperatorDelete)) { Diag(StartLoc, diag::<API key>) << SourceRange(PlaceArgs[0]->getLocStart(), PlaceArgs[NumPlaceArgs - 1]->getLocEnd()); Diag(OperatorDelete->getLocation(), diag::note_previous_decl) << DeleteName; } else { <API key>(StartLoc, Range, FoundDelete.getNamingClass(), Matches[0].first); } } return false; } <API key> - Find an fitting overload for the allocation function in the specified scope. bool Sema::<API key>(SourceLocation StartLoc, SourceRange Range, DeclarationName Name, Expr** Args, unsigned NumArgs, DeclContext *Ctx, bool AllowMissing, FunctionDecl *&Operator) { LookupResult R(*this, Name, StartLoc, LookupOrdinaryName); LookupQualifiedName(R, Ctx); if (R.empty()) { if (AllowMissing) return false; return Diag(StartLoc, diag::<API key>) << Name << Range; } if (R.isAmbiguous()) return true; R.suppressDiagnostics(); <API key> Candidates(StartLoc); for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); Alloc != AllocEnd; ++Alloc) { // Even member operator new/delete are implicitly treated as // static, so don't use AddMemberCandidate. NamedDecl *D = (*Alloc)->getUnderlyingDecl(); if (<API key> *FnTemplate = dyn_cast<<API key>>(D)) { <API key>(FnTemplate, Alloc.getPair(), /*<API key>=*/0, Args, NumArgs, Candidates, /*<API key>=*/false); continue; } FunctionDecl *Fn = cast<FunctionDecl>(D); <API key>(Fn, Alloc.getPair(), Args, NumArgs, Candidates, /*<API key>=*/false); } // Do the resolution. <API key>::iterator Best; switch (Candidates.BestViableFunction(*this, StartLoc, Best)) { case OR_Success: { // Got one! FunctionDecl *FnDecl = Best->Function; // The first argument is size_t, and the first parameter must be size_t, // too. This is checked on declaration and can be assumed. (It can't be // asserted on, though, since invalid decls are left in there.) // Watch out for variadic allocator function. unsigned NumArgsInFnDecl = FnDecl->getNumParams(); for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) { ExprResult Result = <API key>(InitializedEntity::InitializeParameter( FnDecl->getParamDecl(i)), SourceLocation(), Owned(Args[i]->Retain())); if (Result.isInvalid()) return true; Args[i] = Result.takeAs<Expr>(); } Operator = FnDecl; <API key>(StartLoc, Range, R.getNamingClass(), Best->FoundDecl); return false; } case <API key>: Diag(StartLoc, diag::<API key>) << Name << Range; Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); return true; case OR_Ambiguous: Diag(StartLoc, diag::<API key>) << Name << Range; Candidates.NoteCandidates(*this, <API key>, Args, NumArgs); return true; case OR_Deleted: Diag(StartLoc, diag::<API key>) << Best->Function->isDeleted() << Name << Range; Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); return true; } assert(false && "Unreachable, bad result from BestViableFunction"); return true; } <API key> - Declare the global forms of operator new and delete. These are: @code void* operator new(std::size_t) throw(std::bad_alloc); void* operator new[](std::size_t) throw(std::bad_alloc); void operator delete(void *) throw(); void operator delete[](void *) throw(); @endcode Note that the placement and nothrow forms of new are *not* implicitly declared. Their use requires including \<new\>. void Sema::<API key>() { if (<API key>) return; // C++ [basic.std.dynamic]p2: // [...] The following allocation and deallocation functions (18.4) are // implicitly declared in global scope in each translation unit of a // program // void* operator new(std::size_t) throw(std::bad_alloc); // void* operator new[](std::size_t) throw(std::bad_alloc); // void operator delete(void*) throw(); // void operator delete[](void*) throw(); // These implicit declarations introduce only the function names operator // new, operator new[], operator delete, operator delete[]. // Here, we need to refer to std::bad_alloc, so we will implicitly declare // "std" or "bad_alloc" as necessary to form the exception specification. // However, we do not make these implicit declarations visible to name // lookup. if (!StdBadAlloc) { // The "std::bad_alloc" class has not yet been declared, so build it // implicitly. StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, <API key>(), SourceLocation(), &PP.getIdentifierTable().get("bad_alloc"), SourceLocation(), 0); getStdBadAlloc()->setImplicit(true); } <API key> = true; QualType VoidPtr = Context.getPointerType(Context.VoidTy); QualType SizeT = Context.getSizeType(); bool <API key> = getLangOptions().<API key>; <API key>( Context.DeclarationNames.getCXXOperatorName(OO_New), VoidPtr, SizeT, <API key>); <API key>( Context.DeclarationNames.getCXXOperatorName(OO_Array_New), VoidPtr, SizeT, <API key>); <API key>( Context.DeclarationNames.getCXXOperatorName(OO_Delete), Context.VoidTy, VoidPtr); <API key>( Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), Context.VoidTy, VoidPtr); } <API key> - Declares a single implicit global allocation function if it doesn't already exist. void Sema::<API key>(DeclarationName Name, QualType Return, QualType Argument, bool AddMallocAttr) { DeclContext *GlobalCtx = Context.<API key>(); // Check if this function is already declared. { DeclContext::lookup_iterator Alloc, AllocEnd; for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name); Alloc != AllocEnd; ++Alloc) { // Only look at non-template functions, as it is the predefined, // non-templated allocation function we are trying to declare here. if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { QualType InitialParamType = Context.getCanonicalType( Func->getParamDecl(0)->getType().getUnqualifiedType()); // FIXME: Do we need to check for default arguments here? if (Func->getNumParams() == 1 && InitialParamType == Argument) { if(AddMallocAttr && !Func->hasAttr<MallocAttr>()) Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context)); return; } } } } QualType BadAllocType; bool <API key> = (Name.<API key>() == OO_New || Name.<API key>() == OO_Array_New); if (<API key>) { assert(StdBadAlloc && "Must have std::bad_alloc declared"); BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); } QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0, true, false, <API key>? 1 : 0, &BadAllocType, FunctionType::ExtInfo()); FunctionDecl *Alloc = FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name, FnType, /*TInfo=*/0, SC_None, SC_None, false, true); Alloc->setImplicit(); if (AddMallocAttr) Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context)); ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(), 0, Argument, /*TInfo=*/0, SC_None, SC_None, 0); Alloc->setParams(&Param, 1); // FIXME: Also add this declaration to the IdentifierResolver, but // make sure it is at the end of the chain to coincide with the // global scope. Context.<API key>()->addDecl(Alloc); } bool Sema::<API key>(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl* &Operator) { LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); // Try to find operator delete/operator delete[] in class scope. LookupQualifiedName(Found, RD); if (Found.isAmbiguous()) return true; Found.suppressDiagnostics(); llvm::SmallVector<DeclAccessPair,4> Matches; for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); F != FEnd; ++F) { NamedDecl *ND = (*F)->getUnderlyingDecl(); // Ignore template operator delete members from the check for a usual // deallocation function. if (isa<<API key>>(ND)) continue; if (cast<CXXMethodDecl>(ND)-><API key>()) Matches.push_back(F.getPair()); } // There's exactly one suitable operator; pick it. if (Matches.size() == 1) { Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl()); <API key>(StartLoc, SourceRange(), Found.getNamingClass(), Matches[0]); return false; // We found multiple suitable operators; complain about the ambiguity. } else if (!Matches.empty()) { Diag(StartLoc, diag::<API key>) << Name << RD; for (llvm::SmallVectorImpl<DeclAccessPair>::iterator F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F) Diag((*F)->getUnderlyingDecl()->getLocation(), diag::<API key>) << Name; return true; } // We did find operator delete/operator delete[] declarations, but // none of them were suitable. if (!Found.empty()) { Diag(StartLoc, diag::<API key>) << Name << RD; for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); F != FEnd; ++F) Diag((*F)->getUnderlyingDecl()->getLocation(), diag::<API key>) << Name; return true; } // Look for a global declaration. <API key>(); DeclContext *TUDecl = Context.<API key>(); <API key> Null(Context.VoidPtrTy, SourceLocation()); Expr* DeallocArgs[1]; DeallocArgs[0] = &Null; if (<API key>(StartLoc, SourceRange(), Name, DeallocArgs, 1, TUDecl, /*AllowMissing=*/false, Operator)) return true; assert(Operator && "Did not find a deallocation function!"); return false; } ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: @code ::delete ptr; @endcode or @code delete [] ptr; @endcode ExprResult Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Ex) { // C++ [expr.delete]p1: // The operand shall have a pointer type, or a class type having a single // conversion function to a pointer type. The result has type void. // DR599 amends "pointer type" to "pointer to object type" in both cases. FunctionDecl *OperatorDelete = 0; if (!Ex->isTypeDependent()) { QualType Type = Ex->getType(); if (const RecordType *Record = Type->getAs<RecordType>()) { if (RequireCompleteType(StartLoc, Type, PDiag(diag::<API key>))) return ExprError(); llvm::SmallVector<CXXConversionDecl*, 4> <API key>; CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); const UnresolvedSetImpl *Conversions = RD-><API key>(); for (UnresolvedSetImpl::iterator I = Conversions->begin(), E = Conversions->end(); I != E; ++I) { NamedDecl *D = I.getDecl(); if (isa<UsingShadowDecl>(D)) D = cast<UsingShadowDecl>(D)->getTargetDecl(); // Skip over templated conversion functions; they aren't considered. if (isa<<API key>>(D)) continue; CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); QualType ConvType = Conv->getConversionType().getNonReferenceType(); if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) if (ConvPtrType->getPointeeType()-><API key>()) <API key>.push_back(Conv); } if (<API key>.size() == 1) { // We have a single conversion to a pointer-to-object type. Perform // that conversion. // TODO: don't redo the conversion calculation. if (!<API key>(Ex, <API key>.front()->getConversionType(), AA_Converting)) { Type = Ex->getType(); } } else if (<API key>.size() > 1) { Diag(StartLoc, diag::<API key>) << Type << Ex->getSourceRange(); for (unsigned i= 0; i < <API key>.size(); i++) <API key>(<API key>[i]); return ExprError(); } } if (!Type->isPointerType()) return ExprError(Diag(StartLoc, diag::err_delete_operand) << Type << Ex->getSourceRange()); QualType Pointee = Type->getAs<PointerType>()->getPointeeType(); if (Pointee->isVoidType() && !isSFINAEContext()) { // The C++ standard bans deleting a pointer to a non-object type, which // effectively bans deletion of "void*". However, most compilers support // this, so we treat it as a warning unless we're in a SFINAE context. Diag(StartLoc, diag::<API key>) << Type << Ex->getSourceRange(); } else if (Pointee->isFunctionType() || Pointee->isVoidType()) return ExprError(Diag(StartLoc, diag::err_delete_operand) << Type << Ex->getSourceRange()); else if (!Pointee->isDependentType() && RequireCompleteType(StartLoc, Pointee, PDiag(diag::<API key>) << Ex->getSourceRange())) return ExprError(); // C++ [expr.delete]p2: // [Note: a pointer to a const type can be the operand of a // delete-expression; it is not necessary to cast away the constness // (5.2.11) of the pointer expression before it is used as the operand // of the delete-expression. ] ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy), CK_NoOp); DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( ArrayForm ? OO_Array_Delete : OO_Delete); QualType PointeeElem = Context.getBaseElementType(Pointee); if (const RecordType *RT = PointeeElem->getAs<RecordType>()) { CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); if (!UseGlobal && <API key>(StartLoc, RD, DeleteName, OperatorDelete)) return ExprError(); if (!RD-><API key>()) if (const CXXDestructorDecl *Dtor = LookupDestructor(RD)) <API key>(StartLoc, const_cast<CXXDestructorDecl*>(Dtor)); } if (!OperatorDelete) { // Look for a global declaration. <API key>(); DeclContext *TUDecl = Context.<API key>(); if (<API key>(StartLoc, SourceRange(), DeleteName, &Ex, 1, TUDecl, /*AllowMissing=*/false, OperatorDelete)) return ExprError(); } <API key>(StartLoc, OperatorDelete); // FIXME: Check access and ambiguity of operator delete and destructor. } return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, OperatorDelete, Ex, StartLoc)); } \brief Check the use of the given variable as a C++ condition in an if, while, do-while, or switch statement. ExprResult Sema::<API key>(VarDecl *ConditionVar, SourceLocation StmtLoc, bool ConvertToBoolean) { QualType T = ConditionVar->getType(); // C++ [stmt.select]p2: // The declarator shall not specify a function or an array. if (T->isFunctionType()) return ExprError(Diag(ConditionVar->getLocation(), diag::<API key>) << ConditionVar->getSourceRange()); else if (T->isArrayType()) return ExprError(Diag(ConditionVar->getLocation(), diag::<API key>) << ConditionVar->getSourceRange()); Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar, ConditionVar->getLocation(), ConditionVar->getType().getNonReferenceType()); if (ConvertToBoolean && <API key>(Condition, StmtLoc)) return ExprError(); return Owned(Condition); } <API key> - Returns true if a conversion to bool is invalid. bool Sema::<API key>(Expr *&CondExpr) { // C++ 6.4p4: // The value of a condition that is an initialized declaration in a statement // other than a switch statement is the value of the declared variable // implicitly converted to type bool. If that conversion is ill-formed, the // program is ill-formed. // The value of a condition that is an expression is the value of the // expression, implicitly converted to bool. return <API key>(CondExpr); } Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to a pointer to non-const char or non-const wchar_t (for narrow and wide string literals, respectively). bool Sema::<API key>(Expr *From, QualType ToType) { // Look inside the implicit cast, if it exists. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) From = Cast->getSubExpr(); // A string literal (2.13.4) that is not a wide string literal can // be converted to an rvalue of type "pointer to char"; a wide // string literal can be converted to an rvalue of type "pointer // to wchar_t" (C++ 4.2p2). if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) if (const BuiltinType *ToPointeeType = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { // This conversion is considered only when there is an // explicit appropriate pointer target type (C++ 4.2p2). if (!ToPtrType->getPointeeType().hasQualifiers() && ((StrLit->isWide() && ToPointeeType->isWideCharType()) || (!StrLit->isWide() && (ToPointeeType->getKind() == BuiltinType::Char_U || ToPointeeType->getKind() == BuiltinType::Char_S)))) return true; } return false; } static ExprResult <API key>(Sema &S, SourceLocation CastLoc, QualType Ty, CastKind Kind, CXXMethodDecl *Method, Expr *From) { switch (Kind) { default: assert(0 && "Unhandled cast kind!"); case <API key>: { ASTOwningVector<Expr*> ConstructorArgs(S); if (S.<API key>(cast<CXXConstructorDecl>(Method), MultiExprArg(&From, 1), CastLoc, ConstructorArgs)) return ExprError(); ExprResult Result = S.<API key>(CastLoc, Ty, cast<CXXConstructorDecl>(Method), move_arg(ConstructorArgs), /*ZeroInit*/ false, CXXConstructExpr::CK_Complete); if (Result.isInvalid()) return ExprError(); return S.<API key>(Result.takeAs<Expr>()); } case <API key>: { assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); // Create an implicit call expr that calls it. // FIXME: pass the FoundDecl for the user-defined conversion here CXXMemberCallExpr *CE = S.<API key>(From, Method, Method); return S.<API key>(CE); } } } <API key> - Perform an implicit conversion of the expression From to the type ToType using the pre-computed implicit conversion sequence ICS. Returns true if there was an error, false otherwise. The expression From is replaced with the converted expression. Action is the kind of conversion we're performing, used in the error message. bool Sema::<API key>(Expr *&From, QualType ToType, const <API key> &ICS, AssignmentAction Action, bool IgnoreBaseAccess) { switch (ICS.getKind()) { case <API key>::StandardConversion: if (<API key>(From, ToType, ICS.Standard, Action, IgnoreBaseAccess)) return true; break; case <API key>::<API key>: { FunctionDecl *FD = ICS.UserDefined.ConversionFunction; CastKind CastKind = CK_Unknown; QualType BeforeToType; if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { CastKind = <API key>; // If the user-defined conversion is specified by a conversion function, // the initial standard conversion sequence converts the source type to // the implicit object parameter of the conversion function. BeforeToType = Context.getTagDeclType(Conv->getParent()); } else if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { CastKind = <API key>; // Do no conversion if dealing with ... for the first conversion. if (!ICS.UserDefined.EllipsisConversion) { // If the user-defined conversion is specified by a constructor, the // initial standard conversion sequence converts the source type to the // type required by the argument of the constructor BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); } } else assert(0 && "Unknown conversion function kind!"); // Whatch out for elipsis conversion. if (!ICS.UserDefined.EllipsisConversion) { if (<API key>(From, BeforeToType, ICS.UserDefined.Before, AA_Converting, IgnoreBaseAccess)) return true; } ExprResult CastArg = <API key>(*this, From->getLocStart(), ToType.getNonReferenceType(), CastKind, cast<CXXMethodDecl>(FD), From); if (CastArg.isInvalid()) return true; From = CastArg.takeAs<Expr>(); return <API key>(From, ToType, ICS.UserDefined.After, AA_Converting, IgnoreBaseAccess); } case <API key>::AmbiguousConversion: ICS.<API key>(*this, From->getExprLoc(), PDiag(diag::<API key>) << From->getSourceRange()); return true; case <API key>::EllipsisConversion: assert(false && "Cannot perform an ellipsis conversion"); return false; case <API key>::BadConversion: return true; } // Everything went well. return false; } <API key> - Perform an implicit conversion of the expression From to the type ToType by following the standard conversion sequence SCS. Returns true if there was an error, false otherwise. The expression From is replaced with the converted expression. Flavor is the context in which we're performing this conversion, for use in error messages. bool Sema::<API key>(Expr *&From, QualType ToType, const <API key>& SCS, AssignmentAction Action, bool IgnoreBaseAccess) { // Overall FIXME: we are recomputing too many types here and doing far too // much extra work. What this means is that we need to keep track of more // information that is computed when we try the implicit conversion initially, // so that we don't need to recompute anything here. QualType FromType = From->getType(); if (SCS.CopyConstructor) { // FIXME: When can ToType be a reference type? assert(!ToType->isReferenceType()); if (SCS.Second == ICK_Derived_To_Base) { ASTOwningVector<Expr*> ConstructorArgs(*this); if (<API key>(cast<CXXConstructorDecl>(SCS.CopyConstructor), MultiExprArg(*this, &From, 1), /*FIXME:ConstructLoc*/SourceLocation(), ConstructorArgs)) return true; ExprResult FromResult = <API key>(/*FIXME:ConstructLoc*/SourceLocation(), ToType, SCS.CopyConstructor, move_arg(ConstructorArgs), /*ZeroInit*/ false, CXXConstructExpr::CK_Complete); if (FromResult.isInvalid()) return true; From = FromResult.takeAs<Expr>(); return false; } ExprResult FromResult = <API key>(/*FIXME:ConstructLoc*/SourceLocation(), ToType, SCS.CopyConstructor, MultiExprArg(*this, &From, 1), /*ZeroInit*/ false, CXXConstructExpr::CK_Complete); if (FromResult.isInvalid()) return true; From = FromResult.takeAs<Expr>(); return false; } // Resolve overloaded function references. if (Context.hasSameType(FromType, Context.OverloadTy)) { DeclAccessPair Found; FunctionDecl *Fn = <API key>(From, ToType, true, Found); if (!Fn) return true; if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin())) return true; From = <API key>(From, Found, Fn); FromType = From->getType(); } // Perform the first implicit conversion. switch (SCS.First) { case ICK_Identity: case <API key>: // Nothing to do. break; case <API key>: FromType = Context.getArrayDecayedType(FromType); ImpCastExprToType(From, FromType, <API key>); break; case <API key>: FromType = Context.getPointerType(FromType); ImpCastExprToType(From, FromType, <API key>); break; default: assert(false && "Improper first standard conversion"); break; } // Perform the second implicit conversion switch (SCS.Second) { case ICK_Identity: // If both sides are functions (or pointers/references to them), there could // be incompatible exception declarations. if (<API key>(From, ToType)) return true; // Nothing else to do. break; case <API key>: // If both sides are functions (or pointers/references to them), there could // be incompatible exception declarations. if (<API key>(From, ToType)) return true; ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false), CK_NoOp); break; case <API key>: case <API key>: ImpCastExprToType(From, ToType, CK_IntegralCast); break; case <API key>: case <API key>: ImpCastExprToType(From, ToType, CK_FloatingCast); break; case <API key>: case <API key>: ImpCastExprToType(From, ToType, CK_Unknown); break; case <API key>: if (ToType->isRealFloatingType()) ImpCastExprToType(From, ToType, <API key>); else ImpCastExprToType(From, ToType, <API key>); break; case <API key>: ImpCastExprToType(From, ToType, CK_NoOp); break; case <API key>: { if (SCS.IncompatibleObjC) { // Diagnose incompatible Objective-C conversions Diag(From->getSourceRange().getBegin(), diag::<API key>) << From->getType() << ToType << Action << From->getSourceRange(); } CastKind Kind = CK_Unknown; CXXCastPath BasePath; if (<API key>(From, ToType, Kind, BasePath, IgnoreBaseAccess)) return true; ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath); break; } case ICK_Pointer_Member: { CastKind Kind = CK_Unknown; CXXCastPath BasePath; if (<API key>(From, ToType, Kind, BasePath, IgnoreBaseAccess)) return true; if (<API key>(From, ToType)) return true; ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath); break; } case <API key>: { CastKind Kind = CK_Unknown; if (FromType->isMemberPointerType()) Kind = <API key>; ImpCastExprToType(From, Context.BoolTy, Kind); break; } case ICK_Derived_To_Base: { CXXCastPath BasePath; if (<API key>(From->getType(), ToType.getNonReferenceType(), From->getLocStart(), From->getSourceRange(), &BasePath, IgnoreBaseAccess)) return true; ImpCastExprToType(From, ToType.getNonReferenceType(), CK_DerivedToBase, CastCategory(From), &BasePath); break; } case <API key>: ImpCastExprToType(From, ToType, CK_BitCast); break; case ICK_Vector_Splat: ImpCastExprToType(From, ToType, CK_VectorSplat); break; case ICK_Complex_Real: ImpCastExprToType(From, ToType, CK_Unknown); break; case <API key>: case <API key>: case <API key>: case ICK_Qualification: case <API key>: assert(false && "Improper second standard conversion"); break; } switch (SCS.Third) { case ICK_Identity: // Nothing to do. break; case ICK_Qualification: { // The qualification keeps the category of the inner expression, unless the // target type isn't a reference. ExprValueKind VK = ToType->isReferenceType() ? CastCategory(From) : VK_RValue; ImpCastExprToType(From, ToType.<API key>(Context), CK_NoOp, VK); if (SCS.<API key>) Diag(From->getLocStart(), diag::<API key>) << ToType.getNonReferenceType(); break; } default: assert(false && "Improper third standard conversion"); break; } return false; } ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT, SourceLocation KWLoc, SourceLocation LParen, ParsedType Ty, SourceLocation RParen) { QualType T = GetTypeFromParser(Ty); // all traits except __is_class, __is_enum and __is_union require a the type // to be complete. if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) { if (RequireCompleteType(KWLoc, T, diag::<API key>)) return ExprError(); } // There is no point in eagerly computing the value. The traits are designed // to be used from type trait templates, so Ty will be a template parameter // 99% of the time. return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T, RParen, Context.BoolTy)); } QualType Sema::<API key>( Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) { const char *OpSpelling = isIndirect ? "->*" : ".*"; // C++ 5.5p2 // The binary operator .* [p3: ->*] binds its second operand, which shall // be of type "pointer to member of T" (where T is a completely-defined // class type) [...] QualType RType = rex->getType(); const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>(); if (!MemPtr) { Diag(Loc, diag::err_bad_memptr_rhs) << OpSpelling << RType << rex->getSourceRange(); return QualType(); } QualType Class(MemPtr->getClass(), 0); if (RequireCompleteType(Loc, Class, diag::<API key>)) return QualType(); // C++ 5.5p2 // [...] to its first operand, which shall be of class T or of a class of // which T is an unambiguous and accessible base class. [p3: a pointer to // such a class] QualType LType = lex->getType(); if (isIndirect) { if (const PointerType *Ptr = LType->getAs<PointerType>()) LType = Ptr->getPointeeType().getNonReferenceType(); else { Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling << 1 << LType << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); return QualType(); } } if (!Context.<API key>(Class, LType)) { // If we want to check the hierarchy, we need a complete type. if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs) << OpSpelling << (int)isIndirect)) { return QualType(); } CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, /*DetectVirtual=*/false); // FIXME: Would it be useful to print full ambiguity paths, or is that // overkill? if (!IsDerivedFrom(LType, Class, Paths) || Paths.isAmbiguous(Context.getCanonicalType(Class))) { Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling << (int)isIndirect << lex->getType(); return QualType(); } // Cast LHS to type of use. QualType UseType = isIndirect ? Context.getPointerType(Class) : Class; ExprValueKind VK = isIndirect ? VK_RValue : CastCategory(lex); CXXCastPath BasePath; BuildBasePathArray(Paths, BasePath); ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath); } if (isa<<API key>>(rex->IgnoreParens())) { // Diagnose use of pointer-to-member type which when used as // the functional cast in a pointer-to-member expression. Diag(Loc, diag::<API key>) << isIndirect; return QualType(); } // C++ 5.5p2 // The result is an object or a function of the type specified by the // second operand. // The cv qualifiers are the union of those in the pointer and the left side, // in accordance with 5.5p5 and 5.2.5. // FIXME: This returns a dereferenced member function pointer as a normal // function type. However, the only operation valid on such functions is // calling them. There's also a GCC extension to get a function pointer to the // thing, which is another complication, because this type - unlike the type // that is the result of this expression - takes the class as the first // argument. // We probably need a "<API key>" or something like that. QualType Result = MemPtr->getPointeeType(); Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers()); return Result; } \brief Try to convert a type to another according to C++0x 5.16p3. This is part of the parameter validation for the ? operator. If either value operand is a class type, the two operands are attempted to be converted to each other. This function does the conversion in one direction. It returns true if the program is ill-formed and has already been diagnosed as such. static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, SourceLocation QuestionLoc, bool &HaveConversion, QualType &ToType) { HaveConversion = false; ToType = To->getType(); InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(), SourceLocation()); // C++0x 5.16p3 // The process for determining whether an operand expression E1 of type T1 // can be converted to match an operand expression E2 of type T2 is defined // as follows: // -- If E2 is an lvalue: bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid); if (ToIsLvalue) { // E1 can be converted to match E2 if E1 can be implicitly converted to // type "lvalue reference to T2", subject to the constraint that in the // conversion the reference must bind directly to E1. QualType T = Self.Context.<API key>(ToType); InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); <API key> InitSeq(Self, Entity, Kind, &From, 1); if (InitSeq.<API key>()) { ToType = T; HaveConversion = true; return false; } if (InitSeq.isAmbiguous()) return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); } // -- If E2 is an rvalue, or if the conversion above cannot be done: // -- if E1 and E2 have class type, and the underlying class types are // the same or one is a base class of the other: QualType FTy = From->getType(); QualType TTy = To->getType(); const RecordType *FRec = FTy->getAs<RecordType>(); const RecordType *TRec = TTy->getAs<RecordType>(); bool FDerivedFromT = FRec && TRec && FRec != TRec && Self.IsDerivedFrom(FTy, TTy); if (FRec && TRec && (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) { // E1 can be converted to match E2 if the class of T2 is the // same type as, or a base class of, the class of T1, and // [cv2 > cv1]. if (FRec == TRec || FDerivedFromT) { if (TTy.<API key>(FTy)) { InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); <API key> InitSeq(Self, Entity, Kind, &From, 1); if (InitSeq.getKind() != <API key>::FailedSequence) { HaveConversion = true; return false; } if (InitSeq.isAmbiguous()) return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); } } return false; } // -- Otherwise: E1 can be converted to match E2 if E1 can be // implicitly converted to the type that expression E2 would have // if E2 were converted to an rvalue (or the type it has, if E2 is // an rvalue). // This actually refers very narrowly to the lvalue-to-rvalue conversion, not // to the array-to-pointer or function-to-pointer conversions. if (!TTy->getAs<TagType>()) TTy = TTy.getUnqualifiedType(); InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); <API key> InitSeq(Self, Entity, Kind, &From, 1); HaveConversion = InitSeq.getKind() != <API key>::FailedSequence; ToType = TTy; if (InitSeq.isAmbiguous()) return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); return false; } \brief Try to find a common type for two according to C++0x 5.16p5. This is part of the parameter validation for the ? operator. If either value operand is a class type, overload resolution is used to find a conversion to a common type. static bool <API key>(Sema &Self, Expr *&LHS, Expr *&RHS, SourceLocation Loc) { Expr *Args[2] = { LHS, RHS }; <API key> CandidateSet(Loc); Self.<API key>(OO_Conditional, Loc, Args, 2, CandidateSet); <API key>::iterator Best; switch (CandidateSet.BestViableFunction(Self, Loc, Best)) { case OR_Success: // We found a match. Perform the conversions on the arguments and move on. if (Self.<API key>(LHS, Best->BuiltinTypes.ParamTypes[0], Best->Conversions[0], Sema::AA_Converting) || Self.<API key>(RHS, Best->BuiltinTypes.ParamTypes[1], Best->Conversions[1], Sema::AA_Converting)) break; return false; case <API key>: Self.Diag(Loc, diag::<API key>) << LHS->getType() << RHS->getType() << LHS->getSourceRange() << RHS->getSourceRange(); return true; case OR_Ambiguous: Self.Diag(Loc, diag::<API key>) << LHS->getType() << RHS->getType() << LHS->getSourceRange() << RHS->getSourceRange(); // FIXME: Print the possible common types by printing the return types of // the viable candidates. break; case OR_Deleted: assert(false && "Conditional operator has only built-in overloads"); break; } return true; } \brief Perform an "extended" implicit conversion as returned by TryClassUnification. static bool <API key>(Sema &Self, Expr *&E, QualType T) { InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(), SourceLocation()); <API key> InitSeq(Self, Entity, Kind, &E, 1); ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1)); if (Result.isInvalid()) return true; E = Result.takeAs<Expr>(); return false; } \brief Check the operands of ?: under C++ semantics. See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y extension. In this case, LHS == Cond. (But they're not aliases.) QualType Sema::<API key>(Expr *&Cond, Expr *&LHS, Expr *&RHS, SourceLocation QuestionLoc) { // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++ // interface pointers. // C++0x 5.16p1 // The first expression is contextually converted to bool. if (!Cond->isTypeDependent()) { if (<API key>(Cond)) return QualType(); } // Either of the arguments dependent? if (LHS->isTypeDependent() || RHS->isTypeDependent()) return Context.DependentTy; // C++0x 5.16p2 // If either the second or the third operand has type (cv) void, ... QualType LTy = LHS->getType(); QualType RTy = RHS->getType(); bool LVoid = LTy->isVoidType(); bool RVoid = RTy->isVoidType(); if (LVoid || RVoid) { // ... then the [l2r] conversions are performed on the second and third // operands ... <API key>(LHS); <API key>(RHS); LTy = LHS->getType(); RTy = RHS->getType(); // ... and one of the following shall hold: // -- The second or the third operand (but not both) is a throw- // expression; the result is of the type of the other and is an rvalue. bool LThrow = isa<CXXThrowExpr>(LHS); bool RThrow = isa<CXXThrowExpr>(RHS); if (LThrow && !RThrow) return RTy; if (RThrow && !LThrow) return LTy; // -- Both the second and third operands have type void; the result is of // type void and is an rvalue. if (LVoid && RVoid) return Context.VoidTy; // Neither holds, error. Diag(QuestionLoc, diag::<API key>) << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) << LHS->getSourceRange() << RHS->getSourceRange(); return QualType(); } // Neither is void. // C++0x 5.16p3 // Otherwise, if the second and third operand have different types, and // either has (cv) class type, and attempt is made to convert each of those // operands to the other. if (!Context.hasSameType(LTy, RTy) && (LTy->isRecordType() || RTy->isRecordType())) { <API key> ICSLeftToRight, ICSRightToLeft; // These return true if a single direction is already ambiguous. QualType L2RType, R2LType; bool HaveL2R, HaveR2L; if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType)) return QualType(); if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType)) return QualType(); // If both can be converted, [...] the program is ill-formed. if (HaveL2R && HaveR2L) { Diag(QuestionLoc, diag::<API key>) << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange(); return QualType(); } // If exactly one conversion is possible, that conversion is applied to // the chosen operand and the converted operands are used in place of the // original operands for the remainder of this section. if (HaveL2R) { if (<API key>(*this, LHS, L2RType)) return QualType(); LTy = LHS->getType(); } else if (HaveR2L) { if (<API key>(*this, RHS, R2LType)) return QualType(); RTy = RHS->getType(); } } // C++0x 5.16p4 // If the second and third operands are lvalues and have the same type, // the result is of that type [...] bool Same = Context.hasSameType(LTy, RTy); if (Same && LHS->isLvalue(Context) == Expr::LV_Valid && RHS->isLvalue(Context) == Expr::LV_Valid) return LTy; // C++0x 5.16p5 // Otherwise, the result is an rvalue. If the second and third operands // do not have the same type, and either has (cv) class type, ... if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { // ... overload resolution is used to determine the conversions (if any) // to be applied to the operands. If the overload resolution fails, the // program is ill-formed. if (<API key>(*this, LHS, RHS, QuestionLoc)) return QualType(); } // C++0x 5.16p6 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard // conversions are performed on the second and third operands. <API key>(LHS); <API key>(RHS); LTy = LHS->getType(); RTy = RHS->getType(); // After those conversions, one of the following shall hold: // -- The second and third operands have the same type; the result // is of that type. If the operands have class type, the result // is a prvalue temporary of the result type, which is // copy-initialized from either the second operand or the third // operand depending on the value of the first operand. if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) { if (LTy->isRecordType()) { // The operands have class type. Make a temporary copy. InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy); ExprResult LHSCopy = <API key>(Entity, SourceLocation(), Owned(LHS)); if (LHSCopy.isInvalid()) return QualType(); ExprResult RHSCopy = <API key>(Entity, SourceLocation(), Owned(RHS)); if (RHSCopy.isInvalid()) return QualType(); LHS = LHSCopy.takeAs<Expr>(); RHS = RHSCopy.takeAs<Expr>(); } return LTy; } // Extension: conditional operator involving vector types. if (LTy->isVectorType() || RTy->isVectorType()) return CheckVectorOperands(QuestionLoc, LHS, RHS); // -- The second and third operands have arithmetic or enumeration type; // the usual arithmetic conversions are performed to bring them to a // common type, and the result is of that type. if (LTy->isArithmeticType() && RTy->isArithmeticType()) { <API key>(LHS, RHS); return LHS->getType(); } // -- The second and third operands have pointer type, or one has pointer // type and the other is a null pointer constant; pointer conversions // and qualification conversions are performed to bring them to their // composite pointer type. The result is of the composite pointer type. // -- The second and third operands have pointer to member type, or one has // pointer to member type and the other is a null pointer constant; // pointer to member conversions and qualification conversions are // performed to bring them to a common type, whose cv-qualification // shall match the cv-qualification of either the second or the third // operand. The result is of the common type. bool <API key> = false; QualType Composite = <API key>(QuestionLoc, LHS, RHS, isSFINAEContext()? 0 : &<API key>); if (!Composite.isNull()) { if (<API key>) Diag(QuestionLoc, diag::<API key>) << LTy << RTy << Composite << LHS->getSourceRange() << RHS->getSourceRange(); return Composite; } // Similarly, attempt to find composite type of two objective-c pointers. Composite = <API key>(LHS, RHS, QuestionLoc); if (!Composite.isNull()) return Composite; Diag(QuestionLoc, diag::<API key>) << LHS->getType() << RHS->getType() << LHS->getSourceRange() << RHS->getSourceRange(); return QualType(); } \brief Find a merged pointer type and convert the two expressions to it. This finds the composite pointer type (or member pointer type) for @p E1 and @p E2 according to C++0x 5.9p2. It converts both expressions to this type and returns it. It does not emit diagnostics. \param Loc The location of the operator requiring these two expressions to be converted to the composite pointer type. If \p <API key> is non-NULL, then we are permitted to find a non-standard (but still sane) composite type to which both expressions can be converted. When such a type is chosen, \c *<API key> will be set true. QualType Sema::<API key>(SourceLocation Loc, Expr *&E1, Expr *&E2, bool *<API key>) { if (<API key>) *<API key> = false; assert(getLangOptions().CPlusPlus && "This function assumes C++"); QualType T1 = E1->getType(), T2 = E2->getType(); if (!T1->isAnyPointerType() && !T1->isMemberPointerType() && !T2->isAnyPointerType() && !T2->isMemberPointerType()) return QualType(); // C++0x 5.9p2 // Pointer conversions and qualification conversions are performed on // pointer operands to bring them to their composite pointer type. If // one operand is a null pointer constant, the composite pointer type is // the type of the other operand. if (E1-><API key>(Context, Expr::<API key>)) { if (T2->isMemberPointerType()) ImpCastExprToType(E1, T2, <API key>); else ImpCastExprToType(E1, T2, <API key>); return T2; } if (E2-><API key>(Context, Expr::<API key>)) { if (T1->isMemberPointerType()) ImpCastExprToType(E2, T1, <API key>); else ImpCastExprToType(E2, T1, <API key>); return T1; } // Now both have to be pointers or member pointers. if ((!T1->isPointerType() && !T1->isMemberPointerType()) || (!T2->isPointerType() && !T2->isMemberPointerType())) return QualType(); // Otherwise, of one of the operands has type "pointer to cv1 void," then // the other has type "pointer to cv2 T" and the composite pointer type is // "pointer to cv12 void," where cv12 is the union of cv1 and cv2. // Otherwise, the composite pointer type is a pointer type similar to the // type of one of the operands, with a cv-qualification signature that is // the union of the cv-qualification signatures of the operand types. // In practice, the first part here is redundant; it's subsumed by the second. // What we do here is, we build the two possible composite types, and try the // conversions in both directions. If only one works, or if the two composite // types are the same, we have succeeded. // FIXME: extended qualifiers? typedef llvm::SmallVector<unsigned, 4> QualifierVector; QualifierVector QualifierUnion; typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4> <API key>; <API key> MemberOfClass; QualType Composite1 = Context.getCanonicalType(T1), Composite2 = Context.getCanonicalType(T2); unsigned NeedConstBefore = 0; do { const PointerType *Ptr1, *Ptr2; if ((Ptr1 = Composite1->getAs<PointerType>()) && (Ptr2 = Composite2->getAs<PointerType>())) { Composite1 = Ptr1->getPointeeType(); Composite2 = Ptr2->getPointeeType(); // If we're allowed to create a non-standard composite type, keep track // of where we need to fill in additional 'const' qualifiers. if (<API key> && Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) NeedConstBefore = QualifierUnion.size(); QualifierUnion.push_back( Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0)); continue; } const MemberPointerType *MemPtr1, *MemPtr2; if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && (MemPtr2 = Composite2->getAs<MemberPointerType>())) { Composite1 = MemPtr1->getPointeeType(); Composite2 = MemPtr2->getPointeeType(); // If we're allowed to create a non-standard composite type, keep track // of where we need to fill in additional 'const' qualifiers. if (<API key> && Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) NeedConstBefore = QualifierUnion.size(); QualifierUnion.push_back( Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(), MemPtr2->getClass())); continue; } // FIXME: block pointer types? // Cannot unwrap any more types. break; } while (true); if (NeedConstBefore && <API key>) { // Extension: Add 'const' to qualifiers that come before the first qualifier // mismatch, so that our (non-standard!) composite type meets the // requirements of C++ [conv.qual]p4 bullet 3. for (unsigned I = 0; I != NeedConstBefore; ++I) { if ((QualifierUnion[I] & Qualifiers::Const) == 0) { QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const; *<API key> = true; } } } // Rewrap the composites as pointers or member pointers with the union CVRs. <API key>::reverse_iterator MOC = MemberOfClass.rbegin(); for (QualifierVector::reverse_iterator I = QualifierUnion.rbegin(), E = QualifierUnion.rend(); I != E; (void)++I, ++MOC) { Qualifiers Quals = Qualifiers::fromCVRMask(*I); if (MOC->first && MOC->second) { // Rebuild member pointer type Composite1 = Context.<API key>( Context.getQualifiedType(Composite1, Quals), MOC->first); Composite2 = Context.<API key>( Context.getQualifiedType(Composite2, Quals), MOC->second); } else { // Rebuild pointer type Composite1 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals)); Composite2 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals)); } } // Try to convert to the first composite pointer type. InitializedEntity Entity1 = InitializedEntity::InitializeTemporary(Composite1); InitializationKind Kind = InitializationKind::CreateCopy(Loc, SourceLocation()); <API key> E1ToC1(*this, Entity1, Kind, &E1, 1); <API key> E2ToC1(*this, Entity1, Kind, &E2, 1); if (E1ToC1 && E2ToC1) { // Conversion to Composite1 is viable. if (!Context.hasSameType(Composite1, Composite2)) { // Composite2 is a different type from Composite1. Check whether // Composite2 is also viable. InitializedEntity Entity2 = InitializedEntity::InitializeTemporary(Composite2); <API key> E1ToC2(*this, Entity2, Kind, &E1, 1); <API key> E2ToC2(*this, Entity2, Kind, &E2, 1); if (E1ToC2 && E2ToC2) { // Both Composite1 and Composite2 are viable and are different; // this is an ambiguity. return QualType(); } } // Convert E1 to Composite1 ExprResult E1Result = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1)); if (E1Result.isInvalid()) return QualType(); E1 = E1Result.takeAs<Expr>(); // Convert E2 to Composite1 ExprResult E2Result = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1)); if (E2Result.isInvalid()) return QualType(); E2 = E2Result.takeAs<Expr>(); return Composite1; } // Check whether Composite2 is viable. InitializedEntity Entity2 = InitializedEntity::InitializeTemporary(Composite2); <API key> E1ToC2(*this, Entity2, Kind, &E1, 1); <API key> E2ToC2(*this, Entity2, Kind, &E2, 1); if (!E1ToC2 || !E2ToC2) return QualType(); // Convert E1 to Composite2 ExprResult E1Result = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1)); if (E1Result.isInvalid()) return QualType(); E1 = E1Result.takeAs<Expr>(); // Convert E2 to Composite2 ExprResult E2Result = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1)); if (E2Result.isInvalid()) return QualType(); E2 = E2Result.takeAs<Expr>(); return Composite2; } ExprResult Sema::<API key>(Expr *E) { if (!Context.getLangOptions().CPlusPlus) return Owned(E); assert(!isa<<API key>>(E) && "Double-bound temporary?"); const RecordType *RT = E->getType()->getAs<RecordType>(); if (!RT) return Owned(E); // If this is the result of a call or an Objective-C message send expression, // our source might actually be a reference, in which case we shouldn't bind. if (CallExpr *CE = dyn_cast<CallExpr>(E)) { if (CE->getCallReturnType()->isReferenceType()) return Owned(E); } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) { if (const ObjCMethodDecl *MD = ME->getMethodDecl()) { if (MD->getResultType()->isReferenceType()) return Owned(E); } } // That should be enough to guarantee that this type is complete. // If it has a trivial destructor, we can avoid the extra copy. CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); if (RD->isInvalidDecl() || RD-><API key>()) return Owned(E); CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD)); ExprTemporaries.push_back(Temp); if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { <API key>(E->getExprLoc(), Destructor); <API key>(E->getExprLoc(), Destructor, PDiag(diag::<API key>) << E->getType()); } // FIXME: Add the temporary to the temporaries vector. return Owned(<API key>::Create(Context, Temp, E)); } Expr *Sema::<API key>(Expr *SubExpr) { assert(SubExpr && "sub expression can't be null!"); // Check any implicit conversions within the expression. <API key>(SubExpr); unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries; assert(ExprTemporaries.size() >= FirstTemporary); if (ExprTemporaries.size() == FirstTemporary) return SubExpr; Expr *E = <API key>::Create(Context, SubExpr, &ExprTemporaries[FirstTemporary], ExprTemporaries.size() - FirstTemporary); ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary, ExprTemporaries.end()); return E; } ExprResult Sema::<API key>(ExprResult SubExpr) { if (SubExpr.isInvalid()) return ExprError(); return Owned(<API key>(SubExpr.takeAs<Expr>())); } FullExpr Sema::CreateFullExpr(Expr *SubExpr) { unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries; assert(ExprTemporaries.size() >= FirstTemporary); unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary; CXXTemporary **Temporaries = NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary]; FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries); ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary, ExprTemporaries.end()); return E; } ExprResult Sema::<API key>(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &<API key>) { // Since this might be a postfix expression, get rid of ParenListExprs. ExprResult Result = <API key>(S, Base); if (Result.isInvalid()) return ExprError(); Base = Result.get(); QualType BaseType = Base->getType(); <API key> = false; if (BaseType->isDependentType()) { // If we have a pointer to a dependent type and are using the -> operator, // the object type is the type that the pointer points to. We might still // have enough information about that type to do something useful. if (OpKind == tok::arrow) if (const PointerType *Ptr = BaseType->getAs<PointerType>()) BaseType = Ptr->getPointeeType(); ObjectType = ParsedType::make(BaseType); <API key> = true; return Owned(Base); } // C++ [over.match.oper]p8: // [...] When operator->returns, the operator-> is applied to the value // returned, with the original second operand. if (OpKind == tok::arrow) { // The set of types we've considered so far. llvm::SmallPtrSet<CanQualType,8> CTypes; llvm::SmallVector<SourceLocation, 8> Locations; CTypes.insert(Context.getCanonicalType(BaseType)); while (BaseType->isRecordType()) { Result = <API key>(S, Base, OpLoc); if (Result.isInvalid()) return ExprError(); Base = Result.get(); if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base)) Locations.push_back(OpCall->getDirectCallee()->getLocation()); BaseType = Base->getType(); CanQualType CBaseType = Context.getCanonicalType(BaseType); if (!CTypes.insert(CBaseType)) { Diag(OpLoc, diag::<API key>); for (unsigned i = 0; i < Locations.size(); i++) Diag(Locations[i], diag::note_declared_at); return ExprError(); } } if (BaseType->isPointerType()) BaseType = BaseType->getPointeeType(); } // We could end up with various non-record types here, such as extended // vector types or Objective-C interfaces. Just return early and let // <API key> do the work. if (!BaseType->isRecordType()) { // C++ [basic.lookup.classref]p2: // [...] If the type of the object expression is of pointer to scalar // type, the unqualified-id is looked up in the context of the complete // postfix-expression. // This also indicates that we should be parsing a // <API key>. ObjectType = ParsedType(); <API key> = true; return Owned(Base); } // The object type must be complete (or dependent). if (!BaseType->isDependentType() && RequireCompleteType(OpLoc, BaseType, PDiag(diag::<API key>))) return ExprError(); // C++ [basic.lookup.classref]p2: // If the id-expression in a class member access (5.2.5) is an // unqualified-id, and the type of the object expression is of a class // type C (or of pointer to a class type C), the unqualified-id is looked // up in the scope of class C. [...] ObjectType = ParsedType::make(BaseType); return move(Base); } ExprResult Sema::<API key>(SourceLocation NameLoc, Expr *MemExpr) { SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc); Diag(MemExpr->getLocStart(), diag::<API key>) << isa<<API key>>(MemExpr) << FixItHint::CreateInsertion(ExpectedLParenLoc, "()"); return ActOnCallExpr(/*Scope*/ 0, MemExpr, /*LPLoc*/ ExpectedLParenLoc, MultiExprArg(), /*CommaLocs*/ 0, /*RPLoc*/ ExpectedLParenLoc); } ExprResult Sema::<API key>(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeTypeInfo, SourceLocation CCLoc, SourceLocation TildeLoc, <API key> Destructed, bool HasTrailingLParen) { TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); // C++ [expr.pseudo]p2: // The left-hand side of the dot operator shall be of scalar type. The // left-hand side of the arrow operator shall be of pointer to scalar type. // This scalar type is the object type. QualType ObjectType = Base->getType(); if (OpKind == tok::arrow) { if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { ObjectType = Ptr->getPointeeType(); } else if (!Base->isTypeDependent()) { // The user wrote "p->" when she probably meant "p."; fix it. Diag(OpLoc, diag::<API key>) << ObjectType << true << FixItHint::CreateReplacement(OpLoc, "."); if (isSFINAEContext()) return ExprError(); OpKind = tok::period; } } if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) { Diag(OpLoc, diag::<API key>) << ObjectType << Base->getSourceRange(); return ExprError(); } // C++ [expr.pseudo]p2: // [...] The cv-unqualified versions of the object type and of the type // designated by the <API key> shall be the same type. if (DestructedTypeInfo) { QualType DestructedType = DestructedTypeInfo->getType(); SourceLocation DestructedTypeStart = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(); if (!DestructedType->isDependentType() && !ObjectType->isDependentType() && !Context.<API key>(DestructedType, ObjectType)) { Diag(DestructedTypeStart, diag::<API key>) << ObjectType << DestructedType << Base->getSourceRange() << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); // Recover by setting the destructed type to the object type. DestructedType = ObjectType; DestructedTypeInfo = Context.<API key>(ObjectType, DestructedTypeStart); Destructed = <API key>(DestructedTypeInfo); } } // C++ [expr.pseudo]p2: // [...] Furthermore, the two type-names in a <API key> of the // form // ::[opt] <API key>[opt] type-name :: ~ type-name // shall designate the same scalar type. if (ScopeTypeInfo) { QualType ScopeType = ScopeTypeInfo->getType(); if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && !Context.<API key>(ScopeType, ObjectType)) { Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(), diag::<API key>) << ObjectType << ScopeType << Base->getSourceRange() << ScopeTypeInfo->getTypeLoc().getLocalSourceRange(); ScopeType = QualType(); ScopeTypeInfo = 0; } } Expr *Result = new (Context) <API key>(Context, Base, OpKind == tok::arrow, OpLoc, SS.getScopeRep(), SS.getRange(), ScopeTypeInfo, CCLoc, TildeLoc, Destructed); if (HasTrailingLParen) return Owned(Result); return <API key>(Destructed.getLocation(), Result); } ExprResult Sema::<API key>(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName, bool HasTrailingLParen) { assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) && "Invalid first type name in pseudo-destructor"); assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) && "Invalid second type name in pseudo-destructor"); // C++ [expr.pseudo]p2: // The left-hand side of the dot operator shall be of scalar type. The // left-hand side of the arrow operator shall be of pointer to scalar type. // This scalar type is the object type. QualType ObjectType = Base->getType(); if (OpKind == tok::arrow) { if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { ObjectType = Ptr->getPointeeType(); } else if (!ObjectType->isDependentType()) { // The user wrote "p->" when she probably meant "p."; fix it. Diag(OpLoc, diag::<API key>) << ObjectType << true << FixItHint::CreateReplacement(OpLoc, "."); if (isSFINAEContext()) return ExprError(); OpKind = tok::period; } } // Compute the object type that we should use for name lookup purposes. Only // record types and dependent types matter. ParsedType <API key>; if (!SS.isSet()) { if (const Type *T = ObjectType->getAs<RecordType>()) <API key> = ParsedType::make(QualType(T, 0)); else if (ObjectType->isDependentType()) <API key> = ParsedType::make(Context.DependentTy); } // Convert the name of the type being destructed (following the ~) into a // type (with source-location information). QualType DestructedType; TypeSourceInfo *DestructedTypeInfo = 0; <API key> Destructed; if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) { ParsedType T = getTypeName(*SecondTypeName.Identifier, SecondTypeName.StartLocation, S, &SS, true, <API key>); if (!T && ((SS.isSet() && !computeDeclContext(SS, false)) || (!SS.isSet() && ObjectType->isDependentType()))) { // The name of the type being destroyed is a dependent name, and we // couldn't find anything useful in scope. Just store the identifier and // it's location, and we'll perform (qualified) name lookup again at // template instantiation time. Destructed = <API key>(SecondTypeName.Identifier, SecondTypeName.StartLocation); } else if (!T) { Diag(SecondTypeName.StartLocation, diag::<API key>) << SecondTypeName.Identifier << ObjectType; if (isSFINAEContext()) return ExprError(); // Recover by assuming we had the right type all along. DestructedType = ObjectType; } else DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); } else { // Resolve the template-id to a type. <API key> *TemplateId = SecondTypeName.TemplateId; ASTTemplateArgsPtr TemplateArgsPtr(*this, TemplateId->getTemplateArgs(), TemplateId->NumArgs); TypeResult T = ActOnTemplateIdType(TemplateId->Template, TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr, TemplateId->RAngleLoc); if (T.isInvalid() || !T.get()) { // Recover by assuming we had the right type all along. DestructedType = ObjectType; } else DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); } // If we've performed some kind of recovery, (re-)build the type source // information. if (!DestructedType.isNull()) { if (!DestructedTypeInfo) DestructedTypeInfo = Context.<API key>(DestructedType, SecondTypeName.StartLocation); Destructed = <API key>(DestructedTypeInfo); } // Convert the name of the scope type (the type prior to '::') into a type. TypeSourceInfo *ScopeTypeInfo = 0; QualType ScopeType; if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || FirstTypeName.Identifier) { if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) { ParsedType T = getTypeName(*FirstTypeName.Identifier, FirstTypeName.StartLocation, S, &SS, false, <API key>); if (!T) { Diag(FirstTypeName.StartLocation, diag::<API key>) << FirstTypeName.Identifier << ObjectType; if (isSFINAEContext()) return ExprError(); // Just drop this type. It's unnecessary anyway. ScopeType = QualType(); } else ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); } else { // Resolve the template-id to a type. <API key> *TemplateId = FirstTypeName.TemplateId; ASTTemplateArgsPtr TemplateArgsPtr(*this, TemplateId->getTemplateArgs(), TemplateId->NumArgs); TypeResult T = ActOnTemplateIdType(TemplateId->Template, TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr, TemplateId->RAngleLoc); if (T.isInvalid() || !T.get()) { // Recover by dropping this type. ScopeType = QualType(); } else ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); } } if (!ScopeType.isNull() && !ScopeTypeInfo) ScopeTypeInfo = Context.<API key>(ScopeType, FirstTypeName.StartLocation); return <API key>(Base, OpLoc, OpKind, SS, ScopeTypeInfo, CCLoc, TildeLoc, Destructed, HasTrailingLParen); } CXXMemberCallExpr *Sema::<API key>(Expr *Exp, NamedDecl *FoundDecl, CXXMethodDecl *Method) { if (<API key>(Exp, /*Qualifier=*/0, FoundDecl, Method)) assert(0 && "Calling <API key> with invalid call?"); MemberExpr *ME = new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method, SourceLocation(), Method->getType()); QualType ResultType = Method->getCallResultType(); <API key>(Exp->getLocStart(), Method); CXXMemberCallExpr *CE = new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, Exp->getLocEnd()); return CE; } ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) { if (!FullExpr) return ExprError(); return <API key>(FullExpr); }
package net.sf.jasperreports.engine.virtualization; import java.io.IOException; /** * @author Lucian Chirita (lucianc@users.sourceforge.net) */ public class FloatSerializer implements ObjectSerializer<Float> { @Override public int typeValue() { return <API key>.OBJECT_TYPE_FLOAT; } @Override public ReferenceType <API key>() { return ReferenceType.OBJECT; } @Override public boolean <API key>() { return true; } @Override public void write(Float value, <API key> out) throws IOException { out.writeFloat(value); } @Override public Float read(VirtualizationInput in) throws IOException { return in.readFloat(); } }
<?php /** * @see Zend_Session */ require_once 'Zend/Session.php'; /** * @see <API key> */ require_once 'Zend/Controller/Action/Helper/Abstract.php'; class <API key> extends <API key> implements IteratorAggregate, Countable { /** * $_messages - Messages from previous request * * @var array */ static protected $_messages = array(); /** * $_session - Zend_Session storage object * * @var Zend_Session */ static protected $_session = null; /** * $_messageAdded - Wether a message has been previously added * * @var boolean */ static protected $_messageAdded = false; /** * $_namespace - Instance namespace, default is 'default' * * @var string */ protected $_namespace = 'default'; /** * __construct() - Instance constructor, needed to get iterators, etc * * @param string $namespace * @return void */ public function __construct() { if (!self::$_session instanceof <API key>) { self::$_session = new <API key>($this->getName()); foreach (self::$_session as $namespace => $messages) { self::$_messages[$namespace] = $messages; unset(self::$_session->{$namespace}); } } } /** * postDispatch() - runs after action is dispatched, in this * case, it is resetting the namespace in case we have forwarded to a different * action, Flashmessage will be 'clean' (default namespace) * * @return <API key> Provides a fluent interface */ public function postDispatch() { $this->resetNamespace(); return $this; } /** * setNamespace() - change the namespace messages are added to, useful for * per action controller messaging between requests * * @param string $namespace * @return <API key> Provides a fluent interface */ public function setNamespace($namespace = 'default') { $this->_namespace = $namespace; return $this; } /** * resetNamespace() - reset the namespace to the default * * @return <API key> Provides a fluent interface */ public function resetNamespace() { $this->setNamespace(); return $this; } /** * addMessage() - Add a message to flash message * * @param string $message * @return <API key> Provides a fluent interface */ public function addMessage($message) { if (self::$_messageAdded === false) { self::$_session->setExpirationHops(1, null, true); } if (!is_array(self::$_session->{$this->_namespace})) { self::$_session->{$this->_namespace} = array(); } self::$_session->{$this->_namespace}[] = $message; return $this; } /** * hasMessages() - Wether a specific namespace has messages * * @return boolean */ public function hasMessages() { return isset(self::$_messages[$this->_namespace]); } /** * getMessages() - Get messages from a specific namespace * * @return array */ public function getMessages() { if ($this->hasMessages()) { return self::$_messages[$this->_namespace]; } return array(); } /** * Clear all messages from the previous request & current namespace * * @return boolean True if messages were cleared, false if none existed */ public function clearMessages() { if ($this->hasMessages()) { unset(self::$_messages[$this->_namespace]); return true; } return false; } /** * hasCurrentMessages() - check to see if messages have been added to current * namespace within this request * * @return boolean */ public function hasCurrentMessages() { return isset(self::$_session->{$this->_namespace}); } /** * getCurrentMessages() - get messages that have been added to the current * namespace within this request * * @return array */ public function getCurrentMessages() { if ($this->hasCurrentMessages()) { return self::$_session->{$this->_namespace}; } return array(); } /** * clear messages from the current request & current namespace * * @return boolean */ public function <API key>() { if ($this->hasCurrentMessages()) { unset(self::$_session->{$this->_namespace}); return true; } return false; } /** * getIterator() - complete the IteratorAggregate interface, for iterating * * @return ArrayObject */ public function getIterator() { if ($this->hasMessages()) { return new ArrayObject($this->getMessages()); } return new ArrayObject(); } /** * count() - Complete the countable interface * * @return int */ public function count() { if ($this->hasMessages()) { return count($this->getMessages()); } return 0; } /** * Strategy pattern: proxy to addMessage() * * @param string $message * @return void */ public function direct($message) { return $this->addMessage($message); } }
#exploderLightPanel{ position: absolute; width: 90%; margin-left: 5%; height: 90%; margin-top: 5%; background-color: white; z-index: 999; padding: 2em; } .level{ }
package com.ouser.module; import java.util.HashMap; import java.util.Map; import com.ouser.util.StringUtil; import android.os.Bundle; /** * * @author hanlixin * */ public class Photo { public enum Size { Small(80, 0), Normal(100, 1), /** profile */ Large(134, 2), XLarge(640, 3); private int size = 0; private int key = 0; Size(int size, int key) { this.size = size; this.key = key; } public int getSize() { return size; } int getKey() { return key; } static Size fromKey(int key) { for(Size s : Size.values()) { if(s.getKey() == key) { return s; } } return null; } } private String url = ""; private int resId = 0; private Map<Size, String> paths = new HashMap<Size, String>(); private Map<Size, Integer> tryTimes = new HashMap<Size, Integer>(); public String getUrl() { return url; } public void setUrl(String url) { this.url = url; this.tryTimes.clear(); } public int getResId() { return resId; } public void setResId(int res) { this.resId = res; } public void setPath(String path, Size size) { paths.put(size, path); } public String getPath(Size size) { if(paths.containsKey(size)) { return paths.get(size); } return ""; } public void setTryTime(int value, Size size) { tryTimes.put(size, value); } public int getTryTime(Size size) { if(tryTimes.containsKey(size)) { return tryTimes.get(size); } return 0; } public boolean isEmpty() { return StringUtil.isEmpty(url) && resId == 0; } public boolean isSame(Photo p) { return p.url.equals(this.url) || ( this.resId != 0 && p.resId == this.resId); } public Bundle toBundle() { StringBuilder sbPath = new StringBuilder(); for(Map.Entry<Size, String> entry : paths.entrySet()) { sbPath.append(entry.getKey().getKey()).append(":").append(entry.getValue()).append(";"); } StringBuilder sbTryTime = new StringBuilder(); for(Map.Entry<Size, Integer> entry : tryTimes.entrySet()) { sbPath.append(entry.getKey().getKey()).append(":").append(entry.getValue()).append(";"); } Bundle bundle = new Bundle(); bundle.putString("url", url); bundle.putInt("resid", resId); bundle.putString("path", sbPath.toString()); bundle.putString("trytime", sbTryTime.toString()); return bundle; } public void fromBundle(Bundle bundle) { url = bundle.getString("url"); resId = bundle.getInt("resid"); String strPath = bundle.getString("path"); String strTryTime = bundle.getString("trytime"); this.paths.clear(); for(String str : strPath.split(";")) { if("".equals(str)) { continue; } String[] values = str.split(":"); this.paths.put(Size.fromKey(Integer.parseInt(values[0])), values[1]); } this.tryTimes.clear(); for(String str : strTryTime.split(";")) { if("".equals(str)) { continue; } String[] values = str.split(":"); this.tryTimes.put(Size.fromKey(Integer.parseInt(values[0])), Integer.parseInt(values[1])); } } }
package bdv.server; import bdv.db.UserController; import bdv.model.DataSet; import bdv.util.Render; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.<API key>; import org.eclipse.jetty.util.log.Log; import org.stringtemplate.v4.ST; import org.stringtemplate.v4.STGroup; import org.stringtemplate.v4.STRawGroupDir; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.net.URISyntaxException; import java.security.Principal; import java.util.List; import java.util.stream.Collectors; public class UserPageHandler extends BaseContextHandler { private static final org.eclipse.jetty.util.log.Logger LOG = Log.getLogger( UserPageHandler.class ); UserPageHandler( final Server server, final <API key> <API key>, final <API key> <API key>, final String <API key> ) throws IOException, URISyntaxException { super( server, <API key>, <API key>, <API key> );
package jmash; import jmash.interfaces.XmlAble; import org.apache.log4j.Logger; import org.jdom.Element; /** * * @author Alessandro */ public class YeastType implements XmlAble { private static Logger LOGGER = Logger.getLogger(YeastType.class); /** Creates a new instance of YeastType */ public YeastType() { } private String nome; private String codice; private String produttore; private String forma; private String categoria; private String descrizione; private String attenuazioneMed; private String attenuazioneMin; private String attenuazioneMax; private String temperaturaMin; private String temperaturaMax; private String temperaturaMaxFerm; private static String campiXml[] = { "nome", "codice", "produttore", "forma", "categoria", "attenuazioneMed", "attenuazioneMin", "attenuazioneMax", "temperaturaMin", "temperaturaMax", "descrizione"}; public String getNome() { return this.nome; } public void setNome(String nome) { this.nome = nome; } public String getCodice() { return this.codice; } public void setCodice(String codice) { this.codice = codice; } public String getProduttore() { return this.produttore; } public void setProduttore(String produttore) { this.produttore = produttore; } public String getForma() { return this.forma; } public void setForma(String forma) { this.forma = forma; } public String getCategoria() { return this.categoria; } public void setCategoria(String categoria) { this.categoria = categoria; } public String getDescrizione() { return this.descrizione; } public void setDescrizione(String descrizione) { this.descrizione = descrizione; } public String getAttenuazioneMin() { return this.attenuazioneMin; } public void setAttenuazioneMin(String attenuazioneMin) { this.attenuazioneMin = attenuazioneMin; } public String getAttenuazioneMax() { return this.attenuazioneMax; } public void setAttenuazioneMax(String attenuazioneMax) { this.attenuazioneMax = attenuazioneMax; } public String getTemperaturaMin() { return this.temperaturaMin; } public void setTemperaturaMin(String temperaturaMin) { this.temperaturaMin = temperaturaMin; } public String getTemperaturaMax() { return this.temperaturaMax; } public void setTemperaturaMax(String temperaturaMax) { this.temperaturaMax = temperaturaMax; } public String getAttenuazioneMed() { if (attenuazioneMed != null && !"".equals(attenuazioneMed)) { return this.attenuazioneMed; } else if (getAttenuazioneMin() != null && !"".equals(getAttenuazioneMin()) && getAttenuazioneMax() != null && !"".equals(getAttenuazioneMax())) { return (String.valueOf((Integer.valueOf(getAttenuazioneMin())+Integer.valueOf(getAttenuazioneMax()))/2)); } return this.attenuazioneMed; } public void setAttenuazioneMed(String attenuazioneMed) { this.attenuazioneMed = attenuazioneMed; } public String <API key>() { return temperaturaMaxFerm; } public void <API key>(String temperaturaMaxFerm) { this.temperaturaMaxFerm = temperaturaMaxFerm; } public static String[] getCampiXml() { return campiXml; } public static void setCampiXml(String[] aCampiXml) { campiXml = aCampiXml; } @Override public Element toXml() { try { return Utils.toXml(this, campiXml); } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex); } return null; } @Override public String getTag() { return "yeasts"; } @Override public String[] getXmlFields() { return campiXml; } }
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>FastaPlus: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> </head> <body> <div id="top"><!-- do not remove this div! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">FastaPlus &#160;<span id="projectnumber">0.01</span> </div> <div id="projectbrief">by Robert Bakaric</div> </td> </tr> </tbody> </table> </div> <!-- Generated by Doxygen 1.7.6.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacefasta.html">fasta</a> </li> <li class="navelem"><a class="el" href="<API key>.html">XnuScores</a> </li> </ul> </div> </div> <div class="header"> <div class="headertitle"> <div class="title">fasta::XnuScores Member List</div> </div> </div><!--header <div class="contents"> This is the complete list of members for <a class="el" href="<API key>.html">fasta::XnuScores</a>, including all inherited members.<table> <tr class="memlist"><td><a class="el" href="<API key>.html#<API key>">Alphabet</a></td><td><a class="el" href="<API key>.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="<API key>.html#<API key>">Blast</a></td><td><a class="el" href="<API key>.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="<API key>.html#<API key>">Dayhoff</a></td><td><a class="el" href="<API key>.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="<API key>.html#<API key>">Lambda120</a></td><td><a class="el" href="<API key>.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="<API key>.html#<API key>">Lambda250</a></td><td><a class="el" href="<API key>.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="<API key>.html#<API key>">Lambda60</a></td><td><a class="el" href="<API key>.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="<API key>.html#<API key>">M</a></td><td><a class="el" href="<API key>.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="<API key>.html#<API key>">Pam120</a></td><td><a class="el" href="<API key>.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="<API key>.html#<API key>">Pam250</a></td><td><a class="el" href="<API key>.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="<API key>.html#<API key>">Pam60</a></td><td><a class="el" href="<API key>.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="<API key>.html#<API key>">XnuScores</a>()</td><td><a class="el" href="<API key>.html">fasta::XnuScores</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="<API key>.html#<API key>">~XnuScores</a>()</td><td><a class="el" href="<API key>.html">fasta::XnuScores</a></td><td><code> [inline]</code></td></tr> </table></div><!-- contents --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Namespaces</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Variables</a></div> <!-- iframe showing the search results (closed by default) --> <div id="<API key>"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <hr class="footer"/><address class="footer"><small> Generated on Mon Nov 9 2015 20:13:47 for FastaPlus by & <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.7.6.1 </small></address> </body> </html>
#include "<API key>.h" #include <cstdlib> #include <cutils/log.h> #include <fcntl.h> #include <xf86drm.h> uint64_t <API key>(int flags) { uint64_t usage = DRV_BO_USE_NONE; if (flags & <API key>) usage |= DRV_BO_USE_CURSOR; if ((flags & sw_read()) == <API key>) usage |= <API key>; if ((flags & sw_read()) == <API key>) usage |= <API key>; if ((flags & sw_write()) == <API key>) usage |= <API key>; if ((flags & sw_write()) == <API key>) usage |= <API key>; if (flags & <API key>) usage |= <API key>; if (flags & <API key>) usage |= <API key>; if (flags & GRALLOC_USAGE_HW_2D) usage |= <API key>; if (flags & <API key>) /* HWC wants to use display hardware, but can defer to OpenGL. */ usage |= DRV_BO_USE_SCANOUT | <API key>; if (flags & GRALLOC_USAGE_HW_FB) usage |= DRV_BO_USE_SCANOUT; if (flags & <API key>) /* We're ignoring this flag until we decide what to with display link */ usage |= DRV_BO_USE_NONE; if (flags & <API key>) usage |= <API key>; if (flags & <API key>) /*HACK: See b/30054495 */ usage |= <API key>; if (flags & <API key>) usage |= <API key>; if (flags & <API key>) usage |= <API key>; if (flags & <API key>) usage |= <API key>; if (flags & <API key>) usage |= <API key>; return usage; } drv_format_t <API key>(int format) { /* * Conversion from HAL to fourcc-based DRV formats based on * platform_android.c in mesa. */ switch (format) { case <API key>: return DRV_FORMAT_ARGB8888; case <API key>: return <API key>; case <API key>: return DRV_FORMAT_RGB565; case <API key>: return DRV_FORMAT_RGB888; case <API key>: return DRV_FORMAT_ABGR8888; case <API key>: return DRV_FORMAT_XBGR8888; case <API key>: return <API key>; case <API key>: return DRV_FORMAT_YVU420; } return DRV_FORMAT_NONE; } static int32_t <API key>(struct driver **drv, const char *name) { /* TODO(gsingh): Enable render nodes on udl/evdi. */ int fd; drmVersionPtr version; char const *str = "%s/renderD%d"; int32_t num_nodes = 63; int32_t min_node = 128; int32_t max_node = (min_node + num_nodes); for (int i = min_node; i < max_node; i++) { char *node; if (asprintf(&node, str, DRM_DIR_NAME, i) < 0) continue; fd = open(node, O_RDWR, 0); free(node); if (fd < 0) continue; version = drmGetVersion(fd); if (version && name && !strcmp(version->name, name)) { drmFreeVersion(version); continue; } drmFreeVersion(version); *drv = drv_create(fd); if (*drv) return <API key>; } return <API key>; } int32_t <API key>(struct driver **drv) { int32_t ret; ret = <API key>(drv, NULL); /* Look for vgem driver if no hardware is found. */ if (ret) ret = <API key>(drv, "vgem"); return ret; } int32_t <API key>(struct cros_gralloc_handle *hnd) { if (!hnd || hnd->magic != cros_gralloc_magic()) return <API key>; return <API key>; } void cros_gralloc_log(const char *prefix, const char *file, int line, const char *format, ...) { va_list args; va_start(args, format); ALOGE("%s - [%s(%d)]", prefix, basename(file), line); <API key>(ANDROID_LOG_ERROR, prefix, format, args); va_end(args); }
// This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the import React, { Component, PropTypes } from 'react'; import { observer } from 'mobx-react'; import { Button, GasPriceEditor } from '~/ui'; import <API key> from '../<API key>'; import <API key> from '../<API key>'; import styles from './transactionPending.css'; import * as tUtil from '../util/transaction'; @observer export default class TransactionPending extends Component { static contextTypes = { api: PropTypes.object.isRequired }; static propTypes = { className: PropTypes.string, date: PropTypes.instanceOf(Date).isRequired, focus: PropTypes.bool, gasLimit: PropTypes.object, id: PropTypes.object.isRequired, isSending: PropTypes.bool.isRequired, isTest: PropTypes.bool.isRequired, nonce: PropTypes.number, onConfirm: PropTypes.func.isRequired, onReject: PropTypes.func.isRequired, store: PropTypes.object.isRequired, transaction: PropTypes.shape({ data: PropTypes.string, from: PropTypes.string.isRequired, gas: PropTypes.object.isRequired, gasPrice: PropTypes.object.isRequired, to: PropTypes.string, value: PropTypes.object.isRequired }).isRequired }; static defaultProps = { focus: false }; gasStore = new GasPriceEditor.Store(this.context.api, { gas: this.props.transaction.gas.toFixed(), gasLimit: this.props.gasLimit, gasPrice: this.props.transaction.gasPrice.toFixed() }); componentWillMount () { const { store, transaction } = this.props; const { from, gas, gasPrice, to, value } = transaction; const fee = tUtil.getFee(gas, gasPrice); // BigNumber object const gasPriceEthmDisplay = tUtil.<API key>(gasPrice); const gasToDisplay = tUtil.getGasDisplay(gas); const totalValue = tUtil.getTotalValue(fee, value); this.setState({ gasPriceEthmDisplay, totalValue, gasToDisplay }); this.gasStore.setEthValue(value); store.fetchBalances([from, to]); } render () { return this.gasStore.isEditing ? this.renderGasEditor() : this.renderTransaction(); } renderTransaction () { const { className, focus, id, isSending, isTest, store, transaction } = this.props; const { totalValue } = this.state; const { from, value } = transaction; const fromBalance = store.balances[from]; return ( <div className={ `${styles.container} ${className}` }> <<API key> className={ styles.transactionDetails } from={ from } fromBalance={ fromBalance } gasStore={ this.gasStore } id={ id } isTest={ isTest } totalValue={ totalValue } transaction={ transaction } value={ value } /> <<API key> address={ from } focus={ focus } isSending={ isSending } onConfirm={ this.onConfirm } onReject={ this.onReject } /> </div> ); } renderGasEditor () { const { className } = this.props; return ( <div className={ `${styles.container} ${className}` }> <GasPriceEditor store={ this.gasStore }> <Button label='view transaction' onClick={ this.toggleGasEditor } /> </GasPriceEditor> </div> ); } onConfirm = (data) => { const { id, transaction } = this.props; const { password, wallet } = data; const { gas, gasPrice } = this.gasStore.overrideTransaction(transaction); this.props.onConfirm({ gas, gasPrice, id, password, wallet }); } onReject = () => { this.props.onReject(this.props.id); } toggleGasEditor = () => { this.gasStore.setEditing(false); } }
from controllers.job_ctrl import JobController from models.job_model import JobModel from views.job_view import JobView class MainController(object): def __init__(self, main_model): self.main_view = None self.main_model = main_model self.main_model.begin_job_fetch.connect(self.on_begin_job_fetch) self.main_model.<API key>.connect(self.on_job_fetch_update) self.main_model.fetched_job.connect(self.on_fetched_job) def init_ui(self, main_view): self.main_view = main_view self.init_hotkeys() def init_hotkeys(self): self.main_model.hotkey_model.add_hotkey(["Lcontrol", "Lmenu", "J"], self.main_view.focus_job_num_edit) self.main_model.hotkey_model.add_hotkey(["Lcontrol", "Lmenu", "O"], self.main_view.<API key>) self.main_model.hotkey_model.add_hotkey(["Lcontrol", "Lmenu", "B"], self.main_view.<API key>) self.main_model.hotkey_model.start_detection() def fetch_job(self): job_num = self.main_view.job_num if self.main_model.job_exists(job_num): self.main_view.<API key>() return self.main_model.fetch_job(job_num) def cancel_job_fetch(self): self.main_model.cancel_job_fetch() def on_begin_job_fetch(self, max): self.main_view.<API key>(max) def on_job_fetch_update(self, progress): self.main_view.<API key>(progress) def on_fetched_job(self, job_num, base_folder): job = JobModel(job_num, base_folder, self.main_model.settings_model.basecamp_email, self.main_model.settings_model.basecamp_password, self.main_model.settings_model.<API key>, self.main_model.settings_model.<API key>, self.main_model.settings_model.<API key>, self.main_model.settings_model.scene_exe_path) self.main_model.jobs[job.job_num] = job found = bool(job.base_folder) self.main_view.<API key>() if not found: open_anyway = self.main_view.<API key>() if not open_anyway: return job_view = JobView(JobController(job)) job_view.request_minimize.connect(self.main_view.close) self.main_view.add_tab(job_view, job.job_name) def remove_job(self, index): job_num = int(self.main_view.ui.jobs_tab_widget.tabText(index)[1:]) self.main_model.jobs.pop(job_num, None) self.main_view.remove_tab(index)
<?php namespace ModulusAcl\Form; use ModulusForm\Form\FormDefault, Zend\Form\Element\Select; class Route extends FormDefault { public function addElements() { $this->add(array( 'name' => 'id', 'options' => array( 'label' => '', ), 'attributes' => array( 'type' => 'hidden' ), )); $this->add(array( 'name' => 'route', 'options' => array( 'label' => 'Rota: ', 'value_options' => array( ), ), 'type' => 'Zend\Form\Element\Select', 'attributes' => array( 'placeholder' => 'Selecione a url', ), )); $this->add(array( 'name' => 'displayName', 'options' => array( 'label' => 'Nome de exibição: ', ), 'type' => 'Zend\Form\Element\Text', 'attributes' => array( 'placeholder' => 'Entre com o nome', ), )); $this->add(array( 'type' => 'DoctrineModule\Form\Element\ObjectSelect', 'name' => 'role', 'options' => array( 'label' => 'Tipo de usuário: ', 'object_manager' => $this->getEntityManager(), 'target_class' => 'ModulusAcl\Entity\AclRole', 'find_method' => array( 'name' => 'findByActives', 'params' => array('criteria' => array()), ), 'property' => 'name', 'selected' =>1, 'empty_option' => '', ), )); $this->add(array( 'type' => 'ModulusForm\Form\Element\Toggle', 'name' => 'doLog', 'options' => array( 'label' => 'Log ao acessar? ', ), )); $this->add(new \Zend\Form\Element\Csrf('security')); $this->add(array( 'name' => 'submit', 'attributes' => array( 'value' => 'Salvar', 'type' => 'submit', 'class' => 'btn btn-primary', ), )); } }
package edu.stanford.nlp.mt.lm; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReentrantLock; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import edu.stanford.nlp.mt.util.IString; import edu.stanford.nlp.mt.util.Sequence; import edu.stanford.nlp.mt.util.TokenUtils; import edu.stanford.nlp.mt.util.Vocabulary; /** * KenLM language model support via JNI. * * @author daniel cer * @author Spence Green * @author Kenneth Heafield * */ public class KenLanguageModel implements LanguageModel<IString> { private static final Logger logger = LogManager.getLogger(KenLanguageModel.class.getName()); private static final int[] EMPTY_INT_ARRAY = new int[0]; private static final KenLMState ZERO_LENGTH_STATE = new KenLMState(0.0f, EMPTY_INT_ARRAY, 0); public static final String KENLM_LIBRARY_NAME = "PhrasalKenLM"; static { try { System.loadLibrary(KENLM_LIBRARY_NAME); logger.info("Loaded KenLM JNI library."); } catch (java.lang.<API key> e) { logger.fatal("KenLM has not been compiled!", e); System.exit(-1); } } private final KenLM model; private final String name; private AtomicReference<int[]> istringIdToKenLMId; private final ReentrantLock <API key> = new ReentrantLock(); /** * Constructor for multi-threaded queries. * * @param filename */ public KenLanguageModel(String filename) { model = new KenLM(filename); name = String.format("KenLM(%s)", filename); initializeIdTable(); } /** * Create the mapping between IString word ids and KenLM word ids. */ private void initializeIdTable() { // Don't remove this line!! Sanity check to make sure that start and end load before // building the index. logger.info("Special tokens: start: {} end: {}", TokenUtils.START_TOKEN, TokenUtils.END_TOKEN); int[] table = new int[Vocabulary.systemSize()]; for (int i = 0; i < table.length; ++i) { table[i] = model.index(Vocabulary.systemGet(i)); } istringIdToKenLMId = new AtomicReference<int[]>(table); } /** * Maps the IString id to a kenLM id. If the IString * id is out of range, update the vocab mapping. * @param token * @return kenlm id of the string */ private int toKenLMId(IString token) { { int[] map = istringIdToKenLMId.get(); if (token.id < map.length) { return map[token.id]; } } // Rare event: we have to expand the vocabulary. // In principle, this doesn't need to be a lock, but it does // prevent unnecessary work duplication. if (<API key>.tryLock()) { // This thread is responsible for updating the mapping. try { // Maybe another thread did the work for us? int[] oldTable = istringIdToKenLMId.get(); if (token.id < oldTable.length) { return oldTable[token.id]; } int[] newTable = new int[Vocabulary.systemSize()]; System.arraycopy(oldTable, 0, newTable, 0, oldTable.length); for (int i = oldTable.length; i < newTable.length; ++i) { newTable[i] = model.index(Vocabulary.systemGet(i)); } istringIdToKenLMId.set(newTable); return newTable[token.id]; } finally { <API key>.unlock(); } } // Another thread is working. Lookup directly. return model.index(token.toString()); } @Override public IString getStartToken() { return TokenUtils.START_TOKEN; } @Override public IString getEndToken() { return TokenUtils.END_TOKEN; } @Override public String getName() { return name; } @Override public int order() { return model.order(); } @Override public LMState score(Sequence<IString> sequence, int startIndex, LMState priorState) { if (sequence.size() == 0) { // Source deletion rule return priorState == null ? ZERO_LENGTH_STATE : priorState; } // Extract prior state final int[] state = priorState == null ? EMPTY_INT_ARRAY : ((KenLMState) priorState).getState(); final int[] ngramIds = makeKenLMInput(sequence, state); if (sequence.size() == 1 && priorState == null && sequence.get(0).equals(TokenUtils.START_TOKEN)) { // Special case: Source deletion rule (e.g., from the OOV model) at the start of a string assert ngramIds.length == 1; return new KenLMState(0.0f, ngramIds, ngramIds.length); } // Reverse the start index for KenLM final int kenLMStartIndex = ngramIds.length - state.length - startIndex - 1; assert kenLMStartIndex >= 0; // Execute the query (via JNI) and construct the return state final long got = model.scoreSeqMarshalled(ngramIds, kenLMStartIndex); return new KenLMState(KenLM.scoreFromMarshalled(got), ngramIds, KenLM.<API key>(got)); } /** * Convert a Sequence and an optional state to an input for KenLM. * * @param sequence * @param priorState * @return */ private int[] makeKenLMInput(Sequence<IString> sequence, int[] priorState) { final int sequenceSize = sequence.size(); int[] ngramIds = new int[sequenceSize + priorState.length]; if (priorState.length > 0) { System.arraycopy(priorState, 0, ngramIds, sequenceSize, priorState.length); } for (int i = 0; i < sequenceSize; i++) { // Notice: ngramids are in reverse order vv. the Sequence ngramIds[sequenceSize-1-i] = toKenLMId(sequence.get(i)); } return ngramIds; } // TODO(spenceg) This never yielded an improvement.... // private static final int DEFAULT_CACHE_SIZE = 10000; // private static final ThreadLocal<KenLMCache> threadLocalCache = // new ThreadLocal<KenLMCache>(); // private static class KenLMCache { // private final long[] keys; // private final long[] values; // private final int mask; // public KenLMCache(int size) { // this.keys = new long[size]; // this.values = new long[size]; // this.mask = size - 1; // public Long get(int[] kenLMInput, int startIndex) { // long hashValue = MurmurHash2.hash64(kenLMInput, kenLMInput.length, startIndex); // int k = ideal(hashValue); // return keys[k] == hashValue ? values[k] : null; // private int ideal(long hashed) { // return ((int)hashed) & mask; // public void insert(int[] kenLMInput, int startIndex, long value) { // long hashValue = MurmurHash2.hash64(kenLMInput, kenLMInput.length, startIndex); // int k = ideal(hashValue); // keys[k] = hashValue; // values[k] = value; }
// Decompiled with JetBrains decompiler // Type: System.Xml.Linq.BaseUriAnnotation // Assembly: System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKey<API key> // MVID: <API key> // Assembly location: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5\System.Xml.Linq.dll namespace System.Xml.Linq { internal class BaseUriAnnotation { internal string baseUri; public BaseUriAnnotation(string baseUri) { this.baseUri = baseUri; } } }
#!/usr/bin/python # Problem: Making Chess Boards # Language: Python # Usage: python thisfile.py <input.in >output.out from heapq import * def process(r1, r2, c1, c2): for i in range(r1, r2): for j in range(c1, c2): if 0 <= i < m and 0 <= j < n: if g[i][j] == None: s[i][j] = 0 elif i == 0 or j == 0: s[i][j] = 1 elif g[i-1][j] != g[i][j] and g[i][j-1] != g[i][j] and \ g[i-1][j-1] == g[i][j]: s[i][j] = 1 + min(s[i-1][j], s[i][j-1], s[i-1][j-1]) else: s[i][j] = 1 heappush(q, (-s[i][j], i, j)) def clear(r1, r2, c1, c2): for i in range(r1, r2): for j in range(c1, c2): if 0 <= i < m and 0 <= j < n: g[i][j] = None for case in range(int(raw_input())): m, n = map(int, raw_input().split()) v = [eval('0x'+raw_input()) for i in range(m)] g = map(lambda x: map(lambda y: (x>>y)%2, range(n)[::-1]), v) s = [[1 for i in range(n)] for j in range(m)] q = [] process(0, m, 0, n) b = [] while q: x, r, c = heappop(q) if x != 0 and s[r][c] == -x: b.append((-x, r, c)) clear(r+x+1, r+1, c+x+1, c+1) process(r+x+1, r-x+1, c+x+1, c-x+1) vs = sorted(list(set(map(lambda x: x[0], b))))[::-1] print "Case #%d: %d" % (case+1, len(vs)) for k in vs: print k, len(filter(lambda x: x[0] == k, b))
package appalachia.rtg.world.biome.realistic.appalachia.adirondack; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.world.biome.Biome; import net.minecraft.world.chunk.ChunkPrimer; import appalachia.api.AppalachiaBiomes; import rtg.api.config.BiomeConfig; import rtg.api.util.BlockUtil; import rtg.api.util.CliffCalculator; import rtg.api.util.noise.OpenSimplexNoise; import rtg.api.world.IRTGWorld; import rtg.api.world.surface.SurfaceBase; import rtg.api.world.terrain.TerrainBase; public class <API key> extends <API key> { public static Biome biome = AppalachiaBiomes.adirondackBeach; public static Biome river = AppalachiaBiomes.adirondackRiver; public <API key>() { super(biome, river); } @Override public void initConfig() { this.getConfig().addProperty(this.getConfig().SURFACE_MIX_BLOCK).set(""); this.getConfig().addProperty(this.getConfig().<API key>).set(0); } @Override public TerrainBase initTerrain() { return new <API key>(); } @Override public SurfaceBase initSurface() { return new <API key>(config, biome.topBlock, biome.fillerBlock, BlockUtil.getStateDirt(2), 12f, 0.27f); } public class <API key> extends SurfaceBase { protected IBlockState mixBlock; protected float width; protected float height; public <API key>(BiomeConfig config, IBlockState top, IBlockState filler, IBlockState mix, float mixWidth, float mixHeight) { super(config, top, filler); mixBlock = this.getConfigBlock(config.SURFACE_MIX_BLOCK.get(), config.<API key>.get(), mix); width = mixWidth; height = mixHeight; } @Override public void paintTerrain(ChunkPrimer primer, int i, int j, int x, int z, int depth, IRTGWorld rtgWorld, float[] noise, float river, Biome[] base) { Random rand = rtgWorld.rand(); OpenSimplexNoise simplex = rtgWorld.simplex(); float c = CliffCalculator.calc(x, z, noise); boolean cliff = c > 2.3f ? true : false; // 2.3f because higher thresholds result in fewer stone cliffs (more grassy cliffs) for (int k = 255; k > -1; k Block b = primer.getBlockState(x, k, z).getBlock(); if (b == Blocks.AIR) { depth = -1; } else if (b == Blocks.STONE) { depth++; if (cliff) { if (depth > -1 && depth < 2) { if (rand.nextInt(3) == 0) { primer.setBlockState(x, k, z, hcCobble(rtgWorld, i, j, x, z, k)); } else { primer.setBlockState(x, k, z, hcStone(rtgWorld, i, j, x, z, k)); } } else if (depth < 10) { primer.setBlockState(x, k, z, hcStone(rtgWorld, i, j, x, z, k)); } } else { if (depth == 0 && k > 61) { if (simplex.noise2(i / width, j / width) > height) // > 0.27f, i / 12f { primer.setBlockState(x, k, z, mixBlock); } else { primer.setBlockState(x, k, z, topBlock); } } else if (depth < 4) { primer.setBlockState(x, k, z, fillerBlock); } } } } } } @Override public void initDecos() { } public class <API key> extends TerrainBase { public <API key>() { } @Override public float generateNoise(IRTGWorld rtgWorld, int x, int y, float border, float river) { return terrainBeach(x, y, rtgWorld.simplex(), river, 180f, 35f, 63f); } } }
// Decompiled with JetBrains decompiler // Type: System.Boolean // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKey<API key> // MVID: <API key> // Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll using System.Runtime.InteropServices; namespace System { <summary> Represents a Boolean value. </summary> <filterpriority>1</filterpriority> [ComVisible(true)] [<API key>] [Serializable] public struct Boolean : IComparable, IConvertible, IComparable<bool>, IEquatable<bool> { <summary> Represents the Boolean value true as a string. This field is read-only. </summary> <filterpriority>1</filterpriority> [<API key>] public static readonly string TrueString = "True"; <summary> Represents the Boolean value false as a string. This field is read-only. </summary> <filterpriority>1</filterpriority> [<API key>] public static readonly string FalseString = "False"; internal const int True = 1; internal const int False = 0; internal const string TrueLiteral = "True"; internal const string FalseLiteral = "False"; private bool m_value; <summary> Returns the hash code for this instance. </summary> <returns> A hash code for the current <see cref="T:System.Boolean"/>. </returns> <filterpriority>2</filterpriority> [<API key>] public override int GetHashCode() { return !this ? 0 : 1; } <summary> Converts the value of this instance to its equivalent string representation (either "True" or "False"). </summary> <returns> <see cref="F:System.Boolean.TrueString"/> if the value of this instance is true, or <see cref="F:System.Boolean.FalseString"/> if the value of this instance is false. </returns> <filterpriority>2</filterpriority> [<API key>] public override string ToString() { return !this ? "False" : "True"; } <summary> Converts the value of this instance to its equivalent string representation (either "True" or "False"). </summary> <returns> <see cref="F:System.Boolean.TrueString"/> if the value of this instance is true, or <see cref="F:System.Boolean.FalseString"/> if the value of this instance is false. </returns> <param name="provider">(Reserved) An <see cref="T:System.IFormatProvider"/> object. </param><filterpriority>2</filterpriority> public string ToString(IFormatProvider provider) { return !this ? "False" : "True"; } <summary> Returns a value indicating whether this instance is equal to a specified object. </summary> <returns> true if <paramref name="obj"/> is a <see cref="T:System.Boolean"/> and has the same value as this instance; otherwise, false. </returns> <param name="obj">An object to compare to this instance. </param><filterpriority>2</filterpriority> [<API key>] public override bool Equals(object obj) { if (!(obj is bool)) return false; return this == (bool) obj; } <summary> Returns a value indicating whether this instance is equal to a specified <see cref="T:System.Boolean"/> object. </summary> <returns> true if <paramref name="obj"/> has the same value as this instance; otherwise, false. </returns> <param name="obj">A <see cref="T:System.Boolean"/> value to compare to this instance.</param><filterpriority>2</filterpriority> [<API key>] public bool Equals(bool obj) { return this == obj; } <summary> Compares this instance to a specified object and returns an integer that indicates their relationship to one another. </summary> <returns> A signed integer that indicates the relative order of this instance and <paramref name="obj"/>.Return Value Condition Less than zero This instance is false and <paramref name="obj"/> is true. Zero This instance and <paramref name="obj"/> are equal (either both are true or both are false). Greater than zero This instance is true and <paramref name="obj"/> is false.-or- <paramref name="obj"/> is null. </returns> <param name="obj">An object to compare to this instance, or null. </param><exception cref="T:System.ArgumentException"><paramref name="obj"/> is not a <see cref="T:System.Boolean"/>. </exception><filterpriority>2</filterpriority> public int CompareTo(object obj) { if (obj == null) return 1; if (!(obj is bool)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeBoolean")); if (this == (bool) obj) return 0; return !this ? -1 : 1; } <summary> Compares this instance to a specified <see cref="T:System.Boolean"/> object and returns an integer that indicates their relationship to one another. </summary> <returns> A signed integer that indicates the relative values of this instance and <paramref name="value"/>.Return Value Condition Less than zero This instance is false and <paramref name="value"/> is true. Zero This instance and <paramref name="value"/> are equal (either both are true or both are false). Greater than zero This instance is true and <paramref name="value"/> is false. </returns> <param name="value">A <see cref="T:System.Boolean"/> object to compare to this instance. </param><filterpriority>2</filterpriority> [<API key>] public int CompareTo(bool value) { if (this == value) return 0; return !this ? -1 : 1; } <summary> Converts the specified string representation of a logical value to its <see cref="T:System.Boolean"/> equivalent, or throws an exception if the string is not equivalent to the value of <see cref="F:System.Boolean.TrueString"/> or <see cref="F:System.Boolean.FalseString"/>. </summary> <returns> true if <paramref name="value"/> is equivalent to the value of the <see cref="F:System.Boolean.TrueString"/> field; false if <paramref name="value"/> is equivalent to the value of the <see cref="F:System.Boolean.FalseString"/> field. </returns> <param name="value">A string containing the value to convert. </param><exception cref="T:System.<API key>"><paramref name="value"/> is null. </exception><exception cref="T:System.FormatException"><paramref name="value"/> is not equivalent to the value of the <see cref="F:System.Boolean.TrueString"/> or <see cref="F:System.Boolean.FalseString"/> field. </exception><filterpriority>1</filterpriority> [<API key>] public static bool Parse(string value) { if (value == null) throw new <API key>("value"); bool result = false; if (!bool.TryParse(value, out result)) throw new FormatException(Environment.GetResourceString("Format_BadBoolean")); return result; } <summary> Tries to convert the specified string representation of a logical value to its <see cref="T:System.Boolean"/> equivalent. A return value indicates whether the conversion succeeded or failed. </summary> <returns> true if <paramref name="value"/> was converted successfully; otherwise, false. </returns> <param name="value">A string containing the value to convert. </param><param name="result">When this method returns, if the conversion succeeded, contains true if <paramref name="value"/> is equivalent to <see cref="F:System.Boolean.TrueString"/> or false if <paramref name="value"/> is equivalent to <see cref="F:System.Boolean.FalseString"/>. If the conversion failed, contains false. The conversion fails if <paramref name="value"/> is null or is not equivalent to the value of either the <see cref="F:System.Boolean.TrueString"/> or <see cref="F:System.Boolean.FalseString"/> field.</param><filterpriority>1</filterpriority> [<API key>] public static bool TryParse(string value, out bool result) { result = false; if (value == null) return false; if ("True".Equals(value, StringComparison.OrdinalIgnoreCase)) { result = true; return true; } if ("False".Equals(value, StringComparison.OrdinalIgnoreCase)) { result = false; return true; } value = bool.<API key>(value); if ("True".Equals(value, StringComparison.OrdinalIgnoreCase)) { result = true; return true; } if (!"False".Equals(value, StringComparison.OrdinalIgnoreCase)) return false; result = false; return true; } <summary> Returns the <see cref="T:System.TypeCode"/> for value type <see cref="T:System.Boolean"/>. </summary> <returns> The enumerated constant, <see cref="F:System.TypeCode.Boolean"/>. </returns> <filterpriority>2</filterpriority> public TypeCode GetTypeCode() { return TypeCode.Boolean; } bool IConvertible.ToBoolean(IFormatProvider provider) { return this; } char IConvertible.ToChar(IFormatProvider provider) { throw new <API key>(Environment.GetResourceString("InvalidCast_FromTo", (object) "Boolean", (object) "Char")); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(this); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(this); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(this); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(this); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(this); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(this); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(this); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(this); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(this); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(this); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(this); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new <API key>(Environment.GetResourceString("InvalidCast_FromTo", (object) "Boolean", (object) "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible) (bool) (this ? 1 : 0), type, provider); } private static string <API key>(string value) { int startIndex = 0; int index = value.Length - 1; char ch = char.MinValue; while (startIndex < value.Length && (char.IsWhiteSpace(value[startIndex]) || (int) value[startIndex] == (int) ch)) ++startIndex; while (index >= startIndex && (char.IsWhiteSpace(value[index]) || (int) value[index] == (int) ch)) --index; return value.Substring(startIndex, index - startIndex + 1); } } }
package hsa.awp.usergui; import hsa.awp.event.model.Event; import hsa.awp.event.model.Occurrence; import hsa.awp.user.model.SingleUser; import hsa.awp.user.model.User; import hsa.awp.usergui.controller.IUserGuiController; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.ExternalLink; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.Model; import org.apache.wicket.spring.injection.annot.SpringBean; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; /** * Panel showing detailed information about an {@link Event}. * * @author klassm */ public class EventDetailPanel extends Panel { /** * unique serialization id. */ private static final long serialVersionUID = <API key>; /** * GuiController which feeds the Gui with Data. */ @SpringBean(name = "usergui.controller") private transient IUserGuiController controller; /** * Constructor. * * @param id wicket:id. * @param event event to show. */ public EventDetailPanel(String id, Event event) { super(id); List<SingleUser> teachers = new LinkedList<SingleUser>(); event = controller.getEventById(event.getId()); for (Long teacherId : event.getTeachers()) { User user = controller.getUserById(teacherId); if (user != null && user instanceof SingleUser) { teachers.add((SingleUser) user); } } Collections.sort(teachers, new Comparator<SingleUser>() { @Override public int compare(SingleUser o1, SingleUser o2) { return o1.getName().compareTo(o2.getName()); } }); StringBuffer teachersList = new StringBuffer(); if (teachers.size() == 0) { teachersList.append("keine"); } else { boolean first = true; for (SingleUser teacher : teachers) { if (first) { first = false; } else { teachersList.append(", "); } teachersList.append(teacher.getName()); } } WebMarkupContainer eventGeneral = new WebMarkupContainer("event.general"); add(eventGeneral); eventGeneral.add(new Label("event.general.caption", "Allgemeines")); eventGeneral.add(new Label("event.general.eventId", new Model<Integer>(event.getEventId()))); eventGeneral.add(new Label("event.general.subjectName", new Model<String>(event.getSubject().getName()))); eventGeneral.add(new Label("event.general.maxParticipants", new Model<Integer>(event.getMaxParticipants()))); Label teacherLabel = new Label("event.general.teachers", new Model<String>(teachersList.toString())); eventGeneral.add(teacherLabel); eventGeneral.add(new Label("event.general.eventDescription", new Model<String>(event.<API key>()))); ExternalLink detailLink = new ExternalLink("event.general.link", event.getSubject().getLink()); eventGeneral.add(detailLink); detailLink.add(new Label("event.general.linkDesc", event.getSubject().getLink())); String description = event.getSubject().getDescription(); if (description == null || ((description = description.trim().replace("\n", "<br>")).equals(""))) { description = "keine"; } Label subjectDescription = new Label("event.general.subjectDescription", new Model<String>(description)); subjectDescription.<API key>(false); eventGeneral.add(subjectDescription); WebMarkupContainer eventTimetable = new WebMarkupContainer("event.timetable"); add(eventTimetable); eventTimetable.add(new Label("event.timetable.caption", "Stundenplan")); List<Occurrence> occurences; if (event.getTimetable() == null) { occurences = new LinkedList<Occurrence>(); } else { occurences = new LinkedList<Occurrence>(event.getTimetable().getOccurrences()); } eventTimetable.add(new ListView<Occurrence>("event.timetable.list", occurences) { /** * unique serialization id. */ private static final long serialVersionUID = -<API key>; @Override protected void populateItem(ListItem<Occurrence> item) { DateFormat singleFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm"); DateFormat dayFormat = new SimpleDateFormat("EEEE"); DateFormat timeFormat = new SimpleDateFormat("HH:mm"); String s; switch (item.getModelObject().getType()) { case SINGLE: s = "Einzeltermin vom " + singleFormat.format(item.getModelObject().getStartDate().getTime()); s += " bis " + singleFormat.format(item.getModelObject().getEndDate().getTime()); break; case PERIODICAL: s = "Wöchentlich am " + dayFormat.format(item.getModelObject().getStartDate().getTime()); s += " von " + timeFormat.format(item.getModelObject().getStartDate().getTime()) + " bis " + timeFormat.format(item.getModelObject().getEndDate().getTime()); break; default: s = ""; } item.add(new Label("event.timetable.list.occurrence", s)); } }); if (occurences.size() == 0) { eventTimetable.setVisible(false); } } }
@import url("e4_basestyle.css"); @import url("relations.css"); .MTrimmedWindow { background-color: #E1E6F6; } .MPartStack { font-size: 9; font-family: 'Segoe UI'; swt-simple: true; swt-mru-visible: true; } .MTrimBar { background-color: #E1E6F6; } .MToolControl.TrimStack { frame-image: url(./win7TSFrame.png); handle-image: url(./win7Handle.png); } .MTrimBar#<API key> { background-image: url(./win7.png); } .MPartStack.active { <API key>: #F3F9FF #D0DFEE #CEDDED #CEDDED #D2E1F0 #D2E1F0 #FFFFFF 20% 45% 60% 70% 100% 100%; <API key>: #B6BCCC; } #PerspectiveSwitcher { background-color: #F5F7FC #E1E6F6 100%; } #<API key> { swt-tab-renderer: url('bundleclass://org.eclipse.e4.ui.workbench.renderers.swt/org.eclipse.e4.ui.workbench.renderers.swt.CTabRendering'); <API key>: #F0F0F0 #F0F0F0 #F0F0F0 100% 100%; <API key>: #B4B4B4; <API key>: #F0F0F0; swt-tab-outline: #F0F0F0; color: #F0F0F0; swt-tab-height: 8px; padding: 0px 5px 7px; } CTabFolder.MArea .MPartStack, CTabFolder.MArea .MPartStack.active { swt-shadow-visible: false; } CTabFolder Canvas { background-color: #F8F8F8; }
#include <media/rc-map.h> #include <linux/module.h> /* Initial keytable is from Jose Alberto Reguero <jareguero@telefonica.net> and Felipe Morales Moreno <felipe.morales.moreno@gmail.com> */ /* Keytable fixed by Philippe Valembois <lephilousophe@users.sourceforge.net> */ static struct rc_map_table avermedia_rm_ks[] = { { 0x0501, KEY_POWER2 }, /* Power (RED POWER BUTTON) */ { 0x0502, KEY_CHANNELUP }, /* Channel+ */ { 0x0503, KEY_CHANNELDOWN }, /* Channel- */ { 0x0504, KEY_VOLUMEUP }, /* Volume+ */ { 0x0505, KEY_VOLUMEDOWN }, /* Volume- */ { 0x0506, KEY_MUTE }, /* Mute */ { 0x0507, KEY_AGAIN }, /* Recall */ { 0x0508, KEY_VIDEO }, /* Source */ { 0x0509, KEY_1 }, { 0x050a, KEY_2 }, { 0x050b, KEY_3 }, { 0x050c, KEY_4 }, { 0x050d, KEY_5 }, { 0x050e, KEY_6 }, { 0x050f, KEY_7 }, { 0x0510, KEY_8 }, { 0x0511, KEY_9 }, { 0x0512, KEY_0 }, { 0x0513, KEY_AUDIO }, /* Audio */ { 0x0515, KEY_EPG }, /* EPG */ { 0x0516, KEY_PLAYPAUSE }, /* Play/Pause */ { 0x0517, KEY_RECORD }, /* Record */ { 0x0518, KEY_STOP }, /* Stop */ { 0x051c, KEY_BACK }, { 0x051d, KEY_FORWARD }, { 0x054d, KEY_INFO }, /* Display information */ { 0x0556, KEY_ZOOM }, /* Fullscreen */ }; static struct rc_map_list avermedia_rm_ks_map = { .map = { .scan = avermedia_rm_ks, .size = ARRAY_SIZE(avermedia_rm_ks), .rc_type = RC_TYPE_NEC, .name = <API key>, } }; static int __init <API key>(void) { return rc_map_register(&avermedia_rm_ks_map); } static void __exit <API key>(void) { rc_map_unregister(&avermedia_rm_ks_map); } module_init(<API key>) module_exit(<API key>) MODULE_LICENSE("GPL"); MODULE_AUTHOR("Antti Palosaari <crope@iki.fi>");
// This file is part of dit. // dit is free software: you can redistribute it and/or modify // it under the terms of version 3 of the GNU Affero General Public // dit is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #include <cassert> #include <cstdlib> #include <functional> #include <ostream> #include <sstream> #include <string> #include <vector> #include <boost/filesystem.hpp> #include "Command.hpp" #include "Commands.hpp" #include "Config.hpp" #include "Dit.hpp" #include "Project.hpp" namespace fs = boost::filesystem; /** * @brief Usage message for "complete" command. */ const char *const USAGE = "Usage: complete <regular args>"; namespace { /** * @brief Implementation of "complete" command, which helps with completion. */ class CompleteCmd : public <API key><CompleteCmd> { public: /** * @brief Constructs the command implementation. */ CompleteCmd(); public: /** * @copydoc Command::run() */ virtual boost::optional<int> run( Dit &dit, const std::vector<std::string> &args) override; }; } CompleteCmd::CompleteCmd() : parent("complete", "perform command-line completion", USAGE) { } boost::optional<int> CompleteCmd::run(Dit &dit, const std::vector<std::string> &args) { std::ostringstream estream; int exitCode = dit.complete(args, out(), estream); if (!estream.str().empty()) { // Calling err() has side effects, so don't call unless error occurred. err() << estream.str(); } return exitCode; }
namespace DemoWinForm { partial class frmMapFinder { <summary> Required designer variable. </summary> private System.ComponentModel.IContainer components = null; <summary> Clean up any resources being used. </summary> <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code <summary> Required method for Designer support - do not modify the contents of this method with the code editor. </summary> private void InitializeComponent() { this.comboBox7 = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.comboBox8 = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.comboBox9 = new System.Windows.Forms.ComboBox(); this.label4 = new System.Windows.Forms.Label(); this.comboBox2 = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.comboBox5 = new System.Windows.Forms.ComboBox(); this.label5 = new System.Windows.Forms.Label(); this.comboBox6 = new System.Windows.Forms.ComboBox(); this.label6 = new System.Windows.Forms.Label(); this.comboBox4 = new System.Windows.Forms.ComboBox(); this.label10 = new System.Windows.Forms.Label(); this.comboBox3 = new System.Windows.Forms.ComboBox(); this.label9 = new System.Windows.Forms.Label(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.label7 = new System.Windows.Forms.Label(); this.cmbCity = new System.Windows.Forms.ComboBox(); this.lblLandParcelCity = new System.Windows.Forms.Label(); this.cmbCountry = new System.Windows.Forms.ComboBox(); this.<API key> = new System.Windows.Forms.Label(); this.comboBox10 = new System.Windows.Forms.ComboBox(); this.label8 = new System.Windows.Forms.Label(); this.comboBox11 = new System.Windows.Forms.ComboBox(); this.label11 = new System.Windows.Forms.Label(); this.comboBox12 = new System.Windows.Forms.ComboBox(); this.label12 = new System.Windows.Forms.Label(); this.comboBox13 = new System.Windows.Forms.ComboBox(); this.label13 = new System.Windows.Forms.Label(); this.comboBox14 = new System.Windows.Forms.ComboBox(); this.label14 = new System.Windows.Forms.Label(); this.comboBox15 = new System.Windows.Forms.ComboBox(); this.label15 = new System.Windows.Forms.Label(); this.comboBox16 = new System.Windows.Forms.ComboBox(); this.label16 = new System.Windows.Forms.Label(); this.comboBox17 = new System.Windows.Forms.ComboBox(); this.label17 = new System.Windows.Forms.Label(); this.comboBox18 = new System.Windows.Forms.ComboBox(); this.label18 = new System.Windows.Forms.Label(); this.comboBox19 = new System.Windows.Forms.ComboBox(); this.label19 = new System.Windows.Forms.Label(); this.comboBox20 = new System.Windows.Forms.ComboBox(); this.label20 = new System.Windows.Forms.Label(); this.spltMapFinder = new System.Windows.Forms.SplitContainer(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.comboBox21 = new System.Windows.Forms.ComboBox(); this.label21 = new System.Windows.Forms.Label(); this.comboBox22 = new System.Windows.Forms.ComboBox(); this.label22 = new System.Windows.Forms.Label(); this.comboBox23 = new System.Windows.Forms.ComboBox(); this.label23 = new System.Windows.Forms.Label(); this.comboBox24 = new System.Windows.Forms.ComboBox(); this.label24 = new System.Windows.Forms.Label(); this.comboBox25 = new System.Windows.Forms.ComboBox(); this.label25 = new System.Windows.Forms.Label(); this.comboBox26 = new System.Windows.Forms.ComboBox(); this.label26 = new System.Windows.Forms.Label(); this.comboBox27 = new System.Windows.Forms.ComboBox(); this.label27 = new System.Windows.Forms.Label(); this.comboBox28 = new System.Windows.Forms.ComboBox(); this.label28 = new System.Windows.Forms.Label(); this.comboBox29 = new System.Windows.Forms.ComboBox(); this.label29 = new System.Windows.Forms.Label(); this.comboBox30 = new System.Windows.Forms.ComboBox(); this.label30 = new System.Windows.Forms.Label(); this.comboBox31 = new System.Windows.Forms.ComboBox(); this.label31 = new System.Windows.Forms.Label(); this.mapbxMapFinder = new SharpMap.Forms.MapBox(); this.spltMapFinder.Panel1.SuspendLayout(); this.spltMapFinder.Panel2.SuspendLayout(); this.spltMapFinder.SuspendLayout(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // comboBox7 this.comboBox7.FormattingEnabled = true; this.comboBox7.Location = new System.Drawing.Point(216, 291); this.comboBox7.Name = "comboBox7"; this.comboBox7.Size = new System.Drawing.Size(319, 21); this.comboBox7.TabIndex = 85; // label2 this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(146, 291); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(48, 13); this.label2.TabIndex = 86; this.label2.Text = "Location"; // comboBox8 this.comboBox8.FormattingEnabled = true; this.comboBox8.Location = new System.Drawing.Point(216, 237); this.comboBox8.Name = "comboBox8"; this.comboBox8.Size = new System.Drawing.Size(319, 21); this.comboBox8.TabIndex = 83; // label3 this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(128, 237); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(70, 13); this.label3.TabIndex = 84; this.label3.Text = "Sub-Location"; // comboBox9 this.comboBox9.FormattingEnabled = true; this.comboBox9.Location = new System.Drawing.Point(216, 264); this.comboBox9.Name = "comboBox9"; this.comboBox9.Size = new System.Drawing.Size(319, 21); this.comboBox9.TabIndex = 81; // label4 this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(154, 264); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(40, 13); this.label4.TabIndex = 82; this.label4.Text = "County"; // comboBox2 this.comboBox2.FormattingEnabled = true; this.comboBox2.Location = new System.Drawing.Point(216, 210); this.comboBox2.Name = "comboBox2"; this.comboBox2.Size = new System.Drawing.Size(319, 21); this.comboBox2.TabIndex = 79; // label1 this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(150, 213); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(48, 13); this.label1.TabIndex = 80; this.label1.Text = "Location"; // comboBox5 this.comboBox5.FormattingEnabled = true; this.comboBox5.Location = new System.Drawing.Point(216, 156); this.comboBox5.Name = "comboBox5"; this.comboBox5.Size = new System.Drawing.Size(319, 21); this.comboBox5.TabIndex = 77; // label5 this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(159, 156); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(39, 13); this.label5.TabIndex = 78; this.label5.Text = "District"; // comboBox6 this.comboBox6.FormattingEnabled = true; this.comboBox6.Location = new System.Drawing.Point(216, 183); this.comboBox6.Name = "comboBox6"; this.comboBox6.Size = new System.Drawing.Size(319, 21); this.comboBox6.TabIndex = 75; // label6 this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(155, 183); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(44, 13); this.label6.TabIndex = 76; this.label6.Text = "Division"; // comboBox4 this.comboBox4.FormattingEnabled = true; this.comboBox4.Location = new System.Drawing.Point(216, 101); this.comboBox4.Name = "comboBox4"; this.comboBox4.Size = new System.Drawing.Size(319, 21); this.comboBox4.TabIndex = 73; // label10 this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(159, 104); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(39, 13); this.label10.TabIndex = 74; this.label10.Text = "District"; // comboBox3 this.comboBox3.FormattingEnabled = true; this.comboBox3.Location = new System.Drawing.Point(216, 128); this.comboBox3.Name = "comboBox3"; this.comboBox3.Size = new System.Drawing.Size(319, 21); this.comboBox3.TabIndex = 71; // label9 this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(155, 131); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(44, 13); this.label9.TabIndex = 72; this.label9.Text = "Division"; // comboBox1 this.comboBox1.FormattingEnabled = true; this.comboBox1.Location = new System.Drawing.Point(216, 74); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(319, 21); this.comboBox1.TabIndex = 69; // label7 this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(149, 77); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(49, 13); this.label7.TabIndex = 70; this.label7.Text = "Province"; // cmbCity this.cmbCity.FormattingEnabled = true; this.cmbCity.Location = new System.Drawing.Point(216, 44); this.cmbCity.Name = "cmbCity"; this.cmbCity.Size = new System.Drawing.Size(319, 21); this.cmbCity.TabIndex = 66; // lblLandParcelCity this.lblLandParcelCity.AutoSize = true; this.lblLandParcelCity.Location = new System.Drawing.Point(170, 44); this.lblLandParcelCity.Name = "lblLandParcelCity"; this.lblLandParcelCity.Size = new System.Drawing.Size(24, 13); this.lblLandParcelCity.TabIndex = 68; this.lblLandParcelCity.Text = "City"; // cmbCountry this.cmbCountry.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbCountry.FormattingEnabled = true; this.cmbCountry.Location = new System.Drawing.Point(216, 17); this.cmbCountry.MaxDropDownItems = 10; this.cmbCountry.Name = "cmbCountry"; this.cmbCountry.Size = new System.Drawing.Size(319, 21); this.cmbCountry.TabIndex = 65; // <API key> this.<API key>.AutoSize = true; this.<API key>.Location = new System.Drawing.Point(151, 17); this.<API key>.Name = "<API key>"; this.<API key>.Size = new System.Drawing.Size(43, 13); this.<API key>.TabIndex = 67; this.<API key>.Text = "Country"; this.<API key>.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // comboBox10 this.comboBox10.FormattingEnabled = true; this.comboBox10.Location = new System.Drawing.Point(216, 291); this.comboBox10.Name = "comboBox10"; this.comboBox10.Size = new System.Drawing.Size(319, 21); this.comboBox10.TabIndex = 85; // label8 this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(146, 291); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(48, 13); this.label8.TabIndex = 86; this.label8.Text = "Location"; // comboBox11 this.comboBox11.FormattingEnabled = true; this.comboBox11.Location = new System.Drawing.Point(216, 237); this.comboBox11.Name = "comboBox11"; this.comboBox11.Size = new System.Drawing.Size(319, 21); this.comboBox11.TabIndex = 83; // label11 this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(128, 237); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(70, 13); this.label11.TabIndex = 84; this.label11.Text = "Sub-Location"; // comboBox12 this.comboBox12.FormattingEnabled = true; this.comboBox12.Location = new System.Drawing.Point(216, 264); this.comboBox12.Name = "comboBox12"; this.comboBox12.Size = new System.Drawing.Size(319, 21); this.comboBox12.TabIndex = 81; // label12 this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(154, 264); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(40, 13); this.label12.TabIndex = 82; this.label12.Text = "County"; // comboBox13 this.comboBox13.FormattingEnabled = true; this.comboBox13.Location = new System.Drawing.Point(216, 210); this.comboBox13.Name = "comboBox13"; this.comboBox13.Size = new System.Drawing.Size(319, 21); this.comboBox13.TabIndex = 79; // label13 this.label13.AutoSize = true; this.label13.Location = new System.Drawing.Point(150, 213); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(48, 13); this.label13.TabIndex = 80; this.label13.Text = "Location"; // comboBox14 this.comboBox14.FormattingEnabled = true; this.comboBox14.Location = new System.Drawing.Point(216, 156); this.comboBox14.Name = "comboBox14"; this.comboBox14.Size = new System.Drawing.Size(319, 21); this.comboBox14.TabIndex = 77; // label14 this.label14.AutoSize = true; this.label14.Location = new System.Drawing.Point(159, 156); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(39, 13); this.label14.TabIndex = 78; this.label14.Text = "District"; // comboBox15 this.comboBox15.FormattingEnabled = true; this.comboBox15.Location = new System.Drawing.Point(216, 183); this.comboBox15.Name = "comboBox15"; this.comboBox15.Size = new System.Drawing.Size(319, 21); this.comboBox15.TabIndex = 75; // label15 this.label15.AutoSize = true; this.label15.Location = new System.Drawing.Point(155, 183); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(44, 13); this.label15.TabIndex = 76; this.label15.Text = "Division"; // comboBox16 this.comboBox16.FormattingEnabled = true; this.comboBox16.Location = new System.Drawing.Point(216, 101); this.comboBox16.Name = "comboBox16"; this.comboBox16.Size = new System.Drawing.Size(319, 21); this.comboBox16.TabIndex = 73; // label16 this.label16.AutoSize = true; this.label16.Location = new System.Drawing.Point(159, 104); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(39, 13); this.label16.TabIndex = 74; this.label16.Text = "District"; // comboBox17 this.comboBox17.FormattingEnabled = true; this.comboBox17.Location = new System.Drawing.Point(216, 128); this.comboBox17.Name = "comboBox17"; this.comboBox17.Size = new System.Drawing.Size(319, 21); this.comboBox17.TabIndex = 71; // label17 this.label17.AutoSize = true; this.label17.Location = new System.Drawing.Point(155, 131); this.label17.Name = "label17"; this.label17.Size = new System.Drawing.Size(44, 13); this.label17.TabIndex = 72; this.label17.Text = "Division"; // comboBox18 this.comboBox18.FormattingEnabled = true; this.comboBox18.Location = new System.Drawing.Point(216, 74); this.comboBox18.Name = "comboBox18"; this.comboBox18.Size = new System.Drawing.Size(319, 21); this.comboBox18.TabIndex = 69; // label18 this.label18.AutoSize = true; this.label18.Location = new System.Drawing.Point(149, 77); this.label18.Name = "label18"; this.label18.Size = new System.Drawing.Size(49, 13); this.label18.TabIndex = 70; this.label18.Text = "Province"; // comboBox19 this.comboBox19.FormattingEnabled = true; this.comboBox19.Location = new System.Drawing.Point(216, 44); this.comboBox19.Name = "comboBox19"; this.comboBox19.Size = new System.Drawing.Size(319, 21); this.comboBox19.TabIndex = 66; // label19 this.label19.AutoSize = true; this.label19.Location = new System.Drawing.Point(170, 44); this.label19.Name = "label19"; this.label19.Size = new System.Drawing.Size(24, 13); this.label19.TabIndex = 68; this.label19.Text = "City"; // comboBox20 this.comboBox20.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox20.FormattingEnabled = true; this.comboBox20.Location = new System.Drawing.Point(216, 17); this.comboBox20.MaxDropDownItems = 10; this.comboBox20.Name = "comboBox20"; this.comboBox20.Size = new System.Drawing.Size(319, 21); this.comboBox20.TabIndex = 65; // label20 this.label20.AutoSize = true; this.label20.Location = new System.Drawing.Point(151, 17); this.label20.Name = "label20"; this.label20.Size = new System.Drawing.Size(43, 13); this.label20.TabIndex = 67; this.label20.Text = "Country"; this.label20.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // spltMapFinder this.spltMapFinder.Dock = System.Windows.Forms.DockStyle.Fill; this.spltMapFinder.Location = new System.Drawing.Point(0, 0); this.spltMapFinder.Name = "spltMapFinder"; this.spltMapFinder.Orientation = System.Windows.Forms.Orientation.Horizontal; // spltMapFinder.Panel1 this.spltMapFinder.Panel1.Controls.Add(this.groupBox1); // spltMapFinder.Panel2 this.spltMapFinder.Panel2.Controls.Add(this.mapbxMapFinder); this.spltMapFinder.Size = new System.Drawing.Size(874, 548); this.spltMapFinder.SplitterDistance = 240; this.spltMapFinder.TabIndex = 0; // groupBox1 this.groupBox1.Controls.Add(this.comboBox21); this.groupBox1.Controls.Add(this.label21); this.groupBox1.Controls.Add(this.comboBox22); this.groupBox1.Controls.Add(this.label22); this.groupBox1.Controls.Add(this.comboBox23); this.groupBox1.Controls.Add(this.label23); this.groupBox1.Controls.Add(this.comboBox24); this.groupBox1.Controls.Add(this.label24); this.groupBox1.Controls.Add(this.comboBox25); this.groupBox1.Controls.Add(this.label25); this.groupBox1.Controls.Add(this.comboBox26); this.groupBox1.Controls.Add(this.label26); this.groupBox1.Controls.Add(this.comboBox27); this.groupBox1.Controls.Add(this.label27); this.groupBox1.Controls.Add(this.comboBox28); this.groupBox1.Controls.Add(this.label28); this.groupBox1.Controls.Add(this.comboBox29); this.groupBox1.Controls.Add(this.label29); this.groupBox1.Controls.Add(this.comboBox30); this.groupBox1.Controls.Add(this.label30); this.groupBox1.Controls.Add(this.comboBox31); this.groupBox1.Controls.Add(this.label31); this.groupBox1.Location = new System.Drawing.Point(2, 5); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(870, 217); this.groupBox1.TabIndex = 3; this.groupBox1.TabStop = false; this.groupBox1.Text = "Search Map"; this.groupBox1.Enter += new System.EventHandler(this.groupBox1_Enter); // comboBox21 this.comboBox21.FormattingEnabled = true; this.comboBox21.Location = new System.Drawing.Point(514, 135); this.comboBox21.Name = "comboBox21"; this.comboBox21.Size = new System.Drawing.Size(319, 21); this.comboBox21.TabIndex = 85; this.comboBox21.<API key> += new System.EventHandler(this.<API key>); // label21 this.label21.AutoSize = true; this.label21.Location = new System.Drawing.Point(419, 135); this.label21.Name = "label21"; this.label21.Size = new System.Drawing.Size(92, 13); this.label21.TabIndex = 86; this.label21.Text = "Universal Address"; // comboBox22 this.comboBox22.FormattingEnabled = true; this.comboBox22.Location = new System.Drawing.Point(514, 81); this.comboBox22.Name = "comboBox22"; this.comboBox22.Size = new System.Drawing.Size(319, 21); this.comboBox22.TabIndex = 83; // label22 this.label22.AutoSize = true; this.label22.Location = new System.Drawing.Point(438, 84); this.label22.Name = "label22"; this.label22.Size = new System.Drawing.Size(70, 13); this.label22.TabIndex = 84; this.label22.Text = "Sub-Location"; // comboBox23 this.comboBox23.FormattingEnabled = true; this.comboBox23.Location = new System.Drawing.Point(514, 108); this.comboBox23.Name = "comboBox23"; this.comboBox23.Size = new System.Drawing.Size(319, 21); this.comboBox23.TabIndex = 81; // label23 this.label23.AutoSize = true; this.label23.Location = new System.Drawing.Point(468, 109); this.label23.Name = "label23"; this.label23.Size = new System.Drawing.Size(40, 13); this.label23.TabIndex = 82; this.label23.Text = "County"; // comboBox24 this.comboBox24.FormattingEnabled = true; this.comboBox24.Location = new System.Drawing.Point(514, 54); this.comboBox24.Name = "comboBox24"; this.comboBox24.Size = new System.Drawing.Size(319, 21); this.comboBox24.TabIndex = 79; // label24 this.label24.AutoSize = true; this.label24.Location = new System.Drawing.Point(460, 55); this.label24.Name = "label24"; this.label24.Size = new System.Drawing.Size(48, 13); this.label24.TabIndex = 80; this.label24.Text = "Location"; // comboBox25 this.comboBox25.FormattingEnabled = true; this.comboBox25.Location = new System.Drawing.Point(81, 166); this.comboBox25.Name = "comboBox25"; this.comboBox25.Size = new System.Drawing.Size(319, 21); this.comboBox25.TabIndex = 77; // label25 this.label25.AutoSize = true; this.label25.Location = new System.Drawing.Point(24, 166); this.label25.Name = "label25"; this.label25.Size = new System.Drawing.Size(39, 13); this.label25.TabIndex = 78; this.label25.Text = "District"; // comboBox26 this.comboBox26.FormattingEnabled = true; this.comboBox26.Location = new System.Drawing.Point(514, 27); this.comboBox26.Name = "comboBox26"; this.comboBox26.Size = new System.Drawing.Size(319, 21); this.comboBox26.TabIndex = 75; // label26 this.label26.AutoSize = true; this.label26.Location = new System.Drawing.Point(464, 29); this.label26.Name = "label26"; this.label26.Size = new System.Drawing.Size(44, 13); this.label26.TabIndex = 76; this.label26.Text = "Division"; // comboBox27 this.comboBox27.FormattingEnabled = true; this.comboBox27.Location = new System.Drawing.Point(81, 111); this.comboBox27.Name = "comboBox27"; this.comboBox27.Size = new System.Drawing.Size(319, 21); this.comboBox27.TabIndex = 73; // label27 this.label27.AutoSize = true; this.label27.Location = new System.Drawing.Point(24, 114); this.label27.Name = "label27"; this.label27.Size = new System.Drawing.Size(39, 13); this.label27.TabIndex = 74; this.label27.Text = "District"; // comboBox28 this.comboBox28.FormattingEnabled = true; this.comboBox28.Location = new System.Drawing.Point(81, 138); this.comboBox28.Name = "comboBox28"; this.comboBox28.Size = new System.Drawing.Size(319, 21); this.comboBox28.TabIndex = 71; // label28 this.label28.AutoSize = true; this.label28.Location = new System.Drawing.Point(20, 141); this.label28.Name = "label28"; this.label28.Size = new System.Drawing.Size(44, 13); this.label28.TabIndex = 72; this.label28.Text = "Division"; // comboBox29 this.comboBox29.FormattingEnabled = true; this.comboBox29.Location = new System.Drawing.Point(81, 84); this.comboBox29.Name = "comboBox29"; this.comboBox29.Size = new System.Drawing.Size(319, 21); this.comboBox29.TabIndex = 69; // label29 this.label29.AutoSize = true; this.label29.Location = new System.Drawing.Point(14, 87); this.label29.Name = "label29"; this.label29.Size = new System.Drawing.Size(49, 13); this.label29.TabIndex = 70; this.label29.Text = "Province"; // comboBox30 this.comboBox30.FormattingEnabled = true; this.comboBox30.Location = new System.Drawing.Point(81, 54); this.comboBox30.Name = "comboBox30"; this.comboBox30.Size = new System.Drawing.Size(319, 21); this.comboBox30.TabIndex = 66; // label30 this.label30.AutoSize = true; this.label30.Location = new System.Drawing.Point(35, 54); this.label30.Name = "label30"; this.label30.Size = new System.Drawing.Size(24, 13); this.label30.TabIndex = 68; this.label30.Text = "City"; // comboBox31 this.comboBox31.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox31.FormattingEnabled = true; this.comboBox31.Location = new System.Drawing.Point(81, 27); this.comboBox31.MaxDropDownItems = 10; this.comboBox31.Name = "comboBox31"; this.comboBox31.Size = new System.Drawing.Size(319, 21); this.comboBox31.TabIndex = 65; // label31 this.label31.AutoSize = true; this.label31.Location = new System.Drawing.Point(16, 27); this.label31.Name = "label31"; this.label31.Size = new System.Drawing.Size(43, 13); this.label31.TabIndex = 67; this.label31.Text = "Country"; this.label31.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // mapbxMapFinder this.mapbxMapFinder.ActiveTool = SharpMap.Forms.MapBox.Tools.None; this.mapbxMapFinder.BackColor = System.Drawing.SystemColors.Info; this.mapbxMapFinder.Cursor = System.Windows.Forms.Cursors.Default; this.mapbxMapFinder.Dock = System.Windows.Forms.DockStyle.Fill; this.mapbxMapFinder.FineZoomFactor = 10; this.mapbxMapFinder.Location = new System.Drawing.Point(0, 0); this.mapbxMapFinder.Name = "mapbxMapFinder"; this.mapbxMapFinder.QueryLayerIndex = 0; this.mapbxMapFinder.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(210)))), ((int)(((byte)(244)))), ((int)(((byte)(244)))), ((int)(((byte)(244))))); this.mapbxMapFinder.SelectionForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(244)))), ((int)(((byte)(244)))), ((int)(((byte)(244))))); this.mapbxMapFinder.Size = new System.Drawing.Size(874, 304); this.mapbxMapFinder.TabIndex = 5; this.mapbxMapFinder.WheelZoomMagnitude = 2; // frmMapFinder this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(874, 548); this.Controls.Add(this.spltMapFinder); this.Name = "frmMapFinder"; this.Text = "frmMapFinder"; this.Load += new System.EventHandler(this.frmMapFinder_Load); this.spltMapFinder.Panel1.ResumeLayout(false); this.spltMapFinder.Panel2.ResumeLayout(false); this.spltMapFinder.ResumeLayout(false); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ComboBox comboBox7; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox comboBox8; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox comboBox9; private System.Windows.Forms.Label label4; private System.Windows.Forms.ComboBox comboBox2; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox comboBox5; private System.Windows.Forms.Label label5; private System.Windows.Forms.ComboBox comboBox6; private System.Windows.Forms.Label label6; private System.Windows.Forms.ComboBox comboBox4; private System.Windows.Forms.Label label10; private System.Windows.Forms.ComboBox comboBox3; private System.Windows.Forms.Label label9; private System.Windows.Forms.ComboBox comboBox1; private System.Windows.Forms.Label label7; private System.Windows.Forms.ComboBox cmbCity; private System.Windows.Forms.Label lblLandParcelCity; private System.Windows.Forms.ComboBox cmbCountry; private System.Windows.Forms.Label <API key>; private System.Windows.Forms.ComboBox comboBox10; private System.Windows.Forms.Label label8; private System.Windows.Forms.ComboBox comboBox11; private System.Windows.Forms.Label label11; private System.Windows.Forms.ComboBox comboBox12; private System.Windows.Forms.Label label12; private System.Windows.Forms.ComboBox comboBox13; private System.Windows.Forms.Label label13; private System.Windows.Forms.ComboBox comboBox14; private System.Windows.Forms.Label label14; private System.Windows.Forms.ComboBox comboBox15; private System.Windows.Forms.Label label15; private System.Windows.Forms.ComboBox comboBox16; private System.Windows.Forms.Label label16; private System.Windows.Forms.ComboBox comboBox17; private System.Windows.Forms.Label label17; private System.Windows.Forms.ComboBox comboBox18; private System.Windows.Forms.Label label18; private System.Windows.Forms.ComboBox comboBox19; private System.Windows.Forms.Label label19; private System.Windows.Forms.ComboBox comboBox20; private System.Windows.Forms.Label label20; private System.Windows.Forms.SplitContainer spltMapFinder; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.ComboBox comboBox21; private System.Windows.Forms.Label label21; private System.Windows.Forms.ComboBox comboBox22; private System.Windows.Forms.Label label22; private System.Windows.Forms.ComboBox comboBox23; private System.Windows.Forms.Label label23; private System.Windows.Forms.ComboBox comboBox24; private System.Windows.Forms.Label label24; private System.Windows.Forms.ComboBox comboBox25; private System.Windows.Forms.Label label25; private System.Windows.Forms.ComboBox comboBox26; private System.Windows.Forms.Label label26; private System.Windows.Forms.ComboBox comboBox27; private System.Windows.Forms.Label label27; private System.Windows.Forms.ComboBox comboBox28; private System.Windows.Forms.Label label28; private System.Windows.Forms.ComboBox comboBox29; private System.Windows.Forms.Label label29; private System.Windows.Forms.ComboBox comboBox30; private System.Windows.Forms.Label label30; private System.Windows.Forms.ComboBox comboBox31; private System.Windows.Forms.Label label31; private SharpMap.Forms.MapBox mapbxMapFinder; } }
#ifndef _TREENODE_H #define _TREENODE_H #include <stdio.h> #include <stdbool.h> #include <wptypes.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ typedef struct _wp_treenode wp_tree_node_t; typedef enum <API key> { RB_TREE_RED = 0, RB_TREE_BLACK, } <API key>; wp_tree_node_t *wp_tree_node_new (void); wp_tree_node_t *<API key> (void *content, wp_tree_node_t *parent, wp_tree_node_t *left, wp_tree_node_t *right); void wp_tree_node_copy (wp_tree_node_t *dest, const wp_tree_node_t *src); void wp_tree_node_free (wp_tree_node_t *node); void <API key> (wp_tree_node_t *node, void *data); void <API key> (wp_tree_node_t *node, wp_tree_node_t *parent); void <API key> (wp_tree_node_t *node, wp_tree_node_t *left); void <API key> (wp_tree_node_t *node, wp_tree_node_t *right); void *<API key> (const wp_tree_node_t *node); wp_tree_node_t *<API key> (const wp_tree_node_t *node); wp_tree_node_t *<API key> (const wp_tree_node_t *node); wp_tree_node_t *<API key> (const wp_tree_node_t *node); int <API key> (const wp_tree_node_t *node); int <API key> (const wp_tree_node_t *node); void wp_tree_node_dump (const wp_tree_node_t *node, FILE *file, wp_write_func_t f, void *data); /* For Red-Black Tree */ void <API key> (wp_tree_node_t *node); void <API key> (wp_tree_node_t *node); int wp_tree_node_is_red (const wp_tree_node_t *node); int <API key> (const wp_tree_node_t *node); <API key> <API key> (const wp_tree_node_t *node); void <API key> (wp_tree_node_t *node, <API key> color); void <API key> (wp_tree_node_t *dest, const wp_tree_node_t *src); void <API key> (const wp_tree_node_t *node, FILE *file, wp_write_func_t f, void *data); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* _TREENODE_H */
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ENetSharp { public class ENetList { public List<object> data = new List<object>(); internal int position; } public static class ENetListHelper { <summary> Removes everything from the list </summary> <param name="list">The target list</param> public static void enet_list_clear(ref ENetList list) { list.data.Clear(); } public static ENetList enet_list_insert(ref ENetList list, int position, object data) { list.data.Insert(position, data); return list; } public static ENetList enet_list_insert(ref ENetList list, object data) { list.data.Add(data); return list; } public static object enet_list_remove(ref ENetList list, int position) { var data = list.data[position]; list.data.RemoveAt(position); return data; } public static object enet_list_remove(ref ENetList list) { var item = list.data[list.position]; list.data.Remove(item); return item; } public static object enet_list_remove(ref ENetList list, object item) { list.data.Remove(item); return item; } public static void enet_list_remove(ref ENetList list, Predicate<object> items) { list.data.RemoveAll(items); } public static ENetList enet_list_move(ref ENetList list, int positionFirst, int positionLast) { object tmp = list.data[positionFirst]; list.data[positionFirst] = list.data[positionLast]; list.data[positionLast] = tmp; return list; } public static int enet_list_size(ref ENetList list) { return list.data.Count; } //#define enet_list_begin(list) ((list) -> sentinel.next) public static object enet_list_begin(ref ENetList list) { return list.data.First(); } //#define enet_list_end(list) (& (list) -> sentinel) public static object enet_list_end(ref ENetList list) { return list.data.Last(); } //#define enet_list_empty(list) (enet_list_begin (list) == enet_list_end (list)) public static bool enet_list_empty(ref ENetList list) { return !list.data.Any(); } //#define enet_list_next(iterator) ((iterator) -> next) public static object enet_list_next(ref ENetList list) { var d = list.data[list.position]; list.position++; return d; } //#define enet_list_previous(iterator) ((iterator) -> previous) public static object enet_list_previous(ref ENetList list) { var d = list.data[list.position]; list.position return d; } //#define enet_list_front(list) ((void *) (list) -> sentinel.next) public static object enet_list_front(ref ENetList list) { return list.data.First(); } //#define enet_list_back(list) ((void *) (list) -> sentinel.previous) public static object enet_list_back(ref ENetList list) { list.position return list.data[list.position]; } public static object enet_list_current(ref ENetList list) { return list.data[list.position]; } } }
# CMake generated Testfile for # Source directory: /home/zitouni/gnuradio-3.6.1/gr-uhd/grc # Build directory: /home/zitouni/gnuradio-3.6.1/build/gr-uhd/grc # This file includes the relevent testing commands required for # testing this directory and lists subdirectories to be tested as well.
-- Fix oracle syntax for psql set search_path = tm_cz, pg_catalog; DROP FUNCTION IF EXISTS tm_cz.bio_experiment_uid(character varying); \i ../../../ddl/postgres/tm_cz/functions/bio_experiment_uid.sql
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <getopt.h> #include "upgma.h" #include "utils.h" #include "seq_utils.h" #include "sequence.h" #include "seq_reader.h" #include "node.h" #include "tree.h" #include "tree_utils.h" UPGMA::UPGMA (std::istream* pios):num_taxa_(0), num_char_(0), newickstring_(""), tree_(nullptr) { std::string alphaName; // not used, but required by reader seqs_ = ingest_alignment(pios, alphaName); num_taxa_ = static_cast<int>(seqs_.size()); num_char_ = static_cast<int>(seqs_[0].get_length()); // check that it is aligned (doesn't make sense otherwise) if (!is_aligned(seqs_)) { std::cerr << "Error: sequences are not aligned. Exiting." << std::endl; exit(0); } names_ = collect_names(seqs_); full_distmatrix_ = build_matrix(); } std::vector< std::vector<double> > UPGMA::build_matrix () { // 1) skip self comparisons // 2) only calculate one half of matrix (i.e., no duplicate calcs) auto nt = static_cast<size_t>(num_taxa_); std::vector< std::vector<double> > distances(nt, std::vector<double>(nt, 0.0)); double tempScore = 0.0; for (size_t i = 0; i < nt; i++) { std::string seq1 = seqs_[i].get_sequence(); for (size_t j = (i + 1); j < nt; j++) { std::string seq2 = seqs_[j].get_sequence(); // get distance tempScore = static_cast<double>(calc_hamming_dist(seq1, seq2)); // put scale in terms of number of sites. original version did not do this tempScore /= static_cast<double>(num_char_); // put in both top and bottom of matrix, even though only top is used distances[i][j] = distances[j][i] = tempScore; } } // just for debugging /* std::cout << "\t"; for (unsigned int i = 0; i < names_.size(); i++) { std::cout << names_[i] << "\t"; } std::cout << std::endl; for (int i = 0; i < num_taxa_; i++) { std::cout << names_[i] << "\t"; for (int j = 0; j < num_taxa_; j++) { std::cout << distances[i][j] << "\t"; } std::cout << std::endl; } */ return distances; } // find smallest pairwise distance // will always find this on the top half of the matrix i.e., mini1 < mini2 double UPGMA::<API key> (const std::vector< std::vector<double> >& dmatrix, unsigned long& mini1, unsigned long& mini2) { // super large value double minD = 99999999999.99; size_t numseqs = dmatrix.size(); for (size_t i = 0; i < (numseqs - 1); i++) { auto idx = static_cast<size_t>(std::min_element(dmatrix[i].begin() + (i + 1), dmatrix[i].end()) - dmatrix[i].begin()); if (dmatrix[i][idx] < minD) { minD = dmatrix[i][idx]; mini1 = i; mini2 = idx; } } return minD; } void UPGMA::construct_tree () { // location of minimum distance (top half) unsigned long ind1 = 0; unsigned long ind2 = 0; // initialize std::vector< std::vector<double> > dMatrix = full_distmatrix_; Node * anc = nullptr; // new node, ancestor of 2 clusters Node * left = nullptr; Node * right = nullptr; auto nt = static_cast<size_t>(num_taxa_); size_t numClusters = nt; // keep list of nodes left to be clustered. initially all terminal nodes std::vector<Node *> nodes(nt); for (size_t i = 0; i < nt; i++) { auto * nd = new Node(); nd->setName(names_[i]); nd->setHeight(0.0); nodes[i] = nd; } while (numClusters > 1) { // 1. get smallest distance present in the matrix double minD = <API key>(dMatrix, ind1, ind2); left = nodes[ind1]; right = nodes[ind2]; // 2. create new ancestor node anc = new Node(); // 3. add nodes in new cluster above as children to new ancestor anc->addChild(*left); // addChild calls setParent anc->addChild(*right); // 4. compute edgelengths: half of the distance // edgelengths must subtract the existing height double newHeight = 0.5 * minD; left->setBL(newHeight - left->getHeight()); right->setBL(newHeight - right->getHeight()); // make sure to set the height of anc for the next iteration to use anc->setHeight(newHeight); // 5. compute new distance matrix (1 fewer rows & columns) // new distances are proportional averages (size of clusters) // new cluster is placed first (row & column) std::vector<double> avdists(numClusters, 0.0); double Lweight = left->isExternal() ? 1.0 : static_cast<double>(left->getChildCount()); double Rweight = right->isExternal() ? 1.0 : static_cast<double>(right->getChildCount()); for (unsigned long i = 0; i < numClusters; i++) { avdists[i] = ((dMatrix[ind1][i] * Lweight) + (dMatrix[ind2][i] * Rweight)) / (Lweight + Rweight); } numClusters std::vector< std::vector<double> > newDistances(numClusters, std::vector<double>(numClusters, 0.0)); // put in distances to new clusters first double tempDist = 0.0; unsigned long count = 0; for (size_t i = 0; i < nodes.size(); i++) { if (i != ind1 && i != ind2) { count++; tempDist = avdists[i]; newDistances[0][count] = tempDist; newDistances[count][0] = tempDist; } } // now, fill in remaining unsigned long icount = 1; auto ndsize = nodes.size(); for (size_t i = 0; i < ndsize; i++) { if (i != ind1 && i != ind2) { size_t jcount = 1; for (size_t j = 0; j < ndsize; j++) { if (j != ind1 && j != ind2) { newDistances[icount][jcount] = dMatrix[i][j]; newDistances[jcount][icount] = dMatrix[i][j]; jcount++; } } icount++; } } // replace distance matrix dMatrix = newDistances; // 6. finally, update node vector (1 shorter). new node always goes first) std::vector<Node *> newNodes(numClusters); newNodes[0] = anc; unsigned long counter = 1; for (unsigned long i = 0; i < ndsize; i++) { if (i != ind1 && i != ind2) { newNodes[counter] = nodes[i]; counter++; } } // replace node vector nodes = newNodes; } tree_ = new Tree(anc); tree_-><API key>(true); // used by newick writer } std::string UPGMA::get_newick () { if (newickstring_.empty()) { construct_tree(); } newickstring_ = getNewickString(tree_); return newickstring_; } std::vector< std::vector<double> > UPGMA::get_matrix () const { return full_distmatrix_; }
from .gaussian_process import <API key>, mean_field_logits from .<API key> import <API key>
package de.ubleipzig.iiifproducer.template; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import de.ubleipzig.iiif.vocabulary.IIIFEnum; /** * TemplateService. * * @author christopher-johnson */ @JsonPropertyOrder({"@context", "@id", "profile"}) public class TemplateService { @JsonProperty("@context") private String context = IIIFEnum.IMAGE_CONTEXT.IRIString(); @JsonProperty("@id") private String id; @JsonProperty private String profile = IIIFEnum.SERVICE_PROFILE.IRIString(); /** * @param id String */ public TemplateService(final String id) { this.id = id; } }
#ifndef __IMPEXINFO_H__ #define __IMPEXINFO_H__ #include <string> #include <list> #include <map> class Tag { public: enum Type { TYPE_INVALID = 0, TYPE_BOOL = 1, TYPE_INT = 2, TYPE_UINT32 = 3, TYPE_FLOAT = 4, TYPE_STRING = 5 }; protected: Tag( Type type, const std::string& id ) : m_type (type), m_id (id) { } virtual ~Tag() { } public: Type type() const { return m_type; }; std::string id() const { return m_id; }; template<class T> bool getValue( T& value ) const; template<class T> bool setValue( const T& value ); virtual std::string toString() const= 0; virtual void fromString( const std::string& str ) = 0; private: friend class TagMap; Type m_type; std::string m_id; }; class TagMap { public: typedef std::list<Tag *>::const_iterator const_tag_iterator; typedef std::map<std::string, std::list<Tag *> >::const_iterator <API key>; public: TagMap(); ~TagMap(); private: TagMap (const TagMap& other); TagMap& operator = (const TagMap& other); public: void clear(); bool containes( const std::string& id, const std::string& category = std::string() ) const; template<class T> void insert( const T& value, const std::string& id, const std::string& category = std::string() ); void remove( const std::string& id, const std::string& category = std::string() ); Tag *tag( const std::string& id, const std::string& category = std::string() ) const; <API key> begin() const ; <API key> end() const ; const_tag_iterator begin( <API key> iter ) const ; const_tag_iterator end( <API key> iter ) const ; private: typedef std::list<Tag *>::iterator tag_iterator; typedef std::map<std::string, std::list<Tag *> >::iterator category_iterator; std::map<std::string, std::list<Tag *> > m_data; }; /** * @brief ImageExportInfo class declaration. */ class ImageExportInfo : public TagMap { public: ImageExportInfo( const char *fileName ); ~ImageExportInfo(); public: const char *fileName() const; void write() const; private: std::string m_fileName; }; /* @} module_name_api*/ #endif /*__IMPEXINFO_H__*/
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using Hy.Common.Utility.Data; using System.Data.Common; using Hy.Check.Utility; namespace Hy.Check.UI.UC.Sundary { public class ResultDbOper { private IDbConnection m_ResultDbConn = null; public ResultDbOper(IDbConnection resultDb) { m_ResultDbConn = resultDb; } public DataTable GetAllResults() { DataTable res = new DataTable(); try { string strSql = string.Format("select RuleErrId,CheckType ,RuleInstID,RuleExeState,ErrorCount,TargetFeatClass1,GZBM,ErrorType from {0}", COMMONCONST.<API key>); return AdoDbHelper.GetDataTable(m_ResultDbConn, strSql); } catch { return res; } } public DataTable GetLayersResults() { DataTable res = new DataTable(); try { string strSql = string.Format("SELECT checkType,targetfeatclass1,sum(errorcount) as ErrCount,max(RuleErrID) as ruleId from {0} group by targetfeatclass1,checktype order by max(RuleErrID)", COMMONCONST.<API key>); return AdoDbHelper.GetDataTable(m_ResultDbConn, strSql); } catch { return res; } } public int GetResultsCount() { int count = 0; DbDataReader reader =null; try { string strSql = string.Format("select sum(errorcount) as cout from {0}", COMMONCONST.<API key>); reader = AdoDbHelper.GetQueryReader(m_ResultDbConn, strSql) as DbDataReader; if (reader.HasRows) { reader.Read(); count = int.Parse(reader[0].ToString()); } return count; } catch { return count; } finally { reader.Close(); reader.Dispose(); } } } }
<?php namespace MikroOdeme\Enum; class PaymentTypeId { CONST TEK_CEKIM = 1; CONST AYLIK_ABONELIK = 2; CONST HAFTALIK_ABONELIK = 3; CONST IKI_AYLIK_ABONELIK = 4; CONST UC_AYLIK_ABONELIK = 5; CONST ALTI_AYLIK_ABONELIK = 6; CONST AYLIK_DENEMELI = 7; CONST HAFTALIK_DENEMELI = 8; CONST <API key> = 9; CONST UC_AYLIK_DENEMELI = 10; CONST ALTI_AYLIK_DENEMELI = 11; CONST OTUZ_GUNLUK = 13; }
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using System; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; namespace ChummerHub.Areas.Identity.Pages.Account.Manage { #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member '<API key>' public class <API key> : PageModel #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member '<API key>' { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly ILogger<<API key>> _logger; #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member '<API key>.<API key>(UserManager<ApplicationUser>, SignInManager<ApplicationUser>, ILogger<<API key>>)' public <API key>( #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member '<API key>.<API key>(UserManager<ApplicationUser>, SignInManager<ApplicationUser>, ILogger<<API key>>)' UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ILogger<<API key>> logger) { _userManager = userManager; _signInManager = signInManager; _logger = logger; } [BindProperty] #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member '<API key>.Input' public InputModel Input { get; set; } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member '<API key>.Input' #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member '<API key>.InputModel' public class InputModel #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member '<API key>.InputModel' { [Required] [DataType(DataType.Password)] #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member '<API key>.InputModel.Password' public string Password { get; set; } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member '<API key>.InputModel.Password' } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member '<API key>.RequirePassword' public bool RequirePassword { get; set; } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member '<API key>.RequirePassword' #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member '<API key>.OnGet()' public async Task<IActionResult> OnGet() #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member '<API key>.OnGet()' { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } RequirePassword = await _userManager.HasPasswordAsync(user); return Page(); } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member '<API key>.OnPostAsync()' public async Task<IActionResult> OnPostAsync() #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member '<API key>.OnPostAsync()' { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } RequirePassword = await _userManager.HasPasswordAsync(user); if (RequirePassword) { if (!await _userManager.CheckPasswordAsync(user, Input.Password)) { ModelState.AddModelError(string.Empty, "Password not correct."); return Page(); } } var result = await _userManager.DeleteAsync(user); var userId = await _userManager.GetUserIdAsync(user); if (!result.Succeeded) { throw new <API key>($"Unexpected error occurred deleteing user with ID '{userId}'."); } await _signInManager.SignOutAsync(); _logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId); return Redirect("~/"); } } }
namespace Grove.Artifical.TargetingRules { using System; using System.Collections.Generic; using System.Linq; using Gameplay; using Gameplay.Effects; using Gameplay.Misc; using Gameplay.Targeting; public abstract class TargetingRule : MachinePlayRule { public int? TargetLimit; public bool <API key> = true; public override void Process(Artifical.ActivationContext c) { var excludeSelf = <API key> ? null : c.Card; var candidates = c.Selector.GenerateCandidates(c.TriggerMessage, excludeSelf); var parameters = new <API key>(candidates, c, Game); var targetsCombinations = (TargetLimit.HasValue ? SelectTargets(parameters).Take(TargetLimit.Value) : SelectTargets(parameters)) .ToList(); if (targetsCombinations.Count == 0) { if (c.CanCancel) { c.CancelActivation = true; return; } targetsCombinations = ForceSelectTargets(parameters) .Take(Ai.Parameters.TargetCount) .ToList(); } c.SetPossibleTargets(targetsCombinations); } protected abstract IEnumerable<Targets> SelectTargets(<API key> p); protected virtual IEnumerable<Targets> ForceSelectTargets(<API key> p) { return SelectTargets(p); } protected IEnumerable<T> None<T>() { yield break; } protected IList<Targets> Group(IEnumerable<Card> candidates, int minTargetCount, int? maxTargetCount = null, Action<ITarget, Targets> add = null) { return Group(candidates.Cast<ITarget>().ToList(), minTargetCount, maxTargetCount, add); } protected IList<Targets> Group(IEnumerable<Player> candidates, int minTargetCount, int? maxTargetCount = null, Action<ITarget, Targets> add = null) { return Group(candidates.Cast<ITarget>().ToList(), minTargetCount, maxTargetCount, add); } protected IList<Targets> Group(IEnumerable<Effect> candidates, int minTargetCount, int? maxTargetCount = null, Action<ITarget, Targets> add = null) { return Group(candidates.Cast<ITarget>().ToList(), minTargetCount, maxTargetCount, add); } protected IList<Targets> Group(IEnumerable<Card> candidates1, IEnumerable<Card> candidates2, Action<ITarget, Targets> add1 = null, Action<ITarget, Targets> add2 = null) { return Group(candidates1.Cast<ITarget>().ToList(), candidates2.Cast<ITarget>().ToList(), add1, add2); } protected IList<Targets> Group(IList<ITarget> candidates1, IList<ITarget> candidates2, Action<ITarget, Targets> add1 = null, Action<ITarget, Targets> add2 = null) { var results = new List<Targets>(); if (candidates1.Count == 0 || candidates2.Count == 0) return results; add1 = add1 ?? ((trg, trgts) => trgts.AddEffect(trg)); add2 = add2 ?? ((trg, trgts) => trgts.AddEffect(trg)); var index1 = 0; var index2 = 0; var groupCount = Math.Max(candidates1.Count, candidates2.Count); for (var i = 0; i < groupCount; i++) { // generate some options by mixing candidates // from 2 selectors var targets = new Targets(); add1(candidates1[index1], targets); add2(candidates2[index2], targets); index1++; index2++; if (index1 == candidates1.Count) index1 = 0; if (index2 == candidates2.Count) index2 = 0; results.Add(targets); } return results; } protected IList<Targets> Group(IList<ITarget> candidates, List<int> damageDistribution) { var result = new Targets(); foreach (var candidate in candidates) { result.AddEffect(candidate); } result.Distribution = damageDistribution; return new[] {result}; } protected IList<Targets> Group(IList<ITarget> candidates, int minTargetCount, int? maxTargetCount = null, Action<ITarget, Targets> add = null) { var results = new List<Targets>(); var targetCount = candidates.Count < maxTargetCount ? minTargetCount : maxTargetCount ?? minTargetCount; if (targetCount == 0) return results; if (candidates.Count < targetCount) return results; add = add ?? ((trg, trgts) => trgts.AddEffect(trg)); // generate possible groups by varying only the last element // since the number of different groups tried will be small // this is a reasonable approximation. var groupCount = candidates.Count - targetCount + 1; for (var i = 0; i < groupCount; i++) { var targets = new Targets(); // add first targetCount - 1 for (var j = 0; j < targetCount - 1; j++) { add(candidates[j], targets); } // add last add(candidates[targetCount - 1 + i], targets); results.Add(targets); } return results; } protected int <API key>(Card attacker) { if (!attacker.CanAttack) return -1; return Combat.CouldBeBlockedByAny(attacker) ? 2 * attacker.Power.GetValueOrDefault() + attacker.Toughness.GetValueOrDefault() : 5 * attacker.<API key>(singleDamageStep: false); } protected static int <API key>(Card creature) { if (!creature.IsAbleToAttack) return 0; var damage = creature.<API key>(singleDamageStep: false); if (creature.Has().AnyEvadingAbility) return 2 + damage; return damage; } protected int <API key>(Card card) { var count = Combat.<API key>(card); if (count > 0) { return count*10 + card.Toughness.GetValueOrDefault(); } return 0; } protected IEnumerable<Card> <API key>(int? powerIncrease, int? toughnessIncrease, <API key> p) { return p.Candidates<Card>(ControlledBy.SpellOwner) .Where(x => x.IsAttacker) .Select( x => new { Card = x, Gain = QuickCombat.<API key>( attacker: x, blockers: Combat.GetBlockers(x), powerIncrease: powerIncrease.Value, toughnessIncrease: toughnessIncrease.Value) }) .Where(x => x.Gain > 0) .OrderByDescending(x => x.Gain) .Select(x => x.Card); } protected IEnumerable<Card> <API key>(int? powerIncrease, int? toughnessIncrease, <API key> p) { return p.Candidates<Card>(ControlledBy.SpellOwner) .Where(x => x.IsBlocker) .Select( x => new { Card = x, Gain = QuickCombat.<API key>( blocker: x, attacker: Combat.GetAttacker(x), powerIncrease: powerIncrease.Value, toughnessIncrease: toughnessIncrease.Value) }) .Where(x => x.Gain > 0) .OrderByDescending(x => x.Gain) .Select(x => x.Card); } protected IEnumerable<Card> <API key>(<API key> p, Func<TargetsCandidates, IList<TargetCandidates>> selector = null) { return p.Candidates<Card>(ControlledBy.SpellOwner, selector: selector) .Where(x => Stack.<API key>(x.Card()) || Combat.<API key>(x.Card())); } protected static IEnumerable<Card> GetBounceCandidates(<API key> p, Func<TargetsCandidates, IList<TargetCandidates>> selector = null) { return p.Candidates<Card>(ControlledBy.Opponent, selector: selector) .Select(x => new { Card = x, Score = x.Owner == p.Controller ? 2*x.Score : x.Score }) .OrderByDescending(x => x.Score) .Select(x => x.Card); } } }
package com.pix.mind.controllers; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.Stage; import com.pix.mind.PixMindGame; import com.pix.mind.box2d.bodies.PixGuy; public class KeyboardController extends PixGuyController { boolean movingLeft = false; boolean movingRight = false; public KeyboardController(PixGuy pixGuy, Stage stage) { super(pixGuy); stage.addListener(new InputListener(){ @Override public boolean keyDown(InputEvent event, int keycode) { // TODO Auto-generated method stub if (keycode == Keys.LEFT) { movingLeft = true; movingRight = false; } if (keycode == Keys.RIGHT) { movingRight = true; movingLeft = false; } return true; } @Override public boolean keyUp(InputEvent event, int keycode) { // TODO Auto-generated method stub if (keycode == Keys.LEFT) { movingRight = true; movingLeft = false; } if (keycode == Keys.RIGHT) { movingLeft = true; movingRight = false; } if (!Gdx.input.isKeyPressed(Keys.RIGHT)&& !Gdx.input.isKeyPressed(Keys.LEFT)) { movingRight = false; movingLeft = false; } return true; } }); } public void movements() { if (movingLeft) { pixGuy.moveLeft(Gdx.graphics.getDeltaTime()); } if (movingRight) { pixGuy.moveRight(Gdx.graphics.getDeltaTime()); } if(!movingLeft&&!movingRight){ // if it is not touched, set horizontal velocity to 0 to // eliminate inercy. pixGuy.body.setLinearVelocity(0, pixGuy.body.getLinearVelocity().y); } } }
import unittest from test import support import os import io import socket import urllib.request from urllib.request import Request, OpenerDirector # XXX # Request # CacheFTPHandler (hard to write) # parse_keqv_list, parse_http_list, <API key> class TrivialTests(unittest.TestCase): def test_trivial(self): # A couple trivial tests self.assertRaises(ValueError, urllib.request.urlopen, 'bogus url') # XXX Name hacking to get this to work on Windows. fname = os.path.abspath(urllib.request.__file__).replace('\\', '/') # And more hacking to get it to work on MacOS. This assumes # urllib.pathname2url works, unfortunately... if os.name == 'mac': fname = '/' + fname.replace(':', '/') if os.name == 'nt': file_url = "file:///%s" % fname else: file_url = "file://%s" % fname f = urllib.request.urlopen(file_url) buf = f.read() f.close() def <API key>(self): tests = [ ('a,b,c', ['a', 'b', 'c']), ('path"o,l"og"i"cal, example', ['path"o,l"og"i"cal', 'example']), ('a, b, "c", "d", "e,f", g, h', ['a', 'b', '"c"', '"d"', '"e,f"', 'g', 'h']), ('a="b\\"c", d="e\\,f", g="h\\\\i"', ['a="b"c"', 'd="e,f"', 'g="h\\i"'])] for string, list in tests: self.assertEqual(urllib.request.parse_http_list(string), list) def <API key>(): def <API key>(): def <API key>(self): pass def test_<API key>(self): class MockOpener: addheaders = [] def open(self, req, data=None, timeout=socket.<API key>): self.req, self.data, self.timeout = req, data, timeout def error(self, proto, *args): self.proto, self.args = proto, args class MockFile: def read(self, count=None): pass def readline(self, count=None): pass def close(self): pass class MockHeaders(dict): def getheaders(self, name): return list(self.values()) class MockResponse(io.StringIO): def __init__(self, code, msg, headers, data, url=None): io.StringIO.__init__(self, data) self.code, self.msg, self.headers, self.url = code, msg, headers, url def info(self): return self.headers def geturl(self): return self.url class MockCookieJar: def add_cookie_header(self, request): self.ach_req = request def extract_cookies(self, response, request): self.ec_req, self.ec_r = request, response class FakeMethod: def __init__(self, meth_name, action, handle): self.meth_name = meth_name self.handle = handle self.action = action def __call__(self, *args): return self.handle(self.meth_name, self.action, *args) class MockHTTPResponse(io.IOBase): def __init__(self, fp, msg, status, reason): self.fp = fp self.msg = msg self.status = status self.reason = reason self.code = 200 def read(self): return '' def info(self): return {} def geturl(self): return self.url class MockHTTPClass: def __init__(self): self.level = 0 self.req_headers = [] self.data = None self.raise_on_endheaders = False self._tunnel_headers = {} def __call__(self, host, timeout=socket.<API key>): self.host = host self.timeout = timeout return self def set_debuglevel(self, level): self.level = level def _set_tunnel(self, host, port=None, headers=None): self._tunnel_host = host self._tunnel_port = port if headers: self._tunnel_headers = headers else: self._tunnel_headers.clear() def request(self, method, url, body=None, headers=None): self.method = method self.selector = url if headers is not None: self.req_headers += headers.items() self.req_headers.sort() if body: self.data = body if self.raise_on_endheaders: import socket raise socket.error() def getresponse(self): return MockHTTPResponse(MockFile(), {}, 200, "OK") class MockHandler: # useful for testing handler machinery # see <API key>() docstring handler_order = 500 def __init__(self, methods): self._define_methods(methods) def _define_methods(self, methods): for spec in methods: if len(spec) == 2: name, action = spec else: name, action = spec, None meth = FakeMethod(name, action, self.handle) setattr(self.__class__, name, meth) def handle(self, fn_name, action, *args, **kwds): self.parent.calls.append((self, fn_name, args, kwds)) if action is None: return None elif action == "return self": return self elif action == "return response": res = MockResponse(200, "OK", {}, "") return res elif action == "return request": return Request("http://blah/") elif action.startswith("error"): code = action[action.rfind(" ")+1:] try: code = int(code) except ValueError: pass res = MockResponse(200, "OK", {}, "") return self.parent.error("http", args[0], res, code, "", {}) elif action == "raise": raise urllib.error.URLError("blah") assert False def close(self): pass def add_parent(self, parent): self.parent = parent self.parent.calls = [] def __lt__(self, other): if not hasattr(other, "handler_order"): # No handler_order, leave in original order. Yuck. return True return self.handler_order < other.handler_order def <API key>(opener, meth_spec): """Create MockHandlers and add them to an OpenerDirector. meth_spec: list of lists of tuples and strings defining methods to define on handlers. eg: [["http_error", "ftp_open"], ["http_open"]] defines methods .http_error() and .ftp_open() on one handler, and .http_open() on another. These methods just record their arguments and return None. Using a tuple instead of a string causes the method to perform some action (see MockHandler.handle()), eg: [["http_error"], [("http_open", "return request")]] defines .http_error() on one handler (which simply returns None), and .http_open() on another handler, which returns a Request object. """ handlers = [] count = 0 for meths in meth_spec: class MockHandlerSubclass(MockHandler): pass h = MockHandlerSubclass(meths) h.handler_order += count h.add_parent(opener) count = count + 1 handlers.append(h) opener.add_handler(h) return handlers def build_test_opener(*handler_instances): opener = OpenerDirector() for h in handler_instances: opener.add_handler(h) return opener class MockHTTPHandler(urllib.request.BaseHandler): # useful for testing redirections and auth # sends supplied headers and code as first response # sends 200 OK as second response def __init__(self, code, headers): self.code = code self.headers = headers self.reset() def reset(self): self._count = 0 self.requests = [] def http_open(self, req): import email, http.client, copy from io import StringIO self.requests.append(copy.deepcopy(req)) if self._count == 0: self._count = self._count + 1 name = http.client.responses[self.code] msg = email.message_from_string(self.headers) return self.parent.error( "http", req, MockFile(), self.code, name, msg) else: self.req = req msg = email.message_from_string("\r\n\r\n") return MockResponse(200, "OK", msg, "", req.get_full_url()) class MockHTTPSHandler(urllib.request.AbstractHTTPHandler): # Useful for testing the Proxy-Authorization request by verifying the # properties of httpcon def __init__(self): urllib.request.AbstractHTTPHandler.__init__(self) self.httpconn = MockHTTPClass() def https_open(self, req): return self.do_open(self.httpconn, req) class MockPasswordManager: def add_password(self, realm, uri, user, password): self.realm = realm self.url = uri self.user = user self.password = password def find_user_password(self, realm, authuri): self.target_realm = realm self.target_url = authuri return self.user, self.password class OpenerDirectorTests(unittest.TestCase): def <API key>(self): class NonHandler(object): pass self.assertRaises(TypeError, OpenerDirector().add_handler, NonHandler()) def <API key>(self): # test work-around for three methods that accidentally follow the # naming conventions for handler methods # (*_open() / *_request() / *_response()) # These used to call the accidentally-named methods, causing a # TypeError in real code; here, returning self from these mock # methods would either cause no exception, or AttributeError. from urllib.error import URLError o = OpenerDirector() meth_spec = [ [("do_open", "return self"), ("proxy_open", "return self")], [("redirect_request", "return self")], ] handlers = <API key>(o, meth_spec) o.add_handler(urllib.request.UnknownHandler()) for scheme in "do", "proxy", "redirect": self.assertRaises(URLError, o.open, scheme+"://example.com/") def test_handled(self): # handler returning non-None means no more handlers will be called o = OpenerDirector() meth_spec = [ ["http_open", "ftp_open", "http_error_302"], ["ftp_open"], [("http_open", "return self")], [("http_open", "return self")], ] handlers = <API key>(o, meth_spec) req = Request("http://example.com/") r = o.open(req) # Second .http_open() gets called, third doesn't, since second returned # non-None. Handlers without .http_open() never get any methods called # on them. # In fact, second mock handler defining .http_open() returns self # (instead of response), which becomes the OpenerDirector's return # value. self.assertEqual(r, handlers[2]) calls = [(handlers[0], "http_open"), (handlers[2], "http_open")] for expected, got in zip(calls, o.calls): handler, name, args, kwds = got self.assertEqual((handler, name), expected) self.assertEqual(args, (req,)) def test_handler_order(self): o = OpenerDirector() handlers = [] for meths, handler_order in [ ([("http_open", "return self")], 500), (["http_open"], 0), ]: class MockHandlerSubclass(MockHandler): pass h = MockHandlerSubclass(meths) h.handler_order = handler_order handlers.append(h) o.add_handler(h) r = o.open("http://example.com/") # handlers called in reverse order, thanks to their sort order self.assertEqual(o.calls[0][0], handlers[1]) self.assertEqual(o.calls[1][0], handlers[0]) def test_raise(self): # raising URLError stops processing of request o = OpenerDirector() meth_spec = [ [("http_open", "raise")], [("http_open", "return self")], ] handlers = <API key>(o, meth_spec) req = Request("http://example.com/") self.assertRaises(urllib.error.URLError, o.open, req) self.assertEqual(o.calls, [(handlers[0], "http_open", (req,), {})]) ## def test_error(self): ## # XXX this doesn't actually seem to be used in standard library, ## # but should really be tested anyway... def test_http_error(self): # XXX http_error_default # http errors are a special case o = OpenerDirector() meth_spec = [ [("http_open", "error 302")], [("http_error_400", "raise"), "http_open"], [("http_error_302", "return response"), "http_error_303", "http_error"], [("http_error_302")], ] handlers = <API key>(o, meth_spec) class Unknown: def __eq__(self, other): return True req = Request("http://example.com/") r = o.open(req) assert len(o.calls) == 2 calls = [(handlers[0], "http_open", (req,)), (handlers[2], "http_error_302", (req, Unknown(), 302, "", {}))] for expected, got in zip(calls, o.calls): handler, method_name, args = expected self.assertEqual((handler, method_name), got[:2]) self.assertEqual(args, got[2]) def test_processors(self): # *_request / *_response methods get called appropriately o = OpenerDirector() meth_spec = [ [("http_request", "return request"), ("http_response", "return response")], [("http_request", "return request"), ("http_response", "return response")], ] handlers = <API key>(o, meth_spec) req = Request("http://example.com/") r = o.open(req) # processor methods are called on *all* handlers that define them, # not just the first handler that handles the request calls = [ (handlers[0], "http_request"), (handlers[1], "http_request"), (handlers[0], "http_response"), (handlers[1], "http_response")] for i, (handler, name, args, kwds) in enumerate(o.calls): if i < 2: # *_request self.assertEqual((handler, name), calls[i]) self.assertEqual(len(args), 1) self.assertTrue(isinstance(args[0], Request)) else: # *_response self.assertEqual((handler, name), calls[i]) self.assertEqual(len(args), 2) self.assertTrue(isinstance(args[0], Request)) # response from opener.open is None, because there's no # handler that defines http_open to handle it self.assertTrue(args[1] is None or isinstance(args[1], MockResponse)) def sanepathname2url(path): urlpath = urllib.request.pathname2url(path) if os.name == "nt" and urlpath.startswith(" urlpath = urlpath[2:] # XXX don't ask me about the mac... return urlpath class HandlerTests(unittest.TestCase): def test_ftp(self): class MockFTPWrapper: def __init__(self, data): self.data = data def retrfile(self, filename, filetype): self.filename, self.filetype = filename, filetype return io.StringIO(self.data), len(self.data) class NullFTPHandler(urllib.request.FTPHandler): def __init__(self, data): self.data = data def connect_ftp(self, user, passwd, host, port, dirs, timeout=socket.<API key>): self.user, self.passwd = user, passwd self.host, self.port = host, port self.dirs = dirs self.ftpwrapper = MockFTPWrapper(self.data) return self.ftpwrapper import ftplib data = "rheum rhaponicum" h = NullFTPHandler(data) o = h.parent = MockOpener() for url, host, port, user, passwd, type_, dirs, filename, mimetype in [ ("ftp://localhost/foo/bar/baz.html", "localhost", ftplib.FTP_PORT, "", "", "I", ["foo", "bar"], "baz.html", "text/html"), ("ftp://parrot@localhost/foo/bar/baz.html", "localhost", ftplib.FTP_PORT, "parrot", "", "I", ["foo", "bar"], "baz.html", "text/html"), ("ftp://%25parrot@localhost/foo/bar/baz.html", "localhost", ftplib.FTP_PORT, "%parrot", "", "I", ["foo", "bar"], "baz.html", "text/html"), ("ftp://%2542parrot@localhost/foo/bar/baz.html", "localhost", ftplib.FTP_PORT, "%42parrot", "", "I", ["foo", "bar"], "baz.html", "text/html"), ("ftp://localhost:80/foo/bar/", "localhost", 80, "", "", "D", ["foo", "bar"], "", None), ("ftp://localhost/baz.gif;type=a", "localhost", ftplib.FTP_PORT, "", "", "A", [], "baz.gif", None), # XXX really this should guess image/gif ]: req = Request(url) req.timeout = None r = h.ftp_open(req) # ftp authentication not yet implemented by FTPHandler self.assertEqual(h.user, user) self.assertEqual(h.passwd, passwd) self.assertEqual(h.host, socket.gethostbyname(host)) self.assertEqual(h.port, port) self.assertEqual(h.dirs, dirs) self.assertEqual(h.ftpwrapper.filename, filename) self.assertEqual(h.ftpwrapper.filetype, type_) headers = r.info() self.assertEqual(headers.get("Content-type"), mimetype) self.assertEqual(int(headers["Content-length"]), len(data)) def test_file(self): import email.utils, socket h = urllib.request.FileHandler() o = h.parent = MockOpener() TESTFN = support.TESTFN urlpath = sanepathname2url(os.path.abspath(TESTFN)) towrite = b"hello, world\n" urls = [ "file://localhost%s" % urlpath, "file://%s" % urlpath, "file://%s%s" % (socket.gethostbyname('localhost'), urlpath), ] try: localaddr = socket.gethostbyname(socket.gethostname()) except socket.gaierror: localaddr = '' if localaddr: urls.append("file://%s%s" % (localaddr, urlpath)) for url in urls: f = open(TESTFN, "wb") try: try: f.write(towrite) finally: f.close() r = h.file_open(Request(url)) try: data = r.read() headers = r.info() respurl = r.geturl() finally: r.close() stats = os.stat(TESTFN) modified = email.utils.formatdate(stats.st_mtime, usegmt=True) finally: os.remove(TESTFN) self.assertEqual(data, towrite) self.assertEqual(headers["Content-type"], "text/plain") self.assertEqual(headers["Content-length"], "13") self.assertEqual(headers["Last-modified"], modified) self.assertEqual(respurl, url) for url in [ "file://localhost:80%s" % urlpath, "file:///file_does_not_exist.txt", "file://%s:80%s/%s" % (socket.gethostbyname('localhost'), os.getcwd(), TESTFN), "file://somerandomhost.ontheinternet.com%s/%s" % (os.getcwd(), TESTFN), ]: try: f = open(TESTFN, "wb") try: f.write(towrite) finally: f.close() self.assertRaises(urllib.error.URLError, h.file_open, Request(url)) finally: os.remove(TESTFN) h = urllib.request.FileHandler() o = h.parent = MockOpener() # XXXX why does // mean ftp (and /// mean not ftp!), and where # is file: scheme specified? I think this is really a bug, and # what was intended was to distinguish between URLs like: # file:/blah.txt (a file) # file://localhost/blah.txt (a file) # file:///blah.txt (a file) # file://ftp.example.com/blah.txt (an ftp URL) for url, ftp in [ ("file://ftp.example.com//foo.txt", True), ("file://ftp.example.com///foo.txt", False), # XXXX bug: fails with OSError, should be URLError ("file://ftp.example.com/foo.txt", False), ("file://somehost//foo/something.txt", True), ("file://localhost//foo/something.txt", False), ]: req = Request(url) try: h.file_open(req) # XXXX remove OSError when bug fixed except (urllib.error.URLError, OSError): self.assertFalse(ftp) else: self.assertIs(o.req, req) self.assertEqual(req.type, "ftp") self.assertEqual(req.type is "ftp", ftp) def test_http(self): h = urllib.request.AbstractHTTPHandler() o = h.parent = MockOpener() url = "http://example.com/" for method, data in [("GET", None), ("POST", "blah")]: req = Request(url, data, {"Foo": "bar"}) req.timeout = None req.<API key>("Spam", "eggs") http = MockHTTPClass() r = h.do_open(http, req) # result attributes r.read; r.readline # wrapped MockFile methods r.info; r.geturl # addinfourl methods r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply() hdrs = r.info() hdrs.get; hdrs.__contains__ # r.info() gives dict from .getreply() self.assertEqual(r.geturl(), url) self.assertEqual(http.host, "example.com") self.assertEqual(http.level, 0) self.assertEqual(http.method, method) self.assertEqual(http.selector, "/") self.assertEqual(http.req_headers, [("Connection", "close"), ("Foo", "bar"), ("Spam", "eggs")]) self.assertEqual(http.data, data) # check socket.error converted to URLError http.raise_on_endheaders = True self.assertRaises(urllib.error.URLError, h.do_open, http, req) # check adding of standard headers o.addheaders = [("Spam", "eggs")] for data in "", None: # POST, GET req = Request("http://example.com/", data) r = MockResponse(200, "OK", {}, "") newreq = h.do_request_(req) if data is None: # GET self.assertTrue("Content-length" not in req.unredirected_hdrs) self.assertTrue("Content-type" not in req.unredirected_hdrs) else: # POST self.assertEqual(req.unredirected_hdrs["Content-length"], "0") self.assertEqual(req.unredirected_hdrs["Content-type"], "application/<API key>") # XXX the details of Host could be better tested self.assertEqual(req.unredirected_hdrs["Host"], "example.com") self.assertEqual(req.unredirected_hdrs["Spam"], "eggs") # don't clobber existing headers req.<API key>("Content-length", "foo") req.<API key>("Content-type", "bar") req.<API key>("Host", "baz") req.<API key>("Spam", "foo") newreq = h.do_request_(req) self.assertEqual(req.unredirected_hdrs["Content-length"], "foo") self.assertEqual(req.unredirected_hdrs["Content-type"], "bar") self.assertEqual(req.unredirected_hdrs["Host"], "baz") self.assertEqual(req.unredirected_hdrs["Spam"], "foo") def <API key>(self): # Checks the presence of any unnecessary double slash in url does not # break anything. Previously, a double slash directly after the host # could could cause incorrect parsing. h = urllib.request.AbstractHTTPHandler() o = h.parent = MockOpener() data = "" ds_urls = [ "http://example.com/foo/bar/baz.html", "http://example.com//foo/bar/baz.html", "http://example.com/foo//bar/baz.html", "http://example.com/foo/bar//baz.html" ] for ds_url in ds_urls: ds_req = Request(ds_url, data) # Check whether host is determined correctly if there is no proxy np_ds_req = h.do_request_(ds_req) self.assertEqual(np_ds_req.unredirected_hdrs["Host"],"example.com") # Check whether host is determined correctly if there is a proxy ds_req.set_proxy("someproxy:3128",None) p_ds_req = h.do_request_(ds_req) self.assertEqual(p_ds_req.unredirected_hdrs["Host"],"example.com") def <API key>(self): # Issue4493: urllib2 to supply '/' when to urls where path does not # start with'/' h = urllib.request.AbstractHTTPHandler() o = h.parent = MockOpener() weird_url = 'http: req = Request(weird_url) newreq = h.do_request_(req) self.assertEqual(newreq.host,'www.python.org') self.assertEqual(newreq.selector,'/?getspam') url_without_path = 'http: req = Request(url_without_path) newreq = h.do_request_(req) self.assertEqual(newreq.host,'www.python.org') self.assertEqual(newreq.selector,'') def test_errors(self): h = urllib.request.HTTPErrorProcessor() o = h.parent = MockOpener() url = "http://example.com/" req = Request(url) # all 2xx are passed through r = MockResponse(200, "OK", {}, "", url) newr = h.http_response(req, r) self.assertIs(r, newr) self.assertFalse(hasattr(o, "proto")) # o.error not called r = MockResponse(202, "Accepted", {}, "", url) newr = h.http_response(req, r) self.assertIs(r, newr) self.assertFalse(hasattr(o, "proto")) # o.error not called r = MockResponse(206, "Partial content", {}, "", url) newr = h.http_response(req, r) self.assertIs(r, newr) self.assertFalse(hasattr(o, "proto")) # o.error not called # anything else calls o.error (and MockOpener returns None, here) r = MockResponse(502, "Bad gateway", {}, "", url) self.assertIsNone(h.http_response(req, r)) self.assertEqual(o.proto, "http") # o.error called self.assertEqual(o.args, (req, r, 502, "Bad gateway", {})) def test_cookies(self): cj = MockCookieJar() h = urllib.request.HTTPCookieProcessor(cj) o = h.parent = MockOpener() req = Request("http://example.com/") r = MockResponse(200, "OK", {}, "") newreq = h.http_request(req) self.assertIs(cj.ach_req, req) self.assertIs(cj.ach_req, newreq) self.assertEqual(req.get_origin_req_host(), "example.com") self.assertFalse(req.is_unverifiable()) newr = h.http_response(req, r) self.assertIs(cj.ec_req, req) self.assertIs(cj.ec_r, r) self.assertIs(r, newr) def test_redirect(self): from_url = "http://example.com/a.html" to_url = "http://example.com/b.html" h = urllib.request.HTTPRedirectHandler() o = h.parent = MockOpener() # ordinary redirect behaviour for code in 301, 302, 303, 307: for data in None, "blah\nblah\n": method = getattr(h, "http_error_%s" % code) req = Request(from_url, data) req.timeout = socket.<API key> req.add_header("Nonsense", "viking=withhold") if data is not None: req.add_header("Content-Length", str(len(data))) req.<API key>("Spam", "spam") try: method(req, MockFile(), code, "Blah", MockHeaders({"location": to_url})) except urllib.error.HTTPError: # 307 in response to POST requires user OK self.assertTrue(code == 307 and data is not None) self.assertEqual(o.req.get_full_url(), to_url) try: self.assertEqual(o.req.get_method(), "GET") except AttributeError: self.assertFalse(o.req.has_data()) # now it's a GET, there should not be headers regarding content # (possibly dragged from before being a POST) headers = [x.lower() for x in o.req.headers] self.assertTrue("content-length" not in headers) self.assertTrue("content-type" not in headers) self.assertEqual(o.req.headers["Nonsense"], "viking=withhold") self.assertTrue("Spam" not in o.req.headers) self.assertTrue("Spam" not in o.req.unredirected_hdrs) # loop detection req = Request(from_url) req.timeout = socket.<API key> def redirect(h, req, url=to_url): h.http_error_302(req, MockFile(), 302, "Blah", MockHeaders({"location": url})) # Note that the *original* request shares the same record of # redirections with the sub-requests caused by the redirections. # detect infinite loop redirect of a URL to itself req = Request(from_url, origin_req_host="example.com") count = 0 req.timeout = socket.<API key> try: while 1: redirect(h, req, "http://example.com/") count = count + 1 except urllib.error.HTTPError: # don't stop until max_repeats, because cookies may introduce state self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_repeats) # detect endless non-repeating chain of redirects req = Request(from_url, origin_req_host="example.com") count = 0 req.timeout = socket.<API key> try: while 1: redirect(h, req, "http://example.com/%d" % count) count = count + 1 except urllib.error.HTTPError: self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_redirections) def <API key>(self): # cookies shouldn't leak into redirected requests from http.cookiejar import CookieJar from test.test_http_cookiejar import interact_netscape cj = CookieJar() interact_netscape(cj, "http: hh = MockHTTPHandler(302, "Location: http: hdeh = urllib.request.<API key>() hrh = urllib.request.HTTPRedirectHandler() cp = urllib.request.HTTPCookieProcessor(cj) o = build_test_opener(hh, hdeh, hrh, cp) o.open("http: self.assertFalse(hh.req.has_header("Cookie")) def test_proxy(self): o = OpenerDirector() ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128")) o.add_handler(ph) meth_spec = [ [("http_open", "return response")] ] handlers = <API key>(o, meth_spec) req = Request("http://acme.example.com/") self.assertEqual(req.get_host(), "acme.example.com") r = o.open(req) self.assertEqual(req.get_host(), "proxy.example.com:3128") self.assertEqual([(handlers[0], "http_open")], [tup[0:2] for tup in o.calls]) def test_proxy_no_proxy(self): os.environ['no_proxy'] = 'python.org' o = OpenerDirector() ph = urllib.request.ProxyHandler(dict(http="proxy.example.com")) o.add_handler(ph) req = Request("http: self.assertEqual(req.get_host(), "www.perl.org") r = o.open(req) self.assertEqual(req.get_host(), "proxy.example.com") req = Request("http: self.assertEqual(req.get_host(), "www.python.org") r = o.open(req) self.assertEqual(req.get_host(), "www.python.org") del os.environ['no_proxy'] def test_proxy_https(self): o = OpenerDirector() ph = urllib.request.ProxyHandler(dict(https="proxy.example.com:3128")) o.add_handler(ph) meth_spec = [ [("https_open", "return response")] ] handlers = <API key>(o, meth_spec) req = Request("https: self.assertEqual(req.get_host(), "www.example.com") r = o.open(req) self.assertEqual(req.get_host(), "proxy.example.com:3128") self.assertEqual([(handlers[0], "https_open")], [tup[0:2] for tup in o.calls]) def <API key>(self): o = OpenerDirector() ph = urllib.request.ProxyHandler(dict(https='proxy.example.com:3128')) o.add_handler(ph) https_handler = MockHTTPSHandler() o.add_handler(https_handler) req = Request("https: req.add_header("Proxy-Authorization","FooBar") req.add_header("User-Agent","Grail") self.assertEqual(req.get_host(), "www.example.com") self.assertIsNone(req._tunnel_host) r = o.open(req) # Verify Proxy-Authorization gets tunneled to request. # httpsconn req_headers do not have the Proxy-Authorization header but # the req will have. self.assertFalse(("Proxy-Authorization","FooBar") in https_handler.httpconn.req_headers) self.assertTrue(("User-Agent","Grail") in https_handler.httpconn.req_headers) self.assertIsNotNone(req._tunnel_host) self.assertEqual(req.get_host(), "proxy.example.com:3128") self.assertEqual(req.get_header("Proxy-authorization"),"FooBar") def test_basic_auth(self, quote_char='"'): opener = OpenerDirector() password_manager = MockPasswordManager() auth_handler = urllib.request.<API key>(password_manager) realm = "ACME Widget Store" http_handler = MockHTTPHandler( 401, 'WWW-Authenticate: Basic realm=%s%s%s\r\n\r\n' % (quote_char, realm, quote_char) ) opener.add_handler(auth_handler) opener.add_handler(http_handler) self._test_basic_auth(opener, auth_handler, "Authorization", realm, http_handler, password_manager, "http://acme.example.com/protected", "http://acme.example.com/protected", ) def test_basic_<API key>(self): self.test_basic_auth(quote_char="'") def <API key>(self): opener = OpenerDirector() ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128")) opener.add_handler(ph) password_manager = MockPasswordManager() auth_handler = urllib.request.<API key>(password_manager) realm = "ACME Networks" http_handler = MockHTTPHandler( 407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm) opener.add_handler(auth_handler) opener.add_handler(http_handler) self._test_basic_auth(opener, auth_handler, "Proxy-authorization", realm, http_handler, password_manager, "http://acme.example.com:3128/protected", "proxy.example.com:3128", ) def <API key>(self): # <API key> threw an exception if it couldn't handle a 40* # return None to allow another handler (especially # <API key>) to handle the response. # try digest first (since it's the strongest auth scheme), so we record # order of calls here to check digest comes first: class <API key>(OpenerDirector): def __init__(self): OpenerDirector.__init__(self) self.recorded = [] def record(self, info): self.recorded.append(info) class <API key>(urllib.request.<API key>): def http_error_401(self, *args, **kwds): self.parent.record("digest") urllib.request.<API key>.http_error_401(self, *args, **kwds) class <API key>(urllib.request.<API key>): def http_error_401(self, *args, **kwds): self.parent.record("basic") urllib.request.<API key>.http_error_401(self, *args, **kwds) opener = <API key>() password_manager = MockPasswordManager() digest_handler = <API key>(password_manager) basic_handler = <API key>(password_manager) realm = "ACME Networks" http_handler = MockHTTPHandler( 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm) opener.add_handler(basic_handler) opener.add_handler(digest_handler) opener.add_handler(http_handler) # check basic auth isn't blocked by digest handler failing self._test_basic_auth(opener, basic_handler, "Authorization", realm, http_handler, password_manager, "http://acme.example.com/protected", "http://acme.example.com/protected", ) # check digest was tried before basic (twice, because # _test_basic_auth called .open() twice) self.assertEqual(opener.recorded, ["digest", "basic"]*2) def _test_basic_auth(self, opener, auth_handler, auth_header, realm, http_handler, password_manager, request_url, protected_url): import base64 user, password = "wile", "coyote" # .add_password() fed through to password manager auth_handler.add_password(realm, request_url, user, password) self.assertEqual(realm, password_manager.realm) self.assertEqual(request_url, password_manager.url) self.assertEqual(user, password_manager.user) self.assertEqual(password, password_manager.password) r = opener.open(request_url) # should have asked the password manager for the username/password self.assertEqual(password_manager.target_realm, realm) self.assertEqual(password_manager.target_url, protected_url) # expect one request without authorization, then one with self.assertEqual(len(http_handler.requests), 2) self.assertFalse(http_handler.requests[0].has_header(auth_header)) userpass = bytes('%s:%s' % (user, password), "ascii") auth_hdr_value = ('Basic ' + base64.encodebytes(userpass).strip().decode()) self.assertEqual(http_handler.requests[1].get_header(auth_header), auth_hdr_value) self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header], auth_hdr_value) # if the password manager can't find a password, the handler won't # handle the HTTP auth error password_manager.user = password_manager.password = None http_handler.reset() r = opener.open(request_url) self.assertEqual(len(http_handler.requests), 1) self.assertFalse(http_handler.requests[0].has_header(auth_header)) class MiscTests(unittest.TestCase): def test_build_opener(self): class MyHTTPHandler(urllib.request.HTTPHandler): pass class FooHandler(urllib.request.BaseHandler): def foo_open(self): pass class BarHandler(urllib.request.BaseHandler): def bar_open(self): pass build_opener = urllib.request.build_opener o = build_opener(FooHandler, BarHandler) self.opener_has_handler(o, FooHandler) self.opener_has_handler(o, BarHandler) # can take a mix of classes and instances o = build_opener(FooHandler, BarHandler()) self.opener_has_handler(o, FooHandler) self.opener_has_handler(o, BarHandler) # subclasses of default handlers override default handlers o = build_opener(MyHTTPHandler) self.opener_has_handler(o, MyHTTPHandler) # a particular case of overriding: default handlers can be passed # in explicitly o = build_opener() self.opener_has_handler(o, urllib.request.HTTPHandler) o = build_opener(urllib.request.HTTPHandler) self.opener_has_handler(o, urllib.request.HTTPHandler) o = build_opener(urllib.request.HTTPHandler()) self.opener_has_handler(o, urllib.request.HTTPHandler) # Issue2670: multiple handlers sharing the same base class class MyOtherHTTPHandler(urllib.request.HTTPHandler): pass o = build_opener(MyHTTPHandler, MyOtherHTTPHandler) self.opener_has_handler(o, MyHTTPHandler) self.opener_has_handler(o, MyOtherHTTPHandler) def opener_has_handler(self, opener, handler_class): self.assertTrue(any(h.__class__ == handler_class for h in opener.handlers)) class RequestTests(unittest.TestCase): def setUp(self): self.get = Request("http: self.post = Request("http: "data", headers={"X-Test": "test"}) def test_method(self): self.assertEqual("POST", self.post.get_method()) self.assertEqual("GET", self.get.get_method()) def test_add_data(self): self.assertFalse(self.get.has_data()) self.assertEqual("GET", self.get.get_method()) self.get.add_data("spam") self.assertTrue(self.get.has_data()) self.assertEqual("POST", self.get.get_method()) def test_get_full_url(self): self.assertEqual("http: self.get.get_full_url()) def test_selector(self): self.assertEqual("/~jeremy/", self.get.get_selector()) req = Request("http: self.assertEqual("/", req.get_selector()) def test_get_type(self): self.assertEqual("http", self.get.get_type()) def test_get_host(self): self.assertEqual("www.python.org", self.get.get_host()) def <API key>(self): req = Request("http: self.assertEqual("www.python.org", req.get_host()) def test_proxy(self): self.assertFalse(self.get.has_proxy()) self.get.set_proxy("www.perl.org", "http") self.assertTrue(self.get.has_proxy()) self.assertEqual("www.python.org", self.get.get_origin_req_host()) self.assertEqual("www.perl.org", self.get.get_host()) def test_wrapped_url(self): req = Request("<URL:http: self.assertEqual("www.python.org", req.get_host()) def <API key>(self): req = Request("http://www.python.org/?qs=query#fragment=true") self.assertEqual("/?qs=query", req.get_selector()) req = Request("http://www.python.org/#fun=true") self.assertEqual("/", req.get_selector()) def test_main(verbose=None): from test import test_urllib2 support.run_doctest(test_urllib2, verbose) support.run_doctest(urllib.request, verbose) tests = (TrivialTests, OpenerDirectorTests, HandlerTests, MiscTests, RequestTests) support.run_unittest(*tests) if __name__ == "__main__": test_main(verbose=True)
package com.wongsir.newsgathering.model.commons; import com.google.common.base.MoreObjects; import com.google.gson.annotations.SerializedName; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; /** * @Description: TODO * @author Wongsir * @date 201714 * */ public class Webpage { public List<String> attachmentList; public List<String> imageList; private String content; private String title; private String url; private String domain; /** * id,taskid */ private String spiderUUID; @SerializedName("spiderInfoId") private String spiderInfoId; private String category; private String rawHTML; private List<String> keywords; private List<String> summary; @SerializedName("gatherTime") private Date gathertime; /** * id,es */ private String id; private Date publishTime; private Map<String, Set<String>> namedEntity; private Map<String, Object> dynamicFields; private Map<String, Object> staticFields; private long processTime; public Map<String, Object> getStaticFields() { return staticFields; } public Webpage setStaticFields(Map<String, Object> staticFields) { this.staticFields = staticFields; return this; } public Map<String, Set<String>> getNamedEntity() { return namedEntity; } public Webpage setNamedEntity(Map<String, Set<String>> namedEntity) { this.namedEntity = namedEntity; return this; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = domain; } public String getSpiderInfoId() { return spiderInfoId; } public void setSpiderInfoId(String spiderInfoId) { this.spiderInfoId = spiderInfoId; } public Date getGathertime() { return gathertime; } public void setGathertime(Date gathertime) { this.gathertime = gathertime; } public String getSpiderUUID() { return spiderUUID; } public void setSpiderUUID(String spiderUUID) { this.spiderUUID = spiderUUID; } public String getId() { return id; } public void setId(String id) { this.id = id; } public List<String> getKeywords() { return keywords; } public Webpage setKeywords(List<String> keywords) { this.keywords = keywords; return this; } public List<String> getSummary() { return summary; } public Webpage setSummary(List<String> summary) { this.summary = summary; return this; } public Date getPublishTime() { return publishTime; } public Webpage setPublishTime(Date publishTime) { this.publishTime = publishTime; return this; } public String getCategory() { return category; } public Webpage setCategory(String category) { this.category = category; return this; } public String getRawHTML() { return rawHTML; } public Webpage setRawHTML(String rawHTML) { this.rawHTML = rawHTML; return this; } public Map<String, Object> getDynamicFields() { return dynamicFields; } public Webpage setDynamicFields(Map<String, Object> dynamicFields) { this.dynamicFields = dynamicFields; return this; } public List<String> getAttachmentList() { return attachmentList; } public Webpage setAttachmentList(List<String> attachmentList) { this.attachmentList = attachmentList; return this; } public List<String> getImageList() { return imageList; } public Webpage setImageList(List<String> imageList) { this.imageList = imageList; return this; } public long getProcessTime() { return processTime; } public Webpage setProcessTime(long processTime) { this.processTime = processTime; return this; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("content", content) .add("title", title) .add("url", url) .add("domain", domain) .add("spiderUUID", spiderUUID) .add("spiderInfoId", spiderInfoId) .add("category", category) .add("rawHTML", rawHTML) .add("keywords", keywords) .add("summary", summary) .add("gathertime", gathertime) .add("id", id) .add("publishTime", publishTime) .add("namedEntity", namedEntity) .add("dynamicFields", dynamicFields) .add("staticFields", staticFields) .add("attachmentList", attachmentList) .add("imageList", imageList) .toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Webpage webpage = (Webpage) o; return new EqualsBuilder() .append(getContent(), webpage.getContent()) .append(getTitle(), webpage.getTitle()) .append(getUrl(), webpage.getUrl()) .append(getDomain(), webpage.getDomain()) .append(getSpiderUUID(), webpage.getSpiderUUID()) .append(getSpiderInfoId(), webpage.getSpiderInfoId()) .append(getCategory(), webpage.getCategory()) .append(getRawHTML(), webpage.getRawHTML()) .append(getKeywords(), webpage.getKeywords()) .append(getSummary(), webpage.getSummary()) .append(getGathertime(), webpage.getGathertime()) .append(getId(), webpage.getId()) .append(getPublishTime(), webpage.getPublishTime()) .append(getNamedEntity(), webpage.getNamedEntity()) .append(getDynamicFields(), webpage.getDynamicFields()) .append(getStaticFields(), webpage.getStaticFields()) .append(getAttachmentList(), webpage.getAttachmentList()) .append(getImageList(), webpage.getImageList()) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37) .append(getContent()) .append(getTitle()) .append(getUrl()) .append(getDomain()) .append(getSpiderUUID()) .append(getSpiderInfoId()) .append(getCategory()) .append(getRawHTML()) .append(getKeywords()) .append(getSummary()) .append(getGathertime()) .append(getId()) .append(getPublishTime()) .append(getNamedEntity()) .append(getDynamicFields()) .append(getStaticFields()) .append(getAttachmentList()) .append(getImageList()) .toHashCode(); } }
/* * WARNING: This file was automatically generated by Beautiful Capi! * Do not edit this file! Please edit the source API description. */ #ifndef <API key> #define <API key> #include "PointSet/PointsDecl.h" #include "PointSet/Position.h" #ifdef __cplusplus inline PointSet::PointsPtr::PointsPtr() { SetObject(PointSet::PointsPtr(PointSet::PointsPtr::<API key>, <API key>(), false).Detach()); } inline size_t PointSet::PointsPtr::Size() const { return <API key>(GetRawPointer()); } inline void PointSet::PointsPtr::Reserve(size_t capacity) { <API key>(GetRawPointer(), capacity); } inline void PointSet::PointsPtr::Resize(size_t size, const PointSet::Position& default_value) { <API key>(GetRawPointer(), size, default_value.GetRawPointer()); } inline PointSet::Position PointSet::PointsPtr::GetElement(size_t index) const { return PointSet::Position(PointSet::Position::<API key>, <API key>(GetRawPointer(), index), false); } inline void PointSet::PointsPtr::SetElement(size_t index, const PointSet::Position& value) { <API key>(GetRawPointer(), index, value.GetRawPointer()); } inline void PointSet::PointsPtr::PushBack(const PointSet::Position& value) { <API key>(GetRawPointer(), value.GetRawPointer()); } inline void PointSet::PointsPtr::Clear() { <API key>(GetRawPointer()); } inline PointSet::PointsPtr::PointsPtr(const PointsPtr& other) { SetObject(other.GetRawPointer()); if (other.GetRawPointer()) { <API key>(other.GetRawPointer()); } } #ifdef <API key> inline PointSet::PointsPtr::PointsPtr(PointsPtr&& other) { mObject = other.mObject; other.mObject = 0; } #endif /* <API key> */ inline PointSet::PointsPtr::PointsPtr(PointSet::PointsPtr::<API key>, void *object_pointer, bool add_ref_object) { SetObject(object_pointer); if (add_ref_object && object_pointer) { <API key>(object_pointer); } } inline PointSet::PointsPtr::~PointsPtr() { if (GetRawPointer()) { <API key>(GetRawPointer()); SetObject(0); } } inline PointSet::PointsPtr& PointSet::PointsPtr::operator=(const PointSet::PointsPtr& other) { if (GetRawPointer() != other.GetRawPointer()) { if (GetRawPointer()) { <API key>(GetRawPointer()); SetObject(0); } SetObject(other.GetRawPointer()); if (other.GetRawPointer()) { <API key>(other.GetRawPointer()); } } return *this; } #ifdef <API key> inline PointSet::PointsPtr& PointSet::PointsPtr::operator=(PointSet::PointsPtr&& other) { if (GetRawPointer() != other.GetRawPointer()) { if (GetRawPointer()) { <API key>(GetRawPointer()); SetObject(0); } mObject = other.mObject; other.mObject = 0; } return *this; } #endif /* <API key> */ inline PointSet::PointsPtr PointSet::PointsPtr::Null() { return PointSet::PointsPtr(PointSet::PointsPtr::<API key>, static_cast<void*>(0), false); } inline bool PointSet::PointsPtr::IsNull() const { return !GetRawPointer(); } inline bool PointSet::PointsPtr::IsNotNull() const { return GetRawPointer() != 0; } inline bool PointSet::PointsPtr::operator!() const { return !GetRawPointer(); } inline void* PointSet::PointsPtr::Detach() { void* result = GetRawPointer(); SetObject(0); return result; } inline void* PointSet::PointsPtr::GetRawPointer() const { return PointSet::PointsPtr::mObject ? mObject: 0; } inline PointSet::PointsPtr* PointSet::PointsPtr::operator->() { return this; } inline const PointSet::PointsPtr* PointSet::PointsPtr::operator->() const { return this; } inline void PointSet::PointsPtr::SetObject(void* object_pointer) { mObject = object_pointer; } #endif /* __cplusplus */ #endif /* <API key> */
package fr.hnit.babyname; import android.app.AlertDialog; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { public static final String UPDATE_EXTRA = "update"; ListView namesListView; BabyNameAdapter adapter; public static BabyNameDatabase database = new BabyNameDatabase(); public static ArrayList<BabyNameProject> projects = new ArrayList<>(); Intent editIntent; Intent findIntent; Intent settingsIntent; Intent aboutIntent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (database.size() == 0) database.initialize(); namesListView = (ListView) findViewById(R.id.listView); <API key>(namesListView); namesListView.<API key>(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { BabyNameProject project = projects.get(i); if (project != null) { doFindName(project); } } }); adapter = new BabyNameAdapter(this, projects); namesListView.setAdapter(adapter); if (projects.size() == 0) { initializeProjects(); } editIntent = new Intent(MainActivity.this, EditActivity.class); findIntent = new Intent(MainActivity.this, FindActivity.class); settingsIntent = new Intent(MainActivity.this, SettingsActivity.class); aboutIntent = new Intent(MainActivity.this, AboutActivity.class); } @Override public void onResume() { super.onResume(); // Always call the superclass method first adapter.<API key>(); for (BabyNameProject project : projects) { if (project.needSaving) { //Toast.makeText(this, "Saving changes of "+project+"... "+project, Toast.LENGTH_SHORT).show(); if (!BabyNameProject.storeProject(project, this)) { Toast.makeText(this, "Error: could not save changes to babyname project: "+project, Toast.LENGTH_LONG).show(); } } } } private void initializeProjects() { //AppLogger.info("Initializing projects..."); for (String filename : this.fileList()) { if (filename.endsWith(".baby")) { //AppLogger.info("Restoring... "+filename); try { BabyNameProject project = BabyNameProject.readProject(filename, this); if (project != null) projects.add(project); else Toast.makeText(MainActivity.this, "Error: could not read baby name project from "+filename, Toast.LENGTH_LONG).show(); } catch (Exception e) { e.printStackTrace(); } } } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_list, menu); } @Override public boolean <API key>(MenuItem item) { AdapterView.<API key> info = (AdapterView.<API key>) item.getMenuInfo(); if (adapter.getCount() <= info.position) return false; BabyNameProject project = adapter.getItem(info.position); if (project == null) return false; switch (item.getItemId()) { case R.id.action_reset_baby: doResetBaby(project); return true; case R.id.action_top_baby: doShowTop10(project); return true; case R.id.action_delete_baby: doDeleteBaby(project); return true; default: return super.<API key>(item); } } public void doResetBaby(final BabyNameProject project) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.<API key>); builder.setMessage(R.string.<API key>); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { project.reset(); adapter.<API key>(); if (!BabyNameProject.storeProject(project, MainActivity.this)) { Toast.makeText(MainActivity.this, "Error: could not save reset changes to babyname project: "+project, Toast.LENGTH_LONG).show(); } dialog.dismiss(); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // I do not need any action here you might dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } public void doDeleteBaby(final BabyNameProject project) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.<API key>); builder.setMessage(R.string.<API key>); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { projects.remove(project); MainActivity.this.deleteFile(project.getID()+".baby"); adapter.<API key>(); dialog.dismiss(); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } public String projectToString(BabyNameProject p) { String l1 = ""; if (p.genders.contains(NameData.F) && p.genders.contains(NameData.M)) { l1 += getString(R.string.boy_or_girl_name); } else if (p.genders.contains(NameData.M)) { l1 += getString(R.string.boy_name); } else { l1 +=getString( R.string.girl_name); } if (p.origins.size() == 1) { l1 += "\n\t "+String.format(getString(R.string.origin_is), p.origins.toArray()[0]); } else if (p.origins.size() > 1) { l1 += "\n\t "+String.format(getString(R.string.origin_are), p.origins); } else { l1 += "\n\t "+getString(R.string.no_origin); } if (p.pattern != null) { if (".*".equals(p.pattern.toString())) { l1 += "\n\t "+getString(R.string.no_pattern); } else { l1 += "\n\t "+String.format(getString(R.string.matches_with), p.pattern); } } if (p.nexts.size() == 1) { l1 += "\n\t"+getString(R.string.one_remaining_name); } else if (p.nexts.size() == 0) { int n = p.scores.size(); if (n > 11) n = n - 10; l1 += "\n\t"+String.format(getString(R.string.no_remaining_loop), p.loop, n); } else { l1 += "\n\t"+String.format(getString(R.string.remaining_names), p.nexts.size()); } if (p.scores.size() > 0 && p.getBest() != null) { l1 += "\n\n\t"+String.format(getString(R.string.bact_match_is), p.getBest()); } return l1; } public void doShowTop10(final BabyNameProject project) { List<Integer> names = project.getTop10(); final StringBuffer buffer = new StringBuffer(); int n = 0; for (Integer name : names) { buffer.append("\n"+MainActivity.database.get(name)+": "+project.scores.get(name)); } if (names.size() == 0) buffer.append(getString(R.string.no_name_rated)); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.top_title); builder.setMessage(buffer.toString()); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); if (names.size() > 0) builder.setNegativeButton(R.string.copy, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("baby top10", buffer.toString()); clipboard.setPrimaryClip(clip); Toast.makeText(MainActivity.this, R.string.text_copied, Toast.LENGTH_LONG).show(); } }); AlertDialog alert = builder.create(); alert.show(); //Toast.makeText(this, buffer.toString(), Toast.LENGTH_LONG).show(); } public void doFindName(BabyNameProject project) { //AppLogger.info("Open FindActivity with "+project+" index="+projects.indexOf(project)); findIntent.putExtra(FindActivity.PROJECT_EXTRA, projects.indexOf(project)); this.<API key>(findIntent, 0); } private void openEditActivity(BabyNameProject project) { //AppLogger.info("Open EditActivity with "+project+" index="+projects.indexOf(project)); editIntent.putExtra(EditActivity.PROJECT_EXTRA, projects.indexOf(project)); this.<API key>(editIntent, 0); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean <API key>(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: this.<API key>(settingsIntent, 0); return true; case R.id.action_about: this.<API key>(aboutIntent, 0); return true; case R.id.action_new_baby: doNewBaby(); return true; default: return super.<API key>(item); } } public void doNewBaby() { Toast.makeText(this, R.string.new_baby, Toast.LENGTH_LONG).show(); BabyNameProject project = new BabyNameProject(); projects.add(project); openEditActivity(project); } }
import { useState } from "react"; import { PropTypes } from "prop-types"; import { SaveOutlined, WarningOutlined } from "@ant-design/icons"; import { Button, Col, Form, Input, InputNumber, Row, Select, Switch, Typography, Space, } from "@nextgisweb/gui/antd"; import i18n from "@nextgisweb/pyramid/i18n!"; import { <API key>, DegreeFormatOptions, UnitsAreaOptions, UnitsLengthOptions, } from "./select-options"; const { Title } = Typography; const INPUT_DEFAULT_WIDTH = { width: "100%" }; export const SettingsForm = ({ onFinish, initialValues, srsOptions, status, }) => { const [geocoder, setGeocoder] = useState( initialValues.address_geocoder || "nominatim" ); const onValuesChange = (changedValues, allValues) => { setGeocoder(allValues.address_geocoder); }; return ( <Form name="webmap_settings" className="<API key>" initialValues={initialValues} onFinish={onFinish} onValuesChange={onValuesChange} layout="vertical" > <Title level={4}>{i18n.gettext("Identify popup")}</Title> <Row gutter={[16, 16]}> <Col span={8}> <Form.Item name="popup_width" label={i18n.gettext("Width, px")} rules={[ { required: true, }, ]} > <InputNumber min="100" style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={8}> <Form.Item name="popup_height" label={i18n.gettext("Height, px")} rules={[ { required: true, }, ]} > <InputNumber min="100" style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={8}> <Form.Item name="identify_radius" label={i18n.gettext("Radius, px")} rules={[ { required: true, }, ]} > <InputNumber min="1" style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> </Row> <Row gutter={[16, 16]}> <Col span={24}> <Form.Item> <Space direction="horizontal"> <Form.Item noStyle name="identify_attributes" valuePropName="checked" > <Switch /> </Form.Item> {i18n.gettext("Show feature attributes")} </Space> </Form.Item> </Col> </Row> <Title level={4}>{i18n.gettext("Measurement")}</Title> <Row gutter={[16, 16]}> <Col span={8}> <Form.Item name="units_length" label={i18n.gettext("Length units")} > <Select options={UnitsLengthOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={8}> <Form.Item name="units_area" label={i18n.gettext("Area units")} > <Select options={UnitsAreaOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={8}> <Form.Item name="degree_format" label={i18n.gettext("Degree format")} > <Select options={DegreeFormatOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> </Row> <Row gutter={[16, 16]}> <Col span={24}> <Form.Item name="measurement_srid" label={i18n.gettext("Measurement SRID")} > <Select options={srsOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> </Row> <Title level={4}>{i18n.gettext("Address search")}</Title> <Row gutter={[16, 16]}> <Col span={8}> <Form.Item> <Space direction="horizontal"> <Form.Item noStyle name="<API key>" valuePropName="checked" > <Switch /> </Form.Item> {i18n.gettext("Enable")} </Space> </Form.Item> </Col> <Col span={16}> <Form.Item> <Space direction="horizontal"> <Form.Item noStyle name="<API key>" valuePropName="checked" > <Switch /> </Form.Item> {i18n.gettext("Limit by web map initial extent")} </Space> </Form.Item> </Col> </Row> <Row gutter={[16, 16]}> <Col span={8}> <Form.Item name="address_geocoder" label={i18n.gettext("Provider")} > <Select options={<API key>} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={16}> {geocoder == "nominatim" ? ( <Form.Item name="<API key>" label={i18n.gettext( "Limit search results to countries" )} rules={[ { pattern: new RegExp( /^(?:(?:[A-Za-z]+)(?:-[A-Za-z]+)?(?:,|$))+(?<!,)$/ ), message: ( <div> {i18n.gettext( "Invalid countries. For example ru or gb,de" )} </div> ), }, ]} > <Input style={INPUT_DEFAULT_WIDTH} /> </Form.Item> ) : ( <Form.Item name="<API key>" label={i18n.gettext("Yandex.Maps API Geocoder Key")} > <Input style={INPUT_DEFAULT_WIDTH} /> </Form.Item> )} </Col> </Row> <Row className="row-submit"> <Col> <Button htmlType="submit" type={"primary"} danger={status === "saved-error"} icon={ status === "saved-error" ? ( <WarningOutlined /> ) : ( <SaveOutlined /> ) } loading={status === "saving"} > {i18n.gettext("Save")} </Button> </Col> </Row> </Form> ); }; SettingsForm.propTypes = { initialValues: PropTypes.object, onFinish: PropTypes.func, srsOptions: PropTypes.array, status: PropTypes.string, };
#!/usr/bin/env python # File written by pyctools-editor. Do not edit. import argparse import logging from pyctools.core.compound import Compound import pyctools.components.arithmetic import pyctools.components.qt.qtdisplay import pyctools.components.zone.zoneplategenerator class Network(object): components = \ { 'clipper': { 'class': 'pyctools.components.arithmetic.Arithmetic', 'config': "{'func': '16+((data > 180)*219)'}", 'pos': (200.0, 200.0)}, 'clipper2': { 'class': 'pyctools.components.arithmetic.Arithmetic', 'config': "{'func': '16+((data > 230)*219)'}", 'pos': (200.0, 330.0)}, 'qd': { 'class': 'pyctools.components.qt.qtdisplay.QtDisplay', 'config': "{'framerate': 60}", 'pos': (460.0, 200.0)}, 'stacker': { 'class': 'pyctools.components.arithmetic.Arithmetic2', 'config': "{'func': 'numpy.vstack((data1,data2))'}", 'pos': (330.0, 200.0)}, 'zpg': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', 'config': "{'kx': 0.04, 'kt': -0.34, 'xlen': 600, 'ylen': " "400, 'zlen': 1000, 'looping': 'repeat'}", 'pos': (70.0, 200.0)}, 'zpg2': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', 'config': "{'kx': 0.002, 'kt': -0.017, 'xlen': 600, 'ylen': " "200, 'zlen': 1000, 'looping': 'repeat'}", 'pos': (70.0, 330.0)}} linkages = \ { ('clipper', 'output'): [('stacker', 'input1')], ('clipper2', 'output'): [('stacker', 'input2')], ('stacker', 'output'): [('qd', 'input')], ('zpg', 'output'): [('clipper', 'input')], ('zpg2', 'output'): [('clipper2', 'input')]} def make(self): comps = {} for name, component in self.components.items(): comps[name] = eval(component['class'])(config=eval(component['config'])) return Compound(linkages=self.linkages, **comps) if __name__ == '__main__': from PyQt5 import QtCore, QtWidgets QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_X11InitThreads) app = QtWidgets.QApplication([]) comp = Network().make() cnf = comp.get_config() parser = argparse.ArgumentParser( formatter_class=argparse.<API key>) cnf.parser_add(parser) parser.add_argument('-v', '--verbose', action='count', default=0, help='increase verbosity of log messages') args = parser.parse_args() logging.basicConfig(level=logging.ERROR - (args.verbose * 10)) del args.verbose cnf.parser_set(args) comp.set_config(cnf) comp.start() app.exec_() comp.stop() comp.join()
# -*- coding: utf-8 -*- import itertools """ Language short codes => Wordnet Code """ AVAILABLE_LANGUAGES = dict([('sq','als'), ('ar', 'arb'), ('bg', 'bul'), ('ca', 'cat'), ('da', 'dan'), ('zh', 'cmn'), ('el','ell'), ('eu', 'eus'), ('fa', 'fas'), ('fi', 'fin'), ('fr', 'fra'), ('gl','glg'), ('he', 'heb'), ('hr', 'hrv'), ('id', 'ind'), ('it', 'ita'), ('ja','jpn'), ('nn', 'nno'), ('nb', 'nob'), ('no', 'nob'), ('pl', 'pol'), ('pt', 'por'), ('qn','qcn'), ('sl', 'slv'), ('es', 'spa'), ('sv', 'swe'), ('tt', 'tha'), ('ms', 'zsm'), ('en', 'eng')]) """ Language names => Short Code """ <API key> = dict([ ('albanian', 'sq'), ('arabic', 'ar'),('bulgarian', 'bg'), ('catalan', 'cat'), ('danish', 'da'), ('chinese', 'zh'), ('basque', 'eu'), ('persian', 'fa'), ('finnish', 'fi'), ('france', 'fr'), ('galician', 'gl'), ('hebrew', 'he'), ('croatian', 'hr'), ('indonesian', 'id'), ('italian', 'it'), ('japanese', 'ja'), ('norwegian_nynorsk', 'nn'), ('norwegian', 'no'), ('norwegian_bokmal', 'nb'), ('polish', 'pl'), ('portuguese', 'pt'), ('slovenian', 'sl'), ('spanish', 'es'), ('swedish', 'sv'), ('thai', 'sv'), ('malay', 'ms'), ('english', 'en') ]) class WordnetManager(object): def __init__(self, language="en"): """ Constructor for the wordnet manager. It takes a main language. """ self.__language = language def <API key>(self, code=None, language_name=None): """ Check if a language is available """ if code is None and language_name is None: raise Exception("Error evaluating the correct language") if code is not None and code.lower() in AVAILABLE_LANGUAGES: return True if language_name is not None and language_name.lower() in <API key>: return True return False def __nameToWordnetCode(self, name): """ It returns the wordnet code for a given language name """ if not self.<API key>(language_name=name): raise Exception("Wordnet code not found for the language name %s " % name) name = name.lower() languageShortCode = <API key>[name] wordnetCode = self.<API key>(code=languageShortCode) return wordnetCode def <API key>(self, shortCode): """ It returns the wordnet code from a given language short code """ if not self.<API key>(code=shortCode): raise Exception("Wordnet code not found for the language short code %s " % shortCode) code = shortCode.lower() wordnetCode = AVAILABLE_LANGUAGES[code] return wordnetCode def __getSynsets(self, word, wordNetCode): """ It returns the synsets given both word and language code """ from nltk.corpus import wordnet as wn synsets = wn.synsets(word, lang=wordNetCode) return synsets def getLemmas(self, word, languageCode="en"): """ Get the lemmas for a given word :word: The word :languageCode: The language for a given lemma """ wnCode = self.<API key>(shortCode=languageCode) synsets = self.__getSynsets(word, wnCode) #wn.synsets(word, lang=wnCode) lemmas = dict([('en', [])]) for synset in synsets: enLemmas = synset.lemma_names() lemmas['en'].extend(enLemmas) if languageCode != "en" and self.<API key>(code=languageCode): langLemmas = list(sorted(set(synset.lemma_names(lang=wnCode)))) lemmas[languageCode] = langLemmas lemmas['en'] = list(sorted(set(lemmas.get('en', [])))) return lemmas def getSynonyms(self, words=[], language_code="en"): """ Get the synonyms from a list of words. :words: A list of words :language_code: the language for the synonyms. """ if words is None or not isinstance(words, list) or list(words) <= 0: return [] if not self.<API key>(code=language_code): return [] wnCode = self.<API key>(language_code) result = {} for word in words: result[word] = dict([('lemmas', self.getLemmas(word,languageCode=language_code))]) return result def getHyponyms(self, words, language_code="en"): """ Get specific synsets from a given synset """ wnCode = self.<API key>(language_code) result = {} for word in words: synonyms = self.__getSynsets(word, wnCode) hyponyms = [hyp for synset in synonyms for hyp in synset.hyponyms()] engLemmas = [hyp.lemma_names() for hyp in hyponyms] lemmas = dict([('en', list(sorted(set(itertools.chain.from_iterable(engLemmas)), key=lambda s: s.lower())))]) if language_code != "en": languageLemmas = [hyp.lemma_names(lang=wnCode) for hyp in hyponyms] languageLemmas = list(sorted(set(itertools.chain.from_iterable(languageLemmas)), key=lambda s: s.lower())) lemmas[language_code] = languageLemmas result[word] = dict([ ('lemmas', lemmas), ('language', language_code)]) return result def getHypernyms(self, words, language_code="en"): """ Get general synsets from a given synset """ wnCode = self.<API key>(language_code) result = {} for word in words: synonyms = self.__getSynsets(word, wnCode) hypernyms = [hyp for synset in synonyms for hyp in synset.hypernyms()] engLemmas = [hyp.lemma_names() for hyp in hypernyms] lemmas = dict([('en', list(sorted(set(itertools.chain.from_iterable(engLemmas)), key=lambda s: s.lower())))]) if language_code != "en": languageLemmas = [hyp.lemma_names(lang=wnCode) for hyp in hypernyms] languageLemmas = list(sorted(set(itertools.chain.from_iterable(languageLemmas)), key=lambda s: s.lower())) lemmas[language_code] = languageLemmas result[word] = dict([ ('lemmas', lemmas), ('language', language_code)]) return result
package com.weatherapp.model.entities; import java.io.Serializable; import com.fasterxml.jackson.annotation.<API key>; @<API key>(ignoreUnknown = true) public class Location implements Serializable { private static final long serialVersionUID = 1L; private String name; public Location(String name) { this.name = name; } public Location() {} public String getName() { return name; } public void setName(String name) { this.name = name; } }
# Courses-Pick-Helper What this program will do is to constantly scan your shopping cart on your student centre account and help you enroll very fast !!! Basically help you with enrolling courses in your shopping cart of your student centre account when it's "OPEN". Note that this will succeed iff there is no conflict of this course with other courses you've enrolled in.
package units.interfaces; public abstract interface Value<T> extends MyComparable<T> { // OPERATIONS default boolean invariant() { return true; } default void checkInvariant() { if(!invariant()) { System.exit(-1); } } public abstract T newInstance(double value); public abstract T abs(); public abstract T min(T value); public abstract T max(T value); public abstract T add(T value); public abstract T sub(T value); public abstract T mul(double value); public abstract T div(double value); public abstract double div(T value); }
# $HeadURL$ # # imports import sys import re import time # # from DIRAC from DIRAC import gLogger, S_OK, S_ERROR from DIRAC.Core.Utilities.File import checkGuid from DIRAC.Core.Utilities.Adler import compareAdler, intAdlerToHex, hexAdlerToInt from DIRAC.Core.Utilities.SiteSEMapping import getSitesForSE from DIRAC.Core.Utilities.Time import dateTime from DIRAC.Resources.Storage.StorageElement import StorageElement from DIRAC.Resources.Catalog.FileCatalog import FileCatalog from DIRAC.Core.Utilities.ReturnValues import returnSingleResult from DIRAC.AccountingSystem.Client.Types.DataOperation import DataOperation from DIRAC.ConfigurationSystem.Client.Helpers.Resources import Resources from DIRAC.Core.Security.ProxyInfo import getProxyInfo from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations from DIRAC.<API key>.Client.FTSJob import FTSJob from DIRAC.<API key>.Client.FTSFile import FTSFile # # RCSID __RCSID__ = "$Id$" class FTSRequest( object ): """ .. class:: FTSRequest Helper class for FTS job submission and monitoring. """ # # default checksum type __defaultCksmType = "ADLER32" # # flag to disablr/enable checksum test, default: disabled __cksmTest = False def __init__( self ): """c'tor :param self: self reference """ self.log = gLogger.getSubLogger( self.__class__.__name__, True ) # # final states tuple self.finalStates = ( 'Canceled', 'Failed', 'Hold', 'Finished', 'FinishedDirty' ) # # failed states tuple self.failedStates = ( 'Canceled', 'Failed', 'Hold', 'FinishedDirty' ) # # successful states tuple self.successfulStates = ( 'Finished', 'Done' ) # # all file states tuple self.fileStates = ( 'Done', 'Active', 'Pending', 'Ready', 'Canceled', 'Failed', 'Finishing', 'Finished', 'Submitted', 'Hold', 'Waiting' ) self.statusSummary = {} # # request status self.requestStatus = 'Unknown' # # dict for FTS job files self.fileDict = {} # # dict for replicas information self.catalogReplicas = {} # # dict for metadata information self.catalogMetadata = {} # # dict for files that failed to register self.failedRegistrations = {} # # placehoder for FileCatalog reference self.oCatalog = None # # submit timestamp self.submitTime = '' # # placeholder FTS job GUID self.ftsGUID = '' # # placeholder for FTS server URL self.ftsServer = '' # # flag marking FTS job completness self.isTerminal = False # # completness percentage self.percentageComplete = 0.0 # # source SE name self.sourceSE = '' # # flag marking source SE validity self.sourceValid = False # # source space token self.sourceToken = '' # # target SE name self.targetSE = '' # # flag marking target SE validity self.targetValid = False # # target space token self.targetToken = '' # # placeholder for target StorageElement self.oTargetSE = None # # placeholder for source StorageElement self.oSourceSE = None # # checksum type, set it to default self.__cksmType = self.__defaultCksmType # # disable checksum test by default self.__cksmTest = False # # statuses that prevent submitting to FTS self.noSubmitStatus = ( 'Failed', 'Done', 'Staging' ) # # were sources resolved? self.sourceResolved = False # # Number of file transfers actually submitted self.submittedFiles = 0 self.transferTime = 0 self.submitCommand = Operations().getValue( 'DataManagement/FTSPlacement/FTS2/SubmitCommand', '<API key>' ) self.monitorCommand = Operations().getValue( 'DataManagement/FTSPlacement/FTS2/MonitorCommand', '<API key>' ) self.ftsJob = None self.ftsFiles = [] # Methods for setting/getting/checking the SEs def setSourceSE( self, se ): """ set SE for source :param self: self reference :param str se: source SE name """ if se == self.targetSE: return S_ERROR( "SourceSE is TargetSE" ) self.sourceSE = se self.oSourceSE = StorageElement( self.sourceSE ) return self.__checkSourceSE() def __checkSourceSE( self ): """ check source SE availability :param self: self reference """ if not self.sourceSE: return S_ERROR( "SourceSE not set" ) res = self.oSourceSE.isValid( 'Read' ) if not res['OK']: return S_ERROR( "SourceSE not available for reading" ) res = self.__getSESpaceToken( self.oSourceSE ) if not res['OK']: self.log.error( "FTSRequest failed to get SRM Space Token for SourceSE", res['Message'] ) return S_ERROR( "SourceSE does not support FTS transfers" ) if self.__cksmTest: res = self.oSourceSE.getChecksumType() if not res["OK"]: self.log.error( "Unable to get checksum type for SourceSE", "%s: %s" % ( self.sourceSE, res["Message"] ) ) cksmType = res["Value"] if cksmType in ( "NONE", "NULL" ): self.log.warn( "Checksum type set to %s at SourceSE %s, disabling checksum test" % ( cksmType, self.sourceSE ) ) self.__cksmTest = False elif cksmType != self.__cksmType: self.log.warn( "Checksum type mismatch, disabling checksum test" ) self.__cksmTest = False self.sourceToken = res['Value'] self.sourceValid = True return S_OK() def setTargetSE( self, se ): """ set target SE :param self: self reference :param str se: target SE name """ if se == self.sourceSE: return S_ERROR( "TargetSE is SourceSE" ) self.targetSE = se self.oTargetSE = StorageElement( self.targetSE ) return self.__checkTargetSE() def setTargetToken( self, token ): """ target space token setter :param self: self reference :param str token: target space token """ self.targetToken = token return S_OK() def __checkTargetSE( self ): """ check target SE availability :param self: self reference """ if not self.targetSE: return S_ERROR( "TargetSE not set" ) res = self.oTargetSE.isValid( 'Write' ) if not res['OK']: return S_ERROR( "TargetSE not available for writing" ) res = self.__getSESpaceToken( self.oTargetSE ) if not res['OK']: self.log.error( "FTSRequest failed to get SRM Space Token for TargetSE", res['Message'] ) return S_ERROR( "TargetSE does not support FTS transfers" ) # # check checksum types if self.__cksmTest: res = self.oTargetSE.getChecksumType() if not res["OK"]: self.log.error( "Unable to get checksum type for TargetSE", "%s: %s" % ( self.targetSE, res["Message"] ) ) cksmType = res["Value"] if cksmType in ( "NONE", "NULL" ): self.log.warn( "Checksum type set to %s at TargetSE %s, disabling checksum test" % ( cksmType, self.targetSE ) ) self.__cksmTest = False elif cksmType != self.__cksmType: self.log.warn( "Checksum type mismatch, disabling checksum test" ) self.__cksmTest = False self.targetToken = res['Value'] self.targetValid = True return S_OK() @staticmethod def __getSESpaceToken( oSE ): """ get space token from StorageElement instance :param self: self reference :param StorageElement oSE: StorageElement instance """ res = oSE.<API key>( "SRM2" ) if not res['OK']: return res return S_OK( res['Value'].get( 'SpaceToken' ) ) # Methods for setting/getting FTS request parameters def setFTSGUID( self, guid ): """ FTS job GUID setter :param self: self reference :param str guid: string containg GUID """ if not checkGuid( guid ): return S_ERROR( "Incorrect GUID format" ) self.ftsGUID = guid return S_OK() def setFTSServer( self, server ): """ FTS server setter :param self: self reference :param str server: FTS server URL """ self.ftsServer = server return S_OK() def isRequestTerminal( self ): """ check if FTS job has terminated :param self: self reference """ if self.requestStatus in self.finalStates: self.isTerminal = True return S_OK( self.isTerminal ) def setCksmTest( self, cksmTest = False ): """ set cksm test :param self: self reference :param bool cksmTest: flag to enable/disable checksum test """ self.__cksmTest = bool( cksmTest ) return S_OK( self.__cksmTest ) # Methods for setting/getting/checking files and their metadata def setLFN( self, lfn ): """ add LFN :lfn: to :fileDict: :param self: self reference :param str lfn: LFN to add to """ self.fileDict.setdefault( lfn, {'Status':'Waiting'} ) return S_OK() def setSourceSURL( self, lfn, surl ): """ source SURL setter :param self: self reference :param str lfn: LFN :param str surl: source SURL """ target = self.fileDict[lfn].get( 'Target' ) if target == surl: return S_ERROR( "Source and target the same" ) return self.__setFileParameter( lfn, 'Source', surl ) def getSourceSURL( self, lfn ): """ get source SURL for LFN :lfn: :param self: self reference :param str lfn: LFN """ return self.__getFileParameter( lfn, 'Source' ) def setTargetSURL( self, lfn, surl ): """ set target SURL for LFN :lfn: :param self: self reference :param str lfn: LFN :param str surl: target SURL """ source = self.fileDict[lfn].get( 'Source' ) if source == surl: return S_ERROR( "Source and target the same" ) return self.__setFileParameter( lfn, 'Target', surl ) def getFailReason( self, lfn ): """ get fail reason for file :lfn: :param self: self reference :param str lfn: LFN """ return self.__getFileParameter( lfn, 'Reason' ) def getRetries( self, lfn ): """ get number of attepmts made to transfer file :lfn: :param self: self reference :param str lfn: LFN """ return self.__getFileParameter( lfn, 'Retries' ) def getTransferTime( self, lfn ): """ get duration of transfer for file :lfn: :param self: self reference :param str lfn: LFN """ return self.__getFileParameter( lfn, 'Duration' ) def getFailed( self ): """ get list of wrongly transferred LFNs :param self: self reference """ return S_OK( [ lfn for lfn in self.fileDict if self.fileDict[lfn].get( 'Status', '' ) in self.failedStates ] ) def getStaging( self ): """ get files set for prestaging """ return S_OK( [lfn for lfn in self.fileDict if self.fileDict[lfn].get( 'Status', '' ) == 'Staging'] ) def getDone( self ): """ get list of succesfully transferred LFNs :param self: self reference """ return S_OK( [ lfn for lfn in self.fileDict if self.fileDict[lfn].get( 'Status', '' ) in self.successfulStates ] ) def __setFileParameter( self, lfn, paramName, paramValue ): """ set :paramName: to :paramValue: for :lfn: file :param self: self reference :param str lfn: LFN :param str paramName: parameter name :param mixed paramValue: a new parameter value """ self.setLFN( lfn ) self.fileDict[lfn][paramName] = paramValue return S_OK() def __getFileParameter( self, lfn, paramName ): """ get value of :paramName: for file :lfn: :param self: self reference :param str lfn: LFN :param str paramName: parameter name """ if lfn not in self.fileDict: return S_ERROR( "Supplied file not set" ) if paramName not in self.fileDict[lfn]: return S_ERROR( "%s not set for file" % paramName ) return S_OK( self.fileDict[lfn][paramName] ) # Methods for submission def submit( self, monitor = False, printOutput = True ): """ submit FTS job :param self: self reference :param bool monitor: flag to monitor progress of FTS job :param bool printOutput: flag to print output of execution to stdout """ res = self.<API key>() if not res['OK']: return res res = self.__submitFTSTransfer() if not res['OK']: return res resDict = { 'ftsGUID' : self.ftsGUID, 'ftsServer' : self.ftsServer, 'submittedFiles' : self.submittedFiles } if monitor or printOutput: gLogger.always( "Submitted %s@%s" % ( self.ftsGUID, self.ftsServer ) ) if monitor: self.monitor( untilTerminal = True, printOutput = printOutput, full = False ) return S_OK( resDict ) def <API key>( self ): """ check validity of job before submission :param self: self reference """ if not self.fileDict: return S_ERROR( "No files set" ) if not self.sourceValid: return S_ERROR( "SourceSE not valid" ) if not self.targetValid: return S_ERROR( "TargetSE not valid" ) if not self.ftsServer: res = self.__resolveFTSServer() if not res['OK']: return S_ERROR( "FTSServer not valid" ) self.resolveSource() self.resolveTarget() res = self.__filesToSubmit() if not res['OK']: return S_ERROR( "No files to submit" ) return S_OK() def __getCatalogObject( self ): """ CatalogInterface instance facade :param self: self reference """ try: if not self.oCatalog: self.oCatalog = FileCatalog() return S_OK() except: return S_ERROR() def <API key>( self, lfns = None, overwrite = False ): """ update replica cache for list of :lfns: :param self: self reference :param mixed lfns: list of LFNs :param bool overwrite: flag to trigger cache clearing and updating """ if not lfns: lfns = self.fileDict.keys() toUpdate = [ lfn for lfn in lfns if ( lfn not in self.catalogReplicas ) or overwrite ] if not toUpdate: return S_OK() res = self.__getCatalogObject() if not res['OK']: return res res = self.oCatalog.getReplicas( toUpdate ) if not res['OK']: return S_ERROR( "Failed to update replica cache: %s" % res['Message'] ) for lfn, error in res['Value']['Failed'].items(): self.__setFileParameter( lfn, 'Reason', error ) self.__setFileParameter( lfn, 'Status', 'Failed' ) for lfn, replicas in res['Value']['Successful'].items(): self.catalogReplicas[lfn] = replicas return S_OK() def <API key>( self, lfns = None ): """ update metadata cache for list of LFNs :param self: self reference :param list lnfs: list of LFNs """ if not lfns: lfns = self.fileDict.keys() toUpdate = [ lfn for lfn in lfns if lfn not in self.catalogMetadata ] if not toUpdate: return S_OK() res = self.__getCatalogObject() if not res['OK']: return res res = self.oCatalog.getFileMetadata( toUpdate ) if not res['OK']: return S_ERROR( "Failed to get source catalog metadata: %s" % res['Message'] ) for lfn, error in res['Value']['Failed'].items(): self.__setFileParameter( lfn, 'Reason', error ) self.__setFileParameter( lfn, 'Status', 'Failed' ) for lfn, metadata in res['Value']['Successful'].items(): self.catalogMetadata[lfn] = metadata return S_OK() def resolveSource( self ): """ resolve source SE eligible for submission :param self: self reference """ # Avoid resolving sources twice if self.sourceResolved: return S_OK() # Only resolve files that need a transfer toResolve = [ lfn for lfn in self.fileDict if self.fileDict[lfn].get( "Status", "" ) != "Failed" ] if not toResolve: return S_OK() res = self.<API key>( toResolve ) if not res['OK']: return res res = self.<API key>( toResolve ) if not res['OK']: return res # Define the source URLs for lfn in toResolve: replicas = self.catalogReplicas.get( lfn, {} ) if self.sourceSE not in replicas: gLogger.warn( "resolveSource: skipping %s - not replicas at SourceSE %s" % ( lfn, self.sourceSE ) ) self.__setFileParameter( lfn, 'Reason', "No replica at SourceSE" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) continue res = returnSingleResult( self.oSourceSE.getURL( lfn, protocol = 'srm' ) ) if not res['OK']: gLogger.warn( "resolveSource: skipping %s - %s" % ( lfn, res["Message"] ) ) self.__setFileParameter( lfn, 'Reason', res['Message'] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) continue res = self.setSourceSURL( lfn, res['Value'] ) if not res['OK']: gLogger.warn( "resolveSource: skipping %s - %s" % ( lfn, res["Message"] ) ) self.__setFileParameter( lfn, 'Reason', res['Message'] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) continue toResolve = [] for lfn in self.fileDict: if "Source" in self.fileDict[lfn]: toResolve.append( lfn ) if not toResolve: return S_ERROR( "No eligible Source files" ) # Get metadata of the sources, to check for existance, availability and caching res = self.oSourceSE.getFileMetadata( toResolve ) if not res['OK']: return S_ERROR( "Failed to check source file metadata" ) for lfn, error in res['Value']['Failed'].items(): if re.search( 'File does not exist', error ): gLogger.warn( "resolveSource: skipping %s - source file does not exists" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source file does not exist" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) else: gLogger.warn( "resolveSource: skipping %s - failed to get source metadata" % lfn ) self.__setFileParameter( lfn, 'Reason', "Failed to get Source metadata" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) toStage = [] nbStagedFiles = 0 for lfn, metadata in res['Value']['Successful'].items(): lfnStatus = self.fileDict.get( lfn, {} ).get( 'Status' ) if metadata['Unavailable']: gLogger.warn( "resolveSource: skipping %s - source file unavailable" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source file Unavailable" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) elif metadata['Lost']: gLogger.warn( "resolveSource: skipping %s - source file lost" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source file Lost" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) elif not metadata['Cached']: if lfnStatus != 'Staging': toStage.append( lfn ) elif metadata['Size'] != self.catalogMetadata[lfn]['Size']: gLogger.warn( "resolveSource: skipping %s - source file size mismatch" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source size mismatch" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) elif self.catalogMetadata[lfn]['Checksum'] and metadata['Checksum'] and \ not compareAdler( metadata['Checksum'], self.catalogMetadata[lfn]['Checksum'] ): gLogger.warn( "resolveSource: skipping %s - source file checksum mismatch" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source checksum mismatch" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) elif lfnStatus == 'Staging': # file that was staging is now cached self.__setFileParameter( lfn, 'Status', 'Waiting' ) nbStagedFiles += 1 # Some files were being staged if nbStagedFiles: self.log.info( 'resolveSource: %d files have been staged' % nbStagedFiles ) # Launching staging of files not in cache if toStage: gLogger.warn( "resolveSource: %s source files not cached, prestaging..." % len( toStage ) ) stage = self.oSourceSE.prestageFile( toStage ) if not stage["OK"]: gLogger.error( "resolveSource: error is prestaging", stage["Message"] ) for lfn in toStage: self.__setFileParameter( lfn, 'Reason', stage["Message"] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) else: for lfn in toStage: if lfn in stage['Value']['Successful']: self.__setFileParameter( lfn, 'Status', 'Staging' ) elif lfn in stage['Value']['Failed']: self.__setFileParameter( lfn, 'Reason', stage['Value']['Failed'][lfn] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) self.sourceResolved = True return S_OK() def resolveTarget( self ): """ find target SE eligible for submission :param self: self reference """ toResolve = [ lfn for lfn in self.fileDict if self.fileDict[lfn].get( 'Status' ) not in self.noSubmitStatus ] if not toResolve: return S_OK() res = self.<API key>( toResolve ) if not res['OK']: return res for lfn in toResolve: res = returnSingleResult( self.oTargetSE.getURL( lfn, protocol = 'srm' ) ) if not res['OK']: reason = res.get( 'Message', res['Message'] ) gLogger.warn( "resolveTarget: skipping %s - %s" % ( lfn, reason ) ) self.__setFileParameter( lfn, 'Reason', reason ) self.__setFileParameter( lfn, 'Status', 'Failed' ) continue res = self.setTargetSURL( lfn, res['Value'] ) if not res['OK']: gLogger.warn( "resolveTarget: skipping %s - %s" % ( lfn, res["Message"] ) ) self.__setFileParameter( lfn, 'Reason', res['Message'] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) continue toResolve = [] for lfn in self.fileDict: if "Target" in self.fileDict[lfn]: toResolve.append( lfn ) if not toResolve: return S_ERROR( "No eligible Target files" ) res = self.oTargetSE.exists( toResolve ) if not res['OK']: return S_ERROR( "Failed to check target existence" ) for lfn, error in res['Value']['Failed'].items(): self.__setFileParameter( lfn, 'Reason', error ) self.__setFileParameter( lfn, 'Status', 'Failed' ) toRemove = [] for lfn, exists in res['Value']['Successful'].items(): if exists: res = self.getSourceSURL( lfn ) if not res['OK']: gLogger.warn( "resolveTarget: skipping %s - target exists" % lfn ) self.__setFileParameter( lfn, 'Reason', "Target exists" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) elif res['Value'] == self.fileDict[lfn]['Target']: gLogger.warn( "resolveTarget: skipping %s - source and target pfns are the same" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source and Target the same" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) else: toRemove.append( lfn ) if toRemove: self.oTargetSE.removeFile( toRemove ) return S_OK() def __filesToSubmit( self ): """ check if there is at least one file to submit :return: S_OK if at least one file is present, S_ERROR otherwise """ for lfn in self.fileDict: lfnStatus = self.fileDict[lfn].get( 'Status' ) source = self.fileDict[lfn].get( 'Source' ) target = self.fileDict[lfn].get( 'Target' ) if lfnStatus not in self.noSubmitStatus and source and target: return S_OK() return S_ERROR() def __createFTSFiles( self ): """ create LFNs file for <API key> command This file consists one line for each fiel to be transferred: sourceSURL targetSURL [CHECKSUMTYPE:CHECKSUM] :param self: self reference """ self.<API key>() for lfn in self.fileDict: lfnStatus = self.fileDict[lfn].get( 'Status' ) if lfnStatus not in self.noSubmitStatus: cksmStr = "" # # add chsmType:cksm only if cksmType is specified, else let FTS decide by itself if self.__cksmTest and self.__cksmType: checkSum = self.catalogMetadata.get( lfn, {} ).get( 'Checksum' ) if checkSum: cksmStr = " %s:%s" % ( self.__cksmType, intAdlerToHex( hexAdlerToInt( checkSum ) ) ) ftsFile = FTSFile() ftsFile.LFN = lfn ftsFile.SourceSURL = self.fileDict[lfn].get( 'Source' ) ftsFile.TargetSURL = self.fileDict[lfn].get( 'Target' ) ftsFile.SourceSE = self.sourceSE ftsFile.TargetSE = self.targetSE ftsFile.Status = self.fileDict[lfn].get( 'Status' ) ftsFile.Checksum = cksmStr ftsFile.Size = self.catalogMetadata.get( lfn, {} ).get( 'Size' ) self.ftsFiles.append( ftsFile ) self.submittedFiles += 1 return S_OK() def __createFTSJob( self, guid = None ): self.__createFTSFiles() ftsJob = FTSJob() ftsJob.RequestID = 0 ftsJob.OperationID = 0 ftsJob.SourceSE = self.sourceSE ftsJob.TargetSE = self.targetSE ftsJob.SourceToken = self.sourceToken ftsJob.TargetToken = self.targetToken ftsJob.FTSServer = self.ftsServer if guid: ftsJob.FTSGUID = guid for ftsFile in self.ftsFiles: ftsFile.Attempt += 1 ftsFile.Error = "" ftsJob.addFile( ftsFile ) self.ftsJob = ftsJob def __submitFTSTransfer( self ): """ create and execute <API key> CLI command :param self: self reference """ log = gLogger.getSubLogger( 'Submit' ) self.__createFTSJob() submit = self.ftsJob.submitFTS2( command = self.submitCommand ) if not submit["OK"]: log.error( "unable to submit FTSJob: %s" % submit["Message"] ) return submit log.info( "FTSJob '%s'@'%s' has been submitted" % ( self.ftsJob.FTSGUID, self.ftsJob.FTSServer ) ) # # update statuses for job files for ftsFile in self.ftsJob: ftsFile.FTSGUID = self.ftsJob.FTSGUID ftsFile.Status = "Submitted" ftsFile.Attempt += 1 log.info( "FTSJob '%s'@'%s' has been submitted" % ( self.ftsJob.FTSGUID, self.ftsJob.FTSServer ) ) self.ftsGUID = self.ftsJob.FTSGUID return S_OK() def __resolveFTSServer( self ): """ resolve FTS server to use, it should be the closest one from target SE :param self: self reference """ from DIRAC.ConfigurationSystem.Client.Helpers.Resources import <API key> if not self.targetSE: return S_ERROR( "Target SE not set" ) res = getSitesForSE( self.targetSE ) if not res['OK'] or not res['Value']: return S_ERROR( "Could not determine target site" ) targetSites = res['Value'] targetSite = '' for targetSite in targetSites: targetFTS = <API key>( [targetSite] ) if targetFTS['OK']: ftsTarget = targetFTS['Value'][targetSite] if ftsTarget: self.ftsServer = ftsTarget return S_OK( self.ftsServer ) else: return targetFTS return S_ERROR( 'No FTS server found for %s' % targetSite ) # Methods for monitoring def summary( self, untilTerminal = False, printOutput = False ): """ summary of FTS job :param self: self reference :param bool untilTerminal: flag to monitor FTS job to its final state :param bool printOutput: flag to print out monitoring information to the stdout """ res = self.__isSummaryValid() if not res['OK']: return res while not self.isTerminal: res = self.__parseOutput( full = True ) if not res['OK']: return res if untilTerminal: self.__print() self.isRequestTerminal() if res['Value'] or ( not untilTerminal ): break time.sleep( 1 ) if untilTerminal: print "" if printOutput and ( not untilTerminal ): return self.dumpSummary( printOutput = printOutput ) return S_OK() def monitor( self, untilTerminal = False, printOutput = False, full = True ): """ monitor FTS job :param self: self reference :param bool untilTerminal: flag to monitor FTS job to its final state :param bool printOutput: flag to print out monitoring information to the stdout """ if not self.ftsJob: self.resolveSource() self.__createFTSJob( self.ftsGUID ) res = self.__isSummaryValid() if not res['OK']: return res if untilTerminal: res = self.summary( untilTerminal = untilTerminal, printOutput = printOutput ) if not res['OK']: return res res = self.__parseOutput( full = full ) if not res['OK']: return res if untilTerminal: self.finalize() if printOutput: self.dump() return res def dumpSummary( self, printOutput = False ): """ get FTS job summary as str :param self: self reference :param bool printOutput: print summary to stdout """ outStr = '' for status in sorted( self.statusSummary ): if self.statusSummary[status]: outStr = '%s\t%-10s : %-10s\n' % ( outStr, status, str( self.statusSummary[status] ) ) outStr = outStr.rstrip( '\n' ) if printOutput: print outStr return S_OK( outStr ) def __print( self ): """ print progress bar of FTS job completeness to stdout :param self: self reference """ width = 100 bits = int( ( width * self.percentageComplete ) / 100 ) outStr = "|%s>%s| %.1f%s %s %s" % ( "="*bits, " "*( width - bits ), self.percentageComplete, "%", self.requestStatus, " "*10 ) sys.stdout.write( "%s\r" % ( outStr ) ) sys.stdout.flush() def dump( self ): """ print FTS job parameters and files to stdout :param self: self reference """ print "%-10s : %-10s" % ( "Status", self.requestStatus ) print "%-10s : %-10s" % ( "Source", self.sourceSE ) print "%-10s : %-10s" % ( "Target", self.targetSE ) print "%-10s : %-128s" % ( "Server", self.ftsServer ) print "%-10s : %-128s" % ( "GUID", self.ftsGUID ) for lfn in sorted( self.fileDict ): print "\n %-15s : %-128s" % ( 'LFN', lfn ) for key in ['Source', 'Target', 'Status', 'Reason', 'Duration']: print " %-15s : %-128s" % ( key, str( self.fileDict[lfn].get( key ) ) ) return S_OK() def __isSummaryValid( self ): """ check validity of FTS job summary report :param self: self reference """ if not self.ftsServer: return S_ERROR( "FTSServer not set" ) if not self.ftsGUID: return S_ERROR( "FTSGUID not set" ) return S_OK() def __parseOutput( self, full = False ): """ execute <API key> command and parse its output :param self: self reference :param bool full: <API key> verbosity level, when set, collect information of files as well """ monitor = self.ftsJob.monitorFTS2( command = self.monitorCommand, full = full ) if not monitor['OK']: return monitor self.percentageComplete = self.ftsJob.Completeness self.requestStatus = self.ftsJob.Status self.submitTime = self.ftsJob.SubmitTime statusSummary = monitor['Value'] if statusSummary: for state in statusSummary: self.statusSummary[state] = statusSummary[state] self.transferTime = 0 for ftsFile in self.ftsJob: lfn = ftsFile.LFN self.__setFileParameter( lfn, 'Status', ftsFile.Status ) self.__setFileParameter( lfn, 'Reason', ftsFile.Error ) self.__setFileParameter( lfn, 'Duration', ftsFile._duration ) targetURL = self.__getFileParameter( lfn, 'Target' ) if not targetURL['OK']: self.__setFileParameter( lfn, 'Target', ftsFile.TargetSURL ) self.transferTime += int( ftsFile._duration ) return S_OK() # Methods for finalization def finalize( self ): """ finalize FTS job :param self: self reference """ self.<API key>() transEndTime = dateTime() regStartTime = time.time() res = self.<API key>() transDict = res['Value'] res = self.<API key>( transDict['transLFNs'] ) regSuc, regTotal = res['Value'] regTime = time.time() - regStartTime if self.sourceSE and self.targetSE: self.__sendAccounting( regSuc, regTotal, regTime, transEndTime, transDict ) return S_OK() def <API key>( self ): """ collect information of Transfers that can be used by Accounting :param self: self reference """ transDict = { 'transTotal': len( self.fileDict ), 'transLFNs': [], 'transOK': 0, 'transSize': 0 } for lfn in self.fileDict: if self.fileDict[lfn].get( 'Status' ) in self.successfulStates: if self.fileDict[lfn].get( 'Duration', 0 ): transDict['transLFNs'].append( lfn ) transDict['transOK'] += 1 if lfn in self.catalogMetadata: transDict['transSize'] += self.catalogMetadata[lfn].get( 'Size', 0 ) return S_OK( transDict ) def <API key>( self ): """ get failed registrations dict :param self: self reference """ return S_OK( self.failedRegistrations ) def <API key>( self, transLFNs ): """ register successfully transferred files to the catalogs, fill failedRegistrations dict for files that failed to register :param self: self reference :param list transLFNs: LFNs in FTS job """ self.failedRegistrations = {} toRegister = {} for lfn in transLFNs: res = returnSingleResult( self.oTargetSE.getURL( self.fileDict[lfn].get( 'Target' ), protocol = 'srm' ) ) if not res['OK']: self.__setFileParameter( lfn, 'Reason', res['Message'] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) else: toRegister[lfn] = { 'PFN' : res['Value'], 'SE' : self.targetSE } if not toRegister: return S_OK( ( 0, 0 ) ) res = self.__getCatalogObject() if not res['OK']: for lfn in toRegister: self.failedRegistrations = toRegister self.log.error( 'Failed to get Catalog Object', res['Message'] ) return S_OK( ( 0, len( toRegister ) ) ) res = self.oCatalog.addReplica( toRegister ) if not res['OK']: self.failedRegistrations = toRegister self.log.error( 'Failed to get Catalog Object', res['Message'] ) return S_OK( ( 0, len( toRegister ) ) ) for lfn, error in res['Value']['Failed'].items(): self.failedRegistrations[lfn] = toRegister[lfn] self.log.error( 'Registration of Replica failed', '%s : %s' % ( lfn, str( error ) ) ) return S_OK( ( len( res['Value']['Successful'] ), len( toRegister ) ) ) def __sendAccounting( self, regSuc, regTotal, regTime, transEndTime, transDict ): """ send accounting record :param self: self reference :param regSuc: number of files successfully registered :param regTotal: number of files attepted to register :param regTime: time stamp at the end of registration :param transEndTime: time stamp at the end of FTS job :param dict transDict: dict holding couters for files being transerred, their sizes and successfull transfers """ oAccounting = DataOperation() oAccounting.setEndTime( transEndTime ) oAccounting.setStartTime( self.submitTime ) accountingDict = {} accountingDict['OperationType'] = '<API key>' result = getProxyInfo() if not result['OK']: userName = 'system' else: userName = result['Value'].get( 'username', 'unknown' ) accountingDict['User'] = userName accountingDict['Protocol'] = 'FTS' if 'fts3' not in self.ftsServer else 'FTS3' accountingDict['RegistrationTime'] = regTime accountingDict['RegistrationOK'] = regSuc accountingDict['RegistrationTotal'] = regTotal accountingDict['TransferOK'] = transDict['transOK'] accountingDict['TransferTotal'] = transDict['transTotal'] accountingDict['TransferSize'] = transDict['transSize'] accountingDict['FinalStatus'] = self.requestStatus accountingDict['Source'] = self.sourceSE accountingDict['Destination'] = self.targetSE accountingDict['TransferTime'] = self.transferTime oAccounting.setValuesFromDict( accountingDict ) self.log.verbose( "Attempting to commit accounting message..." ) oAccounting.commit() self.log.verbose( "...committed." ) return S_OK()
<?php namespace de\chilan\WebsiteBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class WebsiteBundle extends Bundle { }
var _ = require("lodash"); module.exports = { // ensure client accepts json json_request: function(req, res, next){ if(req.accepts("application/json")) return next(); res.stash.code = 406; _.last(req.route.stack).handle(req, res, next); }, // init response init_response: function(req, res, next){ res.stash = {}; res.response_start = new Date(); return next(); }, // respond to client handle_response: function(req, res, next){ res.setHeader("<API key>", new Date() - res.response_start); res.stash = _.defaults(res.stash, { code: 404 }); if(_.has(res.stash, "body")) res.status(res.stash.code).json(res.stash.body); else res.sendStatus(res.stash.code); } }