code
stringlengths
4
1.01M
language
stringclasses
2 values
// pythonFlu - Python wrapping for OpenFOAM C++ API // Copyright (C) 2010- Alexey Petrov // Copyright (C) 2009-2010 Pebble Bed Modular Reactor (Pty) Limited (PBMR) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // See http://sourceforge.net/projects/pythonflu // // Author : Alexey PETROV //--------------------------------------------------------------------------- #ifndef no_tmp_typemap_GeometricFields_hpp #define no_tmp_typemap_GeometricFields_hpp //--------------------------------------------------------------------------- %import "Foam/src/OpenFOAM/fields/tmp/tmp.i" %import "Foam/ext/common/ext_tmp.hxx" //--------------------------------------------------------------------------- %define NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Type, TPatchField, TMesh ) %typecheck( SWIG_TYPECHECK_POINTER ) 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" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( 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" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( 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" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( 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" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( 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" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( 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" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( 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" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( 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" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::Tensor< Foam::scalar >, Foam::fvsPatchField, Foam::surfaceMesh ); //------------------------------------------------------------------------------- #endif
Java
#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_ */
Java
//----------------------------------------------------------------------------------- // The confidential and proprietary information contained in this file may // 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 // // (C) COPYRIGHT [2016] ARM Limited or its affiliates // 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 // permitted to do so under the terms of a subsisting license agreement // 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]. */ /************************ Defines ******************************/ /*! 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 CRYS_RND_MAX_RESEED_COUNTER (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 CRYS_RND_REQUESTED_SIZE_COUNTER 0x3FFFF /*! AES output block size in words. */ #define CRYS_RND_AES_BLOCK_SIZE_IN_WORDS SASI_AES_BLOCK_SIZE_IN_WORDS /* RND seed and additional input sizes */ #define CRYS_RND_SEED_MAX_SIZE_WORDS 12 #ifndef CRYS_RND_ADDITINAL_INPUT_MAX_SIZE_WORDS #define CRYS_RND_ADDITINAL_INPUT_MAX_SIZE_WORDS CRYS_RND_SEED_MAX_SIZE_WORDS #endif /* Max size of generated random vector in bits according uint16_t type of * * input size parameter in CRYS_RND_Generate function */ #define CRYS_RND_MAX_GEN_VECTOR_SIZE_BYTES 0xFFFF /* allowed sizes of AES Key, in words */ #define CRYS_RND_AES_KEY_128_SIZE_WORDS 4 #define CRYS_RND_AES_KEY_192_SIZE_WORDS 6 #define CRYS_RND_AES_KEY_256_SIZE_WORDS 8 /* Definitions of temp buffer for RND_DMA version of CRYS_RND */ /*******************************************************************/ /* Definitions of temp buffer for DMA version of CRYS_RND */ #define CRYS_RND_WORK_BUFFER_SIZE_WORDS 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[CRYS_RND_WORK_BUFFER_SIZE_WORDS]; }CRYS_RND_WorkBuff_t; #define CRYS_RND_EntropyEstimatData_t CRYS_RND_WorkBuff_t #define crysRndEntrIntBuff crysRndWorkBuff /* RND source buffer inner (entrpopy) offset */ #define CRYS_RND_TRNG_SRC_INNER_OFFSET_WORDS 2 /* Max size for one RNG operation */ #define CRYS_RND_MAX_SIZE_OF_OUTPUT_BYTES 3*1024 /* Size of the expected output buffer used by FIPS KAT */ #define CRYS_PRNG_FIPS_KAT_OUT_DATA_SIZE 64 /************************ Enumerators ****************************/ /* 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; /************************ Structs *****************************/ /* 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[CRYS_RND_SEED_MAX_SIZE_WORDS]; /* Previous value for continuous test */ uint32_t PreviousRandValue[SASI_AES_BLOCK_SIZE_IN_WORDS]; /* AdditionalInput buffer max size = seed max size words + 4w for padding*/ uint32_t PreviousAdditionalInput[CRYS_RND_ADDITINAL_INPUT_MAX_SIZE_WORDS+3]; uint32_t AdditionalInput[CRYS_RND_ADDITINAL_INPUT_MAX_SIZE_WORDS+4]; uint32_t AddInputSizeWords; /* size of additional data set by user, words */ /* entropy source size in words */ uint32_t EntropySourceSizeWords; /* 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 ::CRYS_RND_GenerateVector function API. */ typedef uint32_t (*SaSiRndGenerateVectWorkFunc_t)( \ CRYS_RND_State_t *rndState_ptr, /*context*/ \ uint16_t outSizeBytes, /*in*/ \ 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 */ SaSiRndGenerateVectWorkFunc_t rndGenerateVectFunc; } CRYS_RND_Context_t; /*! Required for internal FIPS verification for PRNG KAT. */ typedef struct { CRYS_RND_WorkBuff_t rndWorkBuff; uint8_t rndOutputBuff[CRYS_PRNG_FIPS_KAT_OUT_DATA_SIZE]; } CRYS_PrngFipsKatCtx_t; /*****************************************************************************/ /********************** Public Functions *************************/ /*****************************************************************************/ /*! @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 ::CRYS_RND_SetGenerateVectorFunc 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 ::CRYS_RND_AddAdditionalInput 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 CRYS_RND_Instantiation( 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 CRYS_RND_UnInstantiation( 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 ::CRYS_RND_AddAdditionalInput 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 CRYS_RND_RESEED_COUNTER_OVERFLOW_ERROR, 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 CRYS_RND_GenerateVector( 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 ::CRYS_RND_Instantiation, 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 ::CRYS_RND_Instantiation is called. @return CRYS_OK on success. @return A non-zero value from crys_rnd_error.h on failure. */ CRYSError_t CRYS_RND_SetGenerateVectorFunc( 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. */ SaSiRndGenerateVectWorkFunc_t rndGenerateVectFunc /*!< [in] Pointer to the random vector generation function. The pointer should point to the ::CRYS_RND_GenerateVector 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 CRYS_RND_GenerateVectorInRange( 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 ::CRYS_RND_Instantiation/::CRYS_RND_Reseeding/::CRYS_RND_GenerateVector functions. @return CRYS_OK on success. @return A non-zero value from crys_rnd_error.h on failure. */ CIMPORT_C CRYSError_t CRYS_RND_AddAdditionalInput( 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 CRYS_RND_EnterKatMode function sets KAT mode bit into StateFlag of global CRYS_RND_WorkingState 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: ::CRYS_RND_MAX_KAT_ENTROPY_AND_NONCE_SIZE, defined. @return CRYS_OK on success. @return A non-zero value from crys_rnd_error.h on failure. */ CIMPORT_C CRYSError_t CRYS_RND_EnterKatMode( 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 CRYS_RND_DisableKatMode function disables KAT mode bit into StateFlag of global CRYS_RND_WorkingState 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 CRYS_RND_DisableKatMode( CRYS_RND_Context_t *rndContext_ptr /*!< [in/out] Pointer to the RND context buffer. */ ); #ifdef __cplusplus } #endif #endif /* #ifndef CRYS_RND_H */
Java
namespace Tsu.Voltmeters.Appa { partial class Multimeter109NControl { /// <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 } }
Java
# _attributevaluebeforechange _namespace: [SMRUCC.genomics.Data.Reactome.LocalMySQL.Tables.gk_current](./index.md)_ -- DROP TABLE IF EXISTS `_attributevaluebeforechange`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `_attributevaluebeforechange` ( `DB_ID` int(10) unsigned NOT NULL, `changedAttribute` text, PRIMARY KEY (`DB_ID`), FULLTEXT KEY `changedAttribute` (`changedAttribute`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; --
Java
package ru.trolsoft.utils.files; import ru.trolsoft.utils.StrUtils; import java.io.*; import java.util.Random; /** * Created on 07/02/17. */ 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(); } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- 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> <!-- ========= START OF TOP NAVBAR ======= --> <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="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if (window == top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Hierarchy For Package org.cripac.isee.vpe.alg.pedestrian.attr</h1> <span class="packageHierarchyLabel">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/PedestrianAttrRecogAppTest.html" title="class in org.cripac.isee.vpe.alg.pedestrian.attr"><span class="typeNameLink">PedestrianAttrRecogAppTest</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/PedestrianAttrRecogApp.html" title="class in org.cripac.isee.vpe.alg.pedestrian.attr"><span class="typeNameLink">PedestrianAttrRecogApp</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/PedestrianAttrRecogApp.RecogStream.html" title="class in org.cripac.isee.vpe.alg.pedestrian.attr"><span class="typeNameLink">PedestrianAttrRecogApp.RecogStream</span></a> </li> </ul> </li> <li type="circle">org.cripac.isee.vpe.ctrl.<a href="../../../../../../../org/cripac/isee/vpe/ctrl/SystemPropertyCenter.html" title="class in org.cripac.isee.vpe.ctrl"><span class="typeNameLink">SystemPropertyCenter</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/PedestrianAttrRecogApp.AppPropertyCenter.html" title="class in org.cripac.isee.vpe.alg.pedestrian.attr"><span class="typeNameLink">PedestrianAttrRecogApp.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/PedestrianAttrRecogApp.Algorithm.html" title="enum in org.cripac.isee.vpe.alg.pedestrian.attr"><span class="typeNameLink">PedestrianAttrRecogApp.Algorithm</span></a> </li> </ul> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <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="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if (window == top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
Java
<?php /** * @package omeka * @subpackage solr-search * @copyright 2012 Rector and Board of Visitors, University of Virginia * @license http://www.apache.org/licenses/LICENSE-2.0.html */ class SolrSearch_AdminController extends Omeka_Controller_AbstractActionController { /** * Display the "Server Configuration" form. */ public function serverAction() { $form = new SolrSearch_Form_Server(); // 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 (SolrSearch_Helpers_Index::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(); } /** * Retourne l'état actuel de l'indexation Solr en JSON */ public function getIndexStatusAction() { $this->view->status = SolrSearch_Helpers_Index::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 Zend_Form_Element_MultiCheckbox('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 SolrSearch_Form_Results(); // 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 SolrSearch_Form_Reindex(); if ($this->_request->isPost()) { try { // Clear and reindex. Zend_Registry::get('job_dispatcher')->sendLongRunning( 'SolrSearch_Job_Reindex' ); } catch (Exception $err) { } } $totalDocumentCount = $this->_helper->db->getTable('NewspaperReaderDocuments')->count(); $this->view->form = $form; $this->view->totalDocumentCount = $totalDocumentCount; } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- 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.DroneStatusChangedListener</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.DroneStatusChangedListener"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <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/DroneStatusChangedListener.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/DroneStatusChangedListener.html" target="_top">Frames</a></li> <li><a href="DroneStatusChangedListener.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface fr.ece.ostis.DroneStatusChangedListener" class="title">Uses of Interface<br>fr.ece.ostis.DroneStatusChangedListener</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/DroneStatusChangedListener.html" title="interface in fr.ece.ostis">DroneStatusChangedListener</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/DroneStatusChangedListener.html" title="interface in fr.ece.ostis">DroneStatusChangedListener</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/DroneStatusChangedListener.html" title="interface in fr.ece.ostis">DroneStatusChangedListener</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/DroneStatusChangedListener.html" title="interface in fr.ece.ostis">DroneStatusChangedListener</a>&gt;</code></td> <td class="colLast"><span class="strong">OstisService.</span><code><strong><a href="../../../../fr/ece/ostis/OstisService.html#mDroneStatusChangedListeners">mDroneStatusChangedListeners</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/DroneStatusChangedListener.html" title="interface in fr.ece.ostis">DroneStatusChangedListener</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#registerStatusChangedListener(fr.ece.ostis.DroneStatusChangedListener)">registerStatusChangedListener</a></strong>(<a href="../../../../fr/ece/ostis/DroneStatusChangedListener.html" title="interface in fr.ece.ostis">DroneStatusChangedListener</a>&nbsp;listener)</code> <div class="block">Registers a drone-status-changed 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#unregisterStatusChangedListener(fr.ece.ostis.DroneStatusChangedListener)">unregisterStatusChangedListener</a></strong>(<a href="../../../../fr/ece/ostis/DroneStatusChangedListener.html" title="interface in fr.ece.ostis">DroneStatusChangedListener</a>&nbsp;listener)</code> <div class="block">Unregisters a drone-status-changed 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/DroneStatusChangedListener.html" title="interface in fr.ece.ostis">DroneStatusChangedListener</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/DroneStatusChangedListener.html" title="interface in fr.ece.ostis">DroneStatusChangedListener</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/NetworkWizardActivity.html" title="class in fr.ece.ostis.ui">NetworkWizardActivity</a></strong></code> <div class="block">TODO</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><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><a href="../../../../fr/ece/ostis/DroneStatusChangedListener.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/DroneStatusChangedListener.html" target="_top">Frames</a></li> <li><a href="DroneStatusChangedListener.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
Java
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
Java
/* 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 hack by Nicolas Gallagher: http://nicolasgallagher.com/micro-clearfix-hack/ */ .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; } }
Java
/* * Copyright (c) 2010 The University of Reading * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University of Reading, nor the names of the * authors or contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package uk.ac.rdg.resc.edal.coverage.domain; import java.util.List; import org.opengis.referencing.crs.CoordinateReferenceSystem; /** * 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 CoordinateReferenceSystem getCoordinateReferenceSystem(); /** * 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(); }
Java
/***************************************************************** * This file is part of Managing Agricultural Research for Learning & * Outcomes Platform (MARLO). * MARLO is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * at your option) any later version. * MARLO is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with MARLO. If not, see <http://www.gnu.org/licenses/>. *****************************************************************/ package org.cgiar.ccafs.marlo.data.manager.impl; import org.cgiar.ccafs.marlo.data.dao.ReportSynthesisGovernanceDAO; import org.cgiar.ccafs.marlo.data.manager.ReportSynthesisGovernanceManager; import org.cgiar.ccafs.marlo.data.model.ReportSynthesisGovernance; import java.util.List; import javax.inject.Inject; import javax.inject.Named; /** * @author CCAFS */ @Named public class ReportSynthesisGovernanceManagerImpl implements ReportSynthesisGovernanceManager { private ReportSynthesisGovernanceDAO reportSynthesisGovernanceDAO; // Managers @Inject public ReportSynthesisGovernanceManagerImpl(ReportSynthesisGovernanceDAO reportSynthesisGovernanceDAO) { this.reportSynthesisGovernanceDAO = reportSynthesisGovernanceDAO; } @Override public void deleteReportSynthesisGovernance(long reportSynthesisGovernanceId) { reportSynthesisGovernanceDAO.deleteReportSynthesisGovernance(reportSynthesisGovernanceId); } @Override public boolean existReportSynthesisGovernance(long reportSynthesisGovernanceID) { return reportSynthesisGovernanceDAO.existReportSynthesisGovernance(reportSynthesisGovernanceID); } @Override public List<ReportSynthesisGovernance> findAll() { return reportSynthesisGovernanceDAO.findAll(); } @Override public ReportSynthesisGovernance getReportSynthesisGovernanceById(long reportSynthesisGovernanceID) { return reportSynthesisGovernanceDAO.find(reportSynthesisGovernanceID); } @Override public ReportSynthesisGovernance saveReportSynthesisGovernance(ReportSynthesisGovernance reportSynthesisGovernance) { return reportSynthesisGovernanceDAO.save(reportSynthesisGovernance); } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_51) on Mon Mar 17 10:31:37 CDT 2014 --> <title>TIntFloatMapDecorator (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="TIntFloatMapDecorator (Trove 3.1a1)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <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/TIntDoubleMapDecorator.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/TIntFloatMapDecorator.html" target="_top">Frames</a></li> <li><a href="TIntFloatMapDecorator.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); 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="#nested_classes_inherited_from_class_java.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> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">gnu.trove.decorator</div> <h2 title="Class TIntFloatMapDecorator" class="title">Class TIntFloatMapDecorator</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.TIntFloatMapDecorator</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">TIntFloatMapDecorator</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.TIntFloatMapDecorator">Serialized Form</a></dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== NESTED CLASS SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="nested_class_summary"> <!-- --> </a> <h3>Nested Class Summary</h3> <ul class="blockList"> <li class="blockList"><a name="nested_classes_inherited_from_class_java.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.SimpleImmutableEntry&lt;K,V&gt;</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="nested_classes_inherited_from_class_java.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> <!-- =========== FIELD SUMMARY =========== --> <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/TIntFloatMapDecorator.html#_map">_map</a></strong></code> <div class="block">the wrapped primitive map</div> </td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <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/TIntFloatMapDecorator.html#TIntFloatMapDecorator()">TIntFloatMapDecorator</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/TIntFloatMapDecorator.html#TIntFloatMapDecorator(gnu.trove.map.TIntFloatMap)">TIntFloatMapDecorator</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> <!-- ========== METHOD SUMMARY =========== --> <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/TIntFloatMapDecorator.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/TIntFloatMapDecorator.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/TIntFloatMapDecorator.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/TIntFloatMapDecorator.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/TIntFloatMapDecorator.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/TIntFloatMapDecorator.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/TIntFloatMapDecorator.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/TIntFloatMapDecorator.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/TIntFloatMapDecorator.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/TIntFloatMapDecorator.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/TIntFloatMapDecorator.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/TIntFloatMapDecorator.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/TIntFloatMapDecorator.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/TIntFloatMapDecorator.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/TIntFloatMapDecorator.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/TIntFloatMapDecorator.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/TIntFloatMapDecorator.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="methods_inherited_from_class_java.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="methods_inherited_from_class_java.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="methods_inherited_from_class_java.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"> <!-- ============ FIELD DETAIL =========== --> <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> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="TIntFloatMapDecorator()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>TIntFloatMapDecorator</h4> <pre>public&nbsp;TIntFloatMapDecorator()</pre> <div class="block">FOR EXTERNALIZATION ONLY!!</div> </li> </ul> <a name="TIntFloatMapDecorator(gnu.trove.map.TIntFloatMap)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>TIntFloatMapDecorator</h4> <pre>public&nbsp;TIntFloatMapDecorator(<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> <!-- ============ METHOD DETAIL ========== --> <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.ClassNotFoundException</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.ClassNotFoundException</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> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><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="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/TIntDoubleMapDecorator.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/TIntFloatMapDecorator.html" target="_top">Frames</a></li> <li><a href="TIntFloatMapDecorator.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); 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="#nested_classes_inherited_from_class_java.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> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
Java
/*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(getCoreSystemMessages) { expect(getCoreSystemMessages).be.defined; }); }); });
Java
{% 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.get_health_general_display|default:"-" }}</td></tr> <tr><td>{% trans 'Beoordeling algemene gezondheid in vergelijking met vorig jaar' %}</td><td>{{ questionnaire.get_health_changes_display|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.get_high_effort_impact_display|default:"-" }}</td></tr> <tr><td>{% trans 'Matige inspanning zoals het verplaatsen van een tafel, stofzuigen, fietsen' %}</td><td>{{ questionnaire.get_poor_effort_impact_display|default:"-" }}</td></tr> <tr><td>{% trans 'Tillen of boodschappen doen' %}</td><td>{{ questionnaire.get_carrying_impact_display|default:"-" }}</td></tr> <tr><td>{% trans 'Een paar trappen lopen' %}</td><td>{{ questionnaire.get_walking_stairs_impact_display|default:"-" }}</td></tr> <tr><td>{% trans 'Een trap lopen' %}</td><td>{{ questionnaire.get_walking_one_stair_impact_display|default:"-" }}</td></tr> <tr><td>{% trans 'Buigen, knielen of bukken' %}</td><td>{{ questionnaire.get_bent_over_impact_display|default:"-" }}</td></tr> <tr><td>{% trans 'Meer dan een kilometer lopen' %}</td><td>{{ questionnaire.get_walk_km_impact_display|default:"-" }}</td></tr> <tr><td>{% trans 'Een halve kilometer lopen' %}</td><td>{{ questionnaire.get_walk_halfkm_impact_display|default:"-" }}</td></tr> <tr><td>{% trans 'Honderd meter lopen' %}</td><td>{{ questionnaire.get_walk_tenthkm_impact_display|default:"-" }}</td></tr> <tr><td>{% trans 'Wassen of aankleden' %}</td><td>{{ questionnaire.get_wash_cloth_impact_display|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.get_work_less_problem_display|default:"-" }}</td></tr> <tr><td>{% trans 'Minder bereikt dan u zou willen' %}</td><td>{{ questionnaire.get_achieve_problem_display|default:"-" }}</td></tr> <tr><td>{% trans 'Beperkt in het soort werk of het soort bezigheden' %}</td><td>{{ questionnaire.get_work_limitation_problem_display|default:"-" }}</td></tr> <tr><td>{% trans 'Moeite met het werk of andere bezigheden' %}</td><td>{{ questionnaire.get_work_effort_problem_display|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.get_work_less_emotional_problem_display|default:"-" }}</td></tr> <tr><td>{% trans 'Minder bereikt dan u zou willen' %}</td><td>{{ questionnaire.get_achieve_problem_display|default:"-" }}</td></tr> <tr><td>{% trans 'Het werk of andere bezigheden niet zo zorgvuldig gedaan als u gewend bent' %}</td><td>{{ questionnaire.get_accurate_emotional_problem_display|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.get_social_impact_display|default:"-" }}</td></tr> <tr><td>{% trans 'Hoeveel pijn had u de afgelopen 4 weken' %}</td><td>{{ questionnaire.get_pain_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Heeft pijn u in de afgelopen 4 weken belemmerd bij uw normale werkzaamheden' %}</td><td>{{ questionnaire.get_pain_impact_display|default:"-" }}</td></tr> <tr><td colspan="2"><h5><i>Gevoel</i></h5></td></tr> <tr><td>{% trans 'Voelde u zich levenslustig' %}</td><td>{{ questionnaire.get_cheerful_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Voelde u zich zenuwachtig' %}</td><td>{{ questionnaire.get_nervious_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Zat u zo in de put dat niets u kon opvrolijken' %}</td><td>{{ questionnaire.get_blues_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Voelde u zich kalm en rustig' %}</td><td>{{ questionnaire.get_calm_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Voelde u zich energiek' %}</td><td>{{ questionnaire.get_energetic_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Voelde u zich neerslachtig en somber' %}</td><td>{{ questionnaire.get_depressed_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Voelde u zich uitgeblust' %}</td><td>{{ questionnaire.get_burnout_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Voelde u zich gelukkig' %}</td><td>{{ questionnaire.get_happiness_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Voelde u zich moe' %}</td><td>{{ questionnaire.get_tired_score_display|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.get_social_visit_impact_display|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.get_easier_ill_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Ik ben net zo gezond als andere mensen die ik ken' %}</td><td>{{ questionnaire.get_even_healthy_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Ik verwacht dat mijn gezondheid achteruit zal gaan' %}</td><td>{{ questionnaire.get_health_drop_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Mijn gezondheid is uitstekend' %}</td><td>{{ questionnaire.get_health_drop_score_display|default:"-" }}</td></tr> </tbody></table>
Java
/// <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()); }
Java
// Copyright ©2015 The gonum Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gonum import ( "gonum.org/v1/gonum/blas" "gonum.org/v1/gonum/lapack" ) // Dlasr applies a sequence of plane rotations to the m×n matrix A. This series // 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 // implicitly represented by a series of 2×2 rotation matrices. The entries of // 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 ] // [ ... ] // [ 1 ] // [ c[k] s[k] ] // [ -s[k] c[k] ] // [ 1 ] // [ ... ] // [ 1] // if pivot == lapack.Top, the rotation is performed for the (1, k+1) plane, // P(k) = [c[k] s[k] ] // [ 1 ] // [ ... ] // [ 1 ] // [-s[k] c[k] ] // [ 1 ] // [ ... ] // [ 1] // and if pivot == lapack.Bottom, the rotation is performed for the (k, z) plane. // P(k) = [1 ] // [ ... ] // [ 1 ] // [ c[k] s[k]] // [ 1 ] // [ ... ] // [ 1 ] // [ -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 } } } }
Java
# -*- encoding: UTF-8 -*- import re import sys import os import traceback from ..ibdawg import IBDAWG from ..echo import echo from . import gc_options __all__ = [ "lang", "locales", "pkg", "name", "version", "author", \ "load", "parse", "getDictionary", \ "setOptions", "getOptions", "getOptionsLabels", "resetOptions", \ "ignoreRule", "resetIgnoreRules" ] __version__ = u"${version}" lang = u"${lang}" locales = ${loc} pkg = u"${implname}" name = u"${name}" version = u"${version}" author = u"${author}" # commons regexes _zEndOfSentence = re.compile(u'([.?!:;…][ .?!… »”")]*|.$)') _zBeginOfParagraph = re.compile(u"^\W*") _zEndOfParagraph = re.compile(u"\W*$") _zNextWord = re.compile(u" +(\w[\w-]*)") _zPrevWord = re.compile(u"(\w[\w-]*) +$") # grammar rules and dictionary _rules = None _dOptions = dict(gc_options.dOpt) # duplication necessary, to be able to reset to default _aIgnoredRules = set() _oDict = None _dAnalyses = {} # cache for data from dictionary _GLOBALS = globals() #### Parsing def parse (sText, sCountry="${country_default}", bDebug=False, dOptions=None): "analyses the paragraph sText and returns list of errors" aErrors = None sAlt = sText dDA = {} dOpt = _dOptions if not dOptions else dOptions # parse paragraph try: sNew, aErrors = _proofread(sText, sAlt, 0, True, dDA, sCountry, dOpt, bDebug) if sNew: sText = sNew except: raise # parse sentences for iStart, iEnd in _getSentenceBoundaries(sText): if 4 < (iEnd - iStart) < 2000: dDA.clear() try: _, errs = _proofread(sText[iStart:iEnd], sAlt[iStart:iEnd], iStart, False, dDA, sCountry, dOpt, bDebug) aErrors.extend(errs) except: raise return aErrors def _getSentenceBoundaries (sText): iStart = _zBeginOfParagraph.match(sText).end() for m in _zEndOfSentence.finditer(sText): yield (iStart, m.end()) iStart = m.end() def _proofread (s, sx, nOffset, bParagraph, dDA, sCountry, dOptions, bDebug): aErrs = [] bChange = False if not bParagraph: # after the first pass, we modify automatically some characters if u" " in s: s = s.replace(u" ", u' ') # nbsp bChange = True if u" " in s: s = s.replace(u" ", u' ') # nnbsp bChange = True if u"@" in s: s = s.replace(u"@", u' ') bChange = True if u"'" in s: s = s.replace(u"'", u"’") bChange = True if u"‑" in s: s = s.replace(u"‑", u"-") # nobreakdash bChange = True bIdRule = option('idrule') for sOption, lRuleGroup in _getRules(bParagraph): if not sOption or dOptions.get(sOption, False): for zRegex, bUppercase, sRuleId, lActions in lRuleGroup: if sRuleId not in _aIgnoredRules: for m in zRegex.finditer(s): for sFuncCond, cActionType, sWhat, *eAct in lActions: # action in lActions: [ condition, action type, replacement/suggestion/action[, iGroup[, message, URL]] ] try: if not sFuncCond or _GLOBALS[sFuncCond](s, sx, m, dDA, sCountry): if cActionType == "-": # grammar error # (text, replacement, nOffset, m, iGroup, sId, bUppercase, sURL, bIdRule) aErrs.append(_createError(s, sWhat, nOffset, m, eAct[0], sRuleId, bUppercase, eAct[1], eAct[2], bIdRule, sOption)) elif cActionType == "~": # text processor s = _rewrite(s, sWhat, eAct[0], m, bUppercase) bChange = True if bDebug: echo(u"~ " + s + " -- " + m.group(eAct[0]) + " # " + sRuleId) elif cActionType == "=": # disambiguation _GLOBALS[sWhat](s, m, dDA) if bDebug: echo(u"= " + m.group(0) + " # " + sRuleId + "\nDA: " + str(dDA)) else: echo("# error: unknown action at " + sRuleId) except Exception as e: raise Exception(str(e), sRuleId) if bChange: return (s, aErrs) return (False, aErrs) def _createWriterError (s, sRepl, nOffset, m, iGroup, sId, bUppercase, sMsg, sURL, bIdRule, sOption): "error for Writer (LO/OO)" xErr = SingleProofreadingError() #xErr = uno.createUnoStruct( "com.sun.star.linguistic2.SingleProofreadingError" ) xErr.nErrorStart = nOffset + m.start(iGroup) xErr.nErrorLength = m.end(iGroup) - m.start(iGroup) xErr.nErrorType = PROOFREADING xErr.aRuleIdentifier = sId # suggestions if sRepl[0:1] == "=": sugg = _GLOBALS[sRepl[1:]](s, m) if sugg: if bUppercase and m.group(iGroup)[0:1].isupper(): xErr.aSuggestions = tuple(map(str.capitalize, sugg.split("|"))) else: xErr.aSuggestions = tuple(sugg.split("|")) else: xErr.aSuggestions = () elif sRepl == "_": xErr.aSuggestions = () else: if bUppercase and m.group(iGroup)[0:1].isupper(): xErr.aSuggestions = tuple(map(str.capitalize, m.expand(sRepl).split("|"))) else: xErr.aSuggestions = tuple(m.expand(sRepl).split("|")) # Message if sMsg[0:1] == "=": sMessage = _GLOBALS[sMsg[1:]](s, m) else: sMessage = m.expand(sMsg) xErr.aShortComment = sMessage # sMessage.split("|")[0] # in context menu xErr.aFullComment = sMessage # sMessage.split("|")[-1] # in dialog if bIdRule: xErr.aShortComment += " # " + sId # URL if sURL: p = PropertyValue() p.Name = "FullCommentURL" p.Value = sURL xErr.aProperties = (p,) else: xErr.aProperties = () return xErr def _createDictError (s, sRepl, nOffset, m, iGroup, sId, bUppercase, sMsg, sURL, bIdRule, sOption): "error as a dictionary" dErr = {} dErr["nStart"] = nOffset + m.start(iGroup) dErr["nEnd"] = nOffset + m.end(iGroup) dErr["sRuleId"] = sId dErr["sType"] = sOption if sOption else "notype" # suggestions if sRepl[0:1] == "=": sugg = _GLOBALS[sRepl[1:]](s, m) if sugg: if bUppercase and m.group(iGroup)[0:1].isupper(): dErr["aSuggestions"] = list(map(str.capitalize, sugg.split("|"))) else: dErr["aSuggestions"] = sugg.split("|") else: dErr["aSuggestions"] = () elif sRepl == "_": dErr["aSuggestions"] = () else: if bUppercase and m.group(iGroup)[0:1].isupper(): dErr["aSuggestions"] = list(map(str.capitalize, m.expand(sRepl).split("|"))) else: dErr["aSuggestions"] = m.expand(sRepl).split("|") # Message if sMsg[0:1] == "=": sMessage = _GLOBALS[sMsg[1:]](s, m) else: sMessage = m.expand(sMsg) dErr["sMessage"] = sMessage if bIdRule: dErr["sMessage"] += " # " + sId # URL dErr["URL"] = sURL if sURL else "" return dErr def _rewrite (s, sRepl, iGroup, m, bUppercase): "text processor: write sRepl in s at iGroup position" ln = m.end(iGroup) - m.start(iGroup) if sRepl == "*": sNew = " " * ln elif sRepl == ">" or sRepl == "_" or sRepl == u"~": sNew = sRepl + " " * (ln-1) elif sRepl == "@": sNew = "@" * ln elif sRepl[0:1] == "=": if sRepl[1:2] != "@": sNew = _GLOBALS[sRepl[1:]](s, m) sNew = sNew + " " * (ln-len(sNew)) else: sNew = _GLOBALS[sRepl[2:]](s, m) sNew = sNew + "@" * (ln-len(sNew)) if bUppercase and m.group(iGroup)[0:1].isupper(): sNew = sNew.capitalize() else: sNew = m.expand(sRepl) sNew = sNew + " " * (ln-len(sNew)) return s[0:m.start(iGroup)] + sNew + s[m.end(iGroup):] def ignoreRule (sId): _aIgnoredRules.add(sId) def resetIgnoreRules (): _aIgnoredRules.clear() #### init try: # LibreOffice / OpenOffice from com.sun.star.linguistic2 import SingleProofreadingError from com.sun.star.text.TextMarkupType import PROOFREADING from com.sun.star.beans import PropertyValue #import lightproof_handler_${implname} as opt _createError = _createWriterError except ImportError: _createError = _createDictError def load (): global _oDict try: _oDict = IBDAWG("${binary_dic}") except: traceback.print_exc() def setOptions (dOpt): _dOptions.update(dOpt) def getOptions (): return _dOptions def getOptionsLabels (sLang): return gc_options.getUI(sLang) def resetOptions (): global _dOptions _dOptions = dict(gc_options.dOpt) def getDictionary (): return _oDict def _getRules (bParagraph): try: if not bParagraph: return _rules.lSentenceRules return _rules.lParagraphRules except: _loadRules() if not bParagraph: return _rules.lSentenceRules return _rules.lParagraphRules def _loadRules2 (): from itertools import chain from . import gc_rules global _rules _rules = gc_rules # compile rules regex for rule in chain(_rules.lParagraphRules, _rules.lSentenceRules): try: rule[1] = re.compile(rule[1]) except: echo("Bad regular expression in # " + str(rule[3])) rule[1] = "(?i)<Grammalecte>" def _loadRules (): from itertools import chain from . import gc_rules global _rules _rules = gc_rules # compile rules regex for rulegroup in chain(_rules.lParagraphRules, _rules.lSentenceRules): for rule in rulegroup[1]: try: rule[0] = re.compile(rule[0]) except: echo("Bad regular expression in # " + str(rule[2])) rule[0] = "(?i)<Grammalecte>" def _getPath (): return os.path.join(os.path.dirname(sys.modules[__name__].__file__), __name__ + ".py") #### common functions def option (sOpt): "return True if option sOpt is active" return _dOptions.get(sOpt, False) def displayInfo (dDA, tWord): "for debugging: retrieve info of word" if not tWord: echo("> nothing to find") return True if tWord[1] not in _dAnalyses and not _storeMorphFromFSA(tWord[1]): echo("> not in FSA") return True if tWord[0] in dDA: echo("DA: " + str(dDA[tWord[0]])) echo("FSA: " + str(_dAnalyses[tWord[1]])) return True def _storeMorphFromFSA (sWord): "retrieves morphologies list from _oDict -> _dAnalyses" global _dAnalyses _dAnalyses[sWord] = _oDict.getMorph(sWord) return True if _dAnalyses[sWord] else False def morph (dDA, tWord, sPattern, bStrict=True, bNoWord=False): "analyse a tuple (position, word), return True if sPattern in morphologies (disambiguation on)" if not tWord: return bNoWord if tWord[1] not in _dAnalyses and not _storeMorphFromFSA(tWord[1]): return False lMorph = dDA[tWord[0]] if tWord[0] in dDA else _dAnalyses[tWord[1]] if not lMorph: return False p = re.compile(sPattern) if bStrict: return all(p.search(s) for s in lMorph) return any(p.search(s) for s in lMorph) def morphex (dDA, tWord, sPattern, sNegPattern, bNoWord=False): "analyse a tuple (position, word), returns True if not sNegPattern in word morphologies and sPattern in word morphologies (disambiguation on)" if not tWord: return bNoWord if tWord[1] not in _dAnalyses and not _storeMorphFromFSA(tWord[1]): return False lMorph = dDA[tWord[0]] if tWord[0] in dDA else _dAnalyses[tWord[1]] # check negative condition np = re.compile(sNegPattern) if any(np.search(s) for s in lMorph): return False # search sPattern p = re.compile(sPattern) return any(p.search(s) for s in lMorph) def analyse (sWord, sPattern, bStrict=True): "analyse a word, return True if sPattern in morphologies (disambiguation off)" if sWord not in _dAnalyses and not _storeMorphFromFSA(sWord): return False if not _dAnalyses[sWord]: return False p = re.compile(sPattern) if bStrict: return all(p.search(s) for s in _dAnalyses[sWord]) return any(p.search(s) for s in _dAnalyses[sWord]) def analysex (sWord, sPattern, sNegPattern): "analyse a word, returns True if not sNegPattern in word morphologies and sPattern in word morphologies (disambiguation off)" if sWord not in _dAnalyses and not _storeMorphFromFSA(sWord): return False # check negative condition np = re.compile(sNegPattern) if any(np.search(s) for s in _dAnalyses[sWord]): return False # search sPattern p = re.compile(sPattern) return any(p.search(s) for s in _dAnalyses[sWord]) def stem (sWord): "returns a list of sWord's stems" if not sWord: return [] if sWord not in _dAnalyses and not _storeMorphFromFSA(sWord): return [] return [ s[1:s.find(" ")] for s in _dAnalyses[sWord] ] ## functions to get text outside pattern scope # warning: check compile_rules.py to understand how it works def nextword (s, iStart, n): "get the nth word of the input string or empty string" m = re.match(u"( +[\\w%-]+){" + str(n-1) + u"} +([\\w%-]+)", s[iStart:]) if not m: return None return (iStart+m.start(2), m.group(2)) def prevword (s, iEnd, n): "get the (-)nth word of the input string or empty string" m = re.search(u"([\\w%-]+) +([\\w%-]+ +){" + str(n-1) + u"}$", s[:iEnd]) if not m: return None return (m.start(1), m.group(1)) def nextword1 (s, iStart): "get next word (optimization)" m = _zNextWord.match(s[iStart:]) if not m: return None return (iStart+m.start(1), m.group(1)) def prevword1 (s, iEnd): "get previous word (optimization)" m = _zPrevWord.search(s[:iEnd]) if not m: return None return (m.start(1), m.group(1)) def look (s, sPattern, sNegPattern=None): "seek sPattern in s (before/after/fulltext), if sNegPattern not in s" if sNegPattern and re.search(sNegPattern, s): return False if re.search(sPattern, s): return True return False def look_chk1 (dDA, s, nOffset, sPattern, sPatternGroup1, sNegPatternGroup1=None): "returns True if s has pattern sPattern and m.group(1) has pattern sPatternGroup1" m = re.search(sPattern, s) if not m: return False try: sWord = m.group(1) nPos = m.start(1) + nOffset except: #print("Missing group 1") return False if sNegPatternGroup1: return morphex(dDA, (nPos, sWord), sPatternGroup1, sNegPatternGroup1) return morph(dDA, (nPos, sWord), sPatternGroup1, False) #### Disambiguator def select (dDA, nPos, sWord, sPattern, lDefault=None): if not sWord: return True if nPos in dDA: return True if sWord not in _dAnalyses and not _storeMorphFromFSA(sWord): return True if len(_dAnalyses[sWord]) == 1: return True lSelect = [ sMorph for sMorph in _dAnalyses[sWord] if re.search(sPattern, sMorph) ] if lSelect: if len(lSelect) != len(_dAnalyses[sWord]): dDA[nPos] = lSelect #echo("= "+sWord+" "+str(dDA.get(nPos, "null"))) elif lDefault: dDA[nPos] = lDefault #echo("= "+sWord+" "+str(dDA.get(nPos, "null"))) return True def exclude (dDA, nPos, sWord, sPattern, lDefault=None): if not sWord: return True if nPos in dDA: return True if sWord not in _dAnalyses and not _storeMorphFromFSA(sWord): return True if len(_dAnalyses[sWord]) == 1: return True lSelect = [ sMorph for sMorph in _dAnalyses[sWord] if not re.search(sPattern, sMorph) ] if lSelect: if len(lSelect) != len(_dAnalyses[sWord]): dDA[nPos] = lSelect #echo("= "+sWord+" "+str(dDA.get(nPos, "null"))) elif lDefault: dDA[nPos] = lDefault #echo("= "+sWord+" "+str(dDA.get(nPos, "null"))) return True def define (dDA, nPos, lMorph): dDA[nPos] = lMorph #echo("= "+str(nPos)+" "+str(dDA[nPos])) return True #### GRAMMAR CHECKER PLUGINS ${plugins} ${generated}
Java
/* «Camelion» - Perl storable/C struct back-and-forth translator * * Copyright (C) Alexey Shishkin 2016 * * This file is part of Project «Camelion». * * Project «Camelion» is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Project «Camelion» is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Project «Camelion». If not, see <http://www.gnu.org/licenses/>. */ #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 CML_ERROR_USER_BADDATA; *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 CML_SerialsReadUINT8(CML_Bytes * bytes, uint32_t * bpos, uint8_t * result) { if (*bpos + sizeof(uint8_t) > bytes->size) return CML_ERROR_USER_BADDATA; *result = bytes->data[*bpos]; *bpos += 1; return CML_ERROR_SUCCESS; } CML_Error CML_SerialsReadINT32(CML_Bytes * bytes, uint32_t * bpos, int32_t * result) { if (*bpos + sizeof(int32_t) > bytes->size) return CML_ERROR_USER_BADDATA; 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 CML_SerialsReadUINT32(CML_Bytes * bytes, uint32_t * bpos, uint32_t * result) { if (*bpos + sizeof(uint32_t) > bytes->size) return CML_ERROR_USER_BADDATA; 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 CML_ERROR_USER_BADDATA; uint32_t i; for (i = 0; i < length; i++, *bpos += 1) result[i] = bytes->data[*bpos]; result[i] = '\0'; return CML_ERROR_SUCCESS; }
Java
package com.entrepidea.jvm; import java.util.ArrayList; import java.util.List; /** * @Desc: * @Source: 深入理解Java虚拟机:JVM高级特性与最佳实践(第2版) * Created by jonat on 10/18/2019. * TODO need revisit - the code seem just running - supposedly it should end soon with exceptions. */ public class RuntimeConstantPoolOOM { public static void main(String[] args){ List<String> l = new ArrayList<>(); int i=0; while(true){ l.add(String.valueOf(i++).intern()); } } }
Java
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 listOnlyThatLevelsModules = 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 SpringBattleStartSetup GetSpringBattleStartSetup(BattleContext context) { try { AutohostMode mode = context.GetMode(); var ret = new SpringBattleStartSetup(); 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 accountIDsWithExtraComms = 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)) accountIDsWithExtraComms.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 SpringBattleStartSetup.ScriptKeyValuePair { Key = "attackingFaction", Value = attacker.Shortcut }); if (defender != null) ret.ModOptions.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "defendingFaction", Value = defender.Shortcut }); ret.ModOptions.Add(new SpringBattleStartSetup.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<SpringBattleStartSetup.ScriptKeyValuePair>(); ret.UserParameters.Add(new SpringBattleStartSetup.UserCustomParameters { LobbyID = p.LobbyID, Parameters = userParams }); bool userBanMuted = user.PunishmentsByAccountID.Any(x => !x.IsExpired && x.BanMute); if (userBanMuted) userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "muted", Value = "1" }); userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "faction", Value = user.Faction != null ? user.Faction.Shortcut : "" }); userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "clan", Value = user.Clan != null ? user.Clan.Shortcut : "" }); userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "level", Value = user.Level.ToString() }); double elo = mode == AutohostMode.Planetwars ? user.EffectivePwElo : (is1v1 ? user.Effective1v1Elo : user.EffectiveElo); userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "elo", Value = Math.Round(elo).ToString() }); // elo for ingame is just ordering for auto /take userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "avatar", Value = user.Avatar }); userParams.Add(new SpringBattleStartSetup.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.EffectPreventIngamePwStructureDestruction == true, planet); if (!allied && user.Faction != null && (user.Faction == attacker || user.Faction == defender)) { userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "canAttackPwStructures", Value = "1" }); } } var pu = new LuaTable(); bool userUnlocksBanned = user.PunishmentsByAccountID.Any(x => !x.IsExpired && x.BanUnlocks); bool userCommandersBanned = user.PunishmentsByAccountID.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 SpringBattleStartSetup.ScriptKeyValuePair { Key = "unlocks", Value = pu.ToBase64String() }); if (accountIDsWithExtraComms.Contains(user.AccountID)) userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "extracomm", Value = "1" }); var pc = new LuaTable(); if (!userCommandersBanned) { // set up commander data foreach (Commander c in user.Commanders.Where(x => x.Unlock != null && x.ProfileNumber <= GlobalConst.CommanderProfileCount)) { 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.CommanderDecorations.Where(x => x.Unlock != null).OrderBy( x => x.SlotID).Select(x => x.Unlock)) { CommanderDecorationIcon iconData = db.CommanderDecorationIcons.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.GetTotalMorphLevelCost(i); if (listOnlyThatLevelsModules) { 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 ApplicationException( string.Format("Error processing commander: {0} - {1} of player {2} - {3}", c.CommanderID, c.Name, user.AccountID, user.Name), ex); } } } else userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "jokecomm", Value = "1" }); userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "commanders", Value = pc.ToBase64String() }); } } } ret.ModOptions.Add(new SpringBattleStartSetup.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 SpringBattleStartSetup.ScriptKeyValuePair { Key = "planetwarsStructures", Value = pwStructures.ToBase64String() }); } return ret; } catch (Exception ex) { Trace.TraceError(ex.ToString()); throw; } } } }
Java
# wp_project Project for Web Programming exam Cartelle: spec: contiene il file delle specifiche e tutto ciò che è inerente alla progettazione dell'elaborato doc: contiene tutti i file della documentazione prodotta src: contiene i file sorgenti del progetto Students: Luca Bettinelli, Michele Masciale e Matteo Mario
Java
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.AbstractCursorAdapter; 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 RESULT_EXTRA_ITEM_ID = ItemListFragment.class.getName() + ".RESULT_EXTRA_ITEM_ID"; public static final String RESULT_EXTRA_ITEM_IDS = ItemListFragment.class.getName() + ".RESULT_EXTRA_ITEM_IDS"; // ----------------------------------------------------------------------------------------------------------------- public static final int SELECTION_TYPE_NONE = 0; public static final int SELECTION_TYPE_SINGLE = 1; public static final int SELECTION_TYPE_MULTI = 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 ARG_IS_OPEN_DRAWER_LAYOUT = "ARG_IS_OPEN_DRAWER_LAYOUT"; // ----------------------------------------------------------------------------------------------------------------- protected static final String STATE_SELECTED_POSITIONS = "STATE_SELECTED_POSITIONS"; // ----------------------------------------------------------------------------------------------------------------- protected static final int LOADER_ITEMS = 1468; // ----------------------------------------------------------------------------------------------------------------- protected ListView list_V; protected View create_V; // ----------------------------------------------------------------------------------------------------------------- protected AbstractCursorAdapter 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(ARG_IS_OPEN_DRAWER_LAYOUT, 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.setOnItemClickListener(this); if (getArguments().getBoolean(ARG_IS_OPEN_DRAWER_LAYOUT, false)) { final int paddingHorizontal = getResources().getDimensionPixelSize(R.dimen.dynamic_margin_drawer_narrow_horizontal); list_V.setPadding(paddingHorizontal, list_V.getPaddingTop(), paddingHorizontal, list_V.getPaddingBottom()); } if (selectionType == SELECTION_TYPE_MULTI) { list_V.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE); if (savedInstanceState != null) { final ArrayList<Integer> selectedPositions = savedInstanceState.getIntegerArrayList(STATE_SELECTED_POSITIONS); 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 == SELECTION_TYPE_MULTI) { final ArrayList<Integer> selectedPositions = new ArrayList<Integer>(); final SparseBooleanArray listPositions = list_V.getCheckedItemPositions(); if (listPositions != null) { for (int i = 0; i < listPositions.size(); i++) { if (listPositions.get(listPositions.keyAt(i))) selectedPositions.add(listPositions.keyAt(i)); } } outState.putIntegerArrayList(STATE_SELECTED_POSITIONS, selectedPositions); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.items_list, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_create: startItemCreate(getActivity(), item.getActionView()); return true; } return super.onOptionsItemSelected(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 SELECTION_TYPE_SINGLE: // Prepare extras final Bundle extras = new Bundle(); onItemSelected(id, adapter, adapter.getCursor(), extras); Intent data = new Intent(); data.putExtra(RESULT_EXTRA_ITEM_ID, id); data.putExtras(extras); getActivity().setResult(Activity.RESULT_OK, data); getActivity().finish(); break; case SELECTION_TYPE_MULTI: adapter.setSelectedIDs(list_V.getCheckedItemIds()); break; } } protected abstract AbstractCursorAdapter 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, AbstractCursorAdapter 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, AbstractCursorAdapter 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 needUpdateSelectedIDs = adapter.getCount() == 0 && selectionType == SELECTION_TYPE_MULTI; adapter.swapCursor(c); if (needUpdateSelectedIDs && 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 ForLoopReplaceableByForEach 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 ForLoopReplaceableByForEach 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()); } } }
Java
#ifndef __LINUX_VIDEODEV_H #define __LINUX_VIDEODEV_H /* Linux V4L API, Version 1 * videodev.h from v4l driver in Linux 2.2.3 * * Used here with the explicit permission of the original author, Alan Cox. * <alan@lxorguk.ukuu.org.uk> */ /* $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 VIDEO_TUNER_STEREO_ON 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 VIDEO_PALETTE_RGB565 3 /* 565 16 bit RGB */ #define VIDEO_PALETTE_RGB24 4 /* 24bit RGB */ #define VIDEO_PALETTE_RGB32 5 /* 32bit RGB */ #define VIDEO_PALETTE_RGB555 6 /* 555 15bit RGB */ #define VIDEO_PALETTE_YUV422 7 /* YUV422 capture */ #define VIDEO_PALETTE_YUYV 8 #define VIDEO_PALETTE_UYVY 9 /* The great thing about standards is ... */ #define VIDEO_PALETTE_YUV420 10 #define VIDEO_PALETTE_YUV411 11 /* YUV411 capture */ #define VIDEO_PALETTE_RAW 12 /* RAW capture (BT848) */ #define VIDEO_PALETTE_YUV422P 13 /* YUV 4:2:2 Planar */ #define VIDEO_PALETTE_YUV411P 14 /* YUV 4:1:1 Planar */ #define VIDEO_PALETTE_YUV420P 15 /* YUV 4:2:0 Planar */ #define VIDEO_PALETTE_YUV410P 16 /* YUV 4:1:0 Planar */ #define VIDEO_PALETTE_PLANAR 13 /* start of planar entries */ #define VIDEO_PALETTE_COMPONENT 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 VIDEO_WINDOW_INTERLACE 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 VID_HARDWARE_QCAM_BW 2 #define VID_HARDWARE_PMS 3 #define VID_HARDWARE_QCAM_C 4 #define VID_HARDWARE_PSEUDO 5 #define VID_HARDWARE_SAA5249 6 #define VID_HARDWARE_AZTECH 7 #define VID_HARDWARE_SF16MI 8 #define VID_HARDWARE_RTRACK 9 #define VID_HARDWARE_ZOLTRIX 10 #define VID_HARDWARE_SAA7146 11 #define VID_HARDWARE_VIDEUM 12 /* Reserved for Winnov videum */ #define VID_HARDWARE_RTRACK2 13 #define VID_HARDWARE_PERMEDIA2 14 /* Reserved for Permedia2 */ #define VID_HARDWARE_RIVA128 15 /* Reserved for RIVA 128 */ #define VID_HARDWARE_PLANB 16 /* PowerMac motherboard video-in */ #define VID_HARDWARE_BROADWAY 17 /* Broadway project */ #define VID_HARDWARE_GEMTEK 18 #define VID_HARDWARE_TYPHOON 19 #define VID_HARDWARE_VINO 20 /* Reserved for SGI Indy Vino */ /* * Initialiser list */ struct video_init { char *name; int (*init)(struct video_init *); }; #endif
Java
// XDwgDirectReader.cpp: implementation of the XDwgDirectReader class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "atlbase.h" #include "XDwgDirectReader.h" #include "db.h" #include "DwgEntityDumper.h" #include "ExSystemServices.h" #include "ExHostAppServices.h" #include "RxDynamicModule.h" ////////////////////////////////////////////////////////////////////////// /////////////DwgReaderServices////////////////////////////////////////////// class DwgReaderServices : public ExSystemServices, public ExHostAppServices { protected: ODRX_USING_HEAP_OPERATORS(ExSystemServices); }; OdRxObjectImpl<DwgReaderServices> svcs; ExProtocolExtension theProtocolExtensions; const CString g_szEntityType = "ENTITY_TYPE"; //gisÊý¾Ý¸ñÍø´óС const double DEFAULT_GIS_GRID_SIZE = 120.0; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// XDWGReader::XDWGReader() { //³õʼ»¯DwgDirect¿â odInitialize(&svcs); theProtocolExtensions.initialize(); //ĬÈ϶ÁÈ¡CAD²ÎÊýÉèÖà m_IsReadPolygon = FALSE; m_IsLine2Polygon = FALSE; m_IsBreakBlock = FALSE; m_IsReadInvisible = FALSE; m_IsJoinXDataAttrs = FALSE; m_IsReadBlockPoint = TRUE; m_IsCreateAnnotation = TRUE; m_iUnbreakBlockMode = 0; m_pSpRef = NULL; m_dAnnoScale = 1; m_bConvertAngle = TRUE; m_pProgressBar = NULL; m_pLogRec = NULL; InitAOPointers(); m_Regapps.RemoveAll(); m_unExplodeBlocks.RemoveAll(); m_bFinishedCreateFtCls = FALSE; m_StepNum = 5000; } XDWGReader::~XDWGReader() { m_unExplodeBlocks.RemoveAll(); theProtocolExtensions.uninitialize(); odUninitialize(); if (m_pLogRec != NULL) { delete m_pLogRec; } } ////////////////////////////////////////////////////////////////////////// //¼òÒªÃèÊö : ɾ³ýÒÑ´æÔÚµÄÒªËØÀà //ÊäÈë²ÎÊý : //·µ »Ø Öµ : //ÐÞ¸ÄÈÕÖ¾ : ////////////////////////////////////////////////////////////////////////// void XDWGReader::CheckDeleteFtCls(IFeatureWorkspace* pFtWS, CString sFtClsName) { if (pFtWS == NULL) return; IFeatureClass* pFtCls = NULL; pFtWS->OpenFeatureClass(CComBSTR(sFtClsName), &pFtCls); if (pFtCls != NULL) { IDatasetPtr pDs = pFtCls; if (pDs != NULL) { pDs->Delete(); } } } /******************************************************************** ¼òÒªÃèÊö : ÅúÁ¿¶ÁȡǰµÄ×¼±¸¹¤×÷ ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : *********************************************************************/ BOOL XDWGReader::PrepareReadDwg(IWorkspace* pTargetWS, IDataset* pTargetDataset, ISpatialReference* pSpRef) { try { m_pTargetWS = pTargetWS; //³õʼ»¯Ö¸Õë //InitAOPointers(); //ÎÞ·¨¶ÁÈ¡µÄʵÌå¸öÊý m_lUnReadEntityNum = 0; ////////////////////////////////////////////////////////////////////////// IFeatureDatasetPtr pFeatDataset(pTargetDataset); if (pSpRef == NULL) { ISpatialReferencePtr pUnknownSpRef(CLSID_UnknownCoordinateSystem); m_pSpRef = pUnknownSpRef.Detach(); m_pSpRef->SetDomain(0.0, 1000000000, 0.0, 1000000000); } else { m_pSpRef = pSpRef; } ////////////////////////////////////////////////////////////////////////// //ÉèÖÃΪ¸ß¾«¶È£¬·ñÔòÎÞ·¨´´½¨±í»òFEATURECLASS IControlPrecision2Ptr pControlPrecision(m_pSpRef); if (pControlPrecision != NULL) { pControlPrecision->put_IsHighPrecision(VARIANT_TRUE); } //ÉèÖÿռä²Î¿¼¾«¶ÈÖµ ISpatialReferenceResolutionPtr spatialReferenceResolution = m_pSpRef; spatialReferenceResolution->SetDefaultMResolution(); spatialReferenceResolution->SetDefaultZResolution(); spatialReferenceResolution->SetDefaultXYResolution(); //ÉèÖÿռä×ø±êÎó²îÖµ ISpatialReferenceTolerancePtr spatialReferenceTolerance = m_pSpRef; spatialReferenceTolerance->SetDefaultMTolerance(); spatialReferenceTolerance->SetDefaultZTolerance(); spatialReferenceTolerance->SetDefaultXYTolerance(); m_bFinishedCreateFtCls = FALSE; return TRUE; } catch (...) { WriteLog("³õʼ»¯Òì³£,Çë¼ì²é¹¤×÷¿Õ¼äºÍ¿Õ¼ä²Î¿¼ÊÇ·ñÕýÈ·."); return FALSE; } } ////////////////////////////////////////////////////////////////////////// //¼òÒªÃèÊö : ´´½¨Ä¿±êÒªËØÀà //ÊäÈë²ÎÊý : //·µ »Ø Öµ : //ÐÞ¸ÄÈÕÖ¾ : ////////////////////////////////////////////////////////////////////////// BOOL XDWGReader::CreateTargetAllFeatureClass() { try { IFeatureWorkspacePtr pFtWS(m_pTargetWS); if (pFtWS == NULL) return FALSE; HRESULT hr; CString sInfoText; //´´½¨ÏµÍ³±í½á¹¹ IFieldsPtr ipFieldsPoint = 0; IFieldsPtr ipFieldsLine = 0; IFieldsPtr ipFieldsPolygon = 0; IFieldsPtr ipFieldsText = 0; IFieldsPtr ipFieldsAnnotation = 0; //Éú³ÉÆÕͨµãÀà×Ö¶Î CreateDwgPointFields(m_pSpRef, &ipFieldsPoint); //Éú³É×¢¼ÇµãÀà×Ö¶Î CreateDwgTextPointFields(m_pSpRef, &ipFieldsText); //Éú³ÉÏßÒªËØÀà×Ö¶Î CreateDwgLineFields(m_pSpRef, &ipFieldsLine); //Éú³ÉÃæÒªËØÀà×Ö¶Î CreateDwgPolygonFields(m_pSpRef, &ipFieldsPolygon); //Éú³É×¢¼Çͼ²ã×Ö¶Î CreateDwgAnnotationFields(m_pSpRef, &ipFieldsAnnotation); ////////////////////////////////////////////////////////////////////////// //Ôö¼ÓÀ©Õ¹ÊôÐÔ×Ö¶Î if (m_IsJoinXDataAttrs && m_Regapps.GetCount() > 0) { IFieldsEditPtr ipEditFieldsPoint = ipFieldsPoint; IFieldsEditPtr ipEditFieldsLine = ipFieldsLine; IFieldsEditPtr ipEditFieldsPolygon = ipFieldsPolygon; IFieldsEditPtr ipEditFieldsText = ipFieldsText; IFieldsEditPtr ipEditFieldsAnnotation = ipFieldsAnnotation; CString sRegappName; for (int i = 0; i < m_Regapps.GetCount(); i++) { //´´½¨À©Õ¹ÊôÐÔ×Ö¶Î IFieldPtr ipField(CLSID_Field); IFieldEditPtr ipFieldEdit = ipField; sRegappName = m_Regapps.GetAt(m_Regapps.FindIndex(i)); CComBSTR bsStr = sRegappName; ipFieldEdit->put_Name(bsStr); ipFieldEdit->put_AliasName(bsStr); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(2000); long lFldIndex = 0; ipEditFieldsPoint->FindField(bsStr, &lFldIndex); if (lFldIndex == -1) { ipEditFieldsPoint->AddField(ipField); } ipEditFieldsLine->FindField(bsStr, &lFldIndex); if (lFldIndex == -1) { ipEditFieldsLine->AddField(ipField); } ipEditFieldsPolygon->FindField(bsStr, &lFldIndex); if (lFldIndex == -1) { ipEditFieldsPolygon->AddField(ipField); } ipEditFieldsText->FindField(bsStr, &lFldIndex); if (lFldIndex == -1) { ipEditFieldsText->AddField(ipField); } ipEditFieldsAnnotation->FindField(bsStr, &lFldIndex); if (lFldIndex == -1) { ipEditFieldsAnnotation->AddField(ipField); } } } //Èç¹ûÓÐͼ²ãÏÈɾ³ý CheckDeleteFtCls(pFtWS, "Point"); CheckDeleteFtCls(pFtWS, "TextPoint"); CheckDeleteFtCls(pFtWS, "Line"); CheckDeleteFtCls(pFtWS, "Polygon"); CheckDeleteFtCls(pFtWS, "Annotation"); CheckDeleteFtCls(pFtWS, "ExtendTable"); //´´½¨µãͼ²ã hr = CreateDatasetFeatureClass(pFtWS, NULL, ipFieldsPoint, CComBSTR("Point"), esriFTSimple, m_pFeatClassPoint); if (m_pFeatClassPoint != NULL) { hr = m_pFeatClassPoint->Insert(VARIANT_TRUE, &m_pPointFeatureCursor); if (FAILED(hr)) { sInfoText.Format("´´½¨µãFeatureCursorʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } hr = m_pFeatClassPoint->CreateFeatureBuffer(&m_pPointFeatureBuffer); if (FAILED(hr)) { sInfoText.Format("´´½¨µãFeautureBufferʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } } else { sInfoText.Format("´´½¨PointÒªËØÀàʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); return FALSE; } //´´½¨ÏßÒªËØÀà hr = CreateDatasetFeatureClass(pFtWS, NULL, ipFieldsLine, CComBSTR("Line"), esriFTSimple, m_pFeatClassLine); if (m_pFeatClassLine != NULL) { hr = m_pFeatClassLine->Insert(VARIANT_TRUE, &m_pLineFeatureCursor); if (FAILED(hr)) { sInfoText.Format("´´½¨ÏßFeatureCursorʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } hr = m_pFeatClassLine->CreateFeatureBuffer(&m_pLineFeatureBuffer); if (FAILED(hr)) { sInfoText.Format("´´½¨ÏßFeautureBufferʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } } else { sInfoText.Format("´´½¨LineÒªËØÀàʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); return FALSE; } if (m_IsReadPolygon || m_IsLine2Polygon) { //´´½¨ÃæÒªËØÀà hr = CreateDatasetFeatureClass(pFtWS, NULL, ipFieldsPolygon, CComBSTR("Polygon"), esriFTSimple, m_pFeatClassPolygon); if (m_pFeatClassPolygon != NULL) { hr = m_pFeatClassPolygon->Insert(VARIANT_TRUE, &m_pPolygonFeatureCursor); if (FAILED(hr)) { sInfoText.Format("´´½¨ÃæFeatureCursorʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } hr = m_pFeatClassPolygon->CreateFeatureBuffer(&m_pPolygonFeatureBuffer); if (FAILED(hr)) { sInfoText.Format("´´½¨ÃæFeautureBufferʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } } else { sInfoText.Format("´´½¨PolygonÒªËØÀàʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); return FALSE; } } //arcgis ×¢¼Çͼ²ã if (m_IsCreateAnnotation) { m_pAnnoFtCls = CreateAnnoFtCls(m_pTargetWS, "Annotation", ipFieldsAnnotation); if (m_pAnnoFtCls != NULL) { //ÉèÖÃÏÖʵ±ÈÀý³ß IUnknownPtr pUnk; m_pAnnoFtCls->get_Extension(&pUnk); IAnnoClassAdminPtr pAnnoClassAdmin = pUnk; if (pAnnoClassAdmin != NULL) { hr = pAnnoClassAdmin->put_ReferenceScale(m_dAnnoScale); hr = pAnnoClassAdmin->UpdateProperties(); } hr = m_pAnnoFtCls->Insert(VARIANT_TRUE, &m_pAnnoFeatureCursor); if (FAILED(hr)) { sInfoText.Format("´´½¨×¢¼ÇFeatureCursorʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } hr = m_pAnnoFtCls->CreateFeatureBuffer(&m_pAnnoFeatureBuffer); if (FAILED(hr)) { sInfoText.Format("´´½¨×¢¼ÇFeautureBufferʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } } else { sInfoText.Format("´´½¨AnnotationÒªËØÀàʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); return FALSE; } //´´½¨×¢¼Çͼ²ã×ÖÌå IFontDispPtr pFont(CLSID_StdFont); IFontPtr fnt = pFont; fnt->put_Name(CComBSTR("ËÎÌå")); CY cy; cy.int64 = 9; fnt->put_Size(cy); m_pAnnoTextFont = pFont.Detach(); } else { //Îı¾µã hr = CreateDatasetFeatureClass(pFtWS, NULL, ipFieldsText, CComBSTR("TextPoint"), esriFTSimple, m_pFeatClassText); if (m_pFeatClassText != NULL) { hr = m_pFeatClassText->Insert(VARIANT_TRUE, &m_pTextFeatureCursor); if (FAILED(hr)) { sInfoText.Format("´´½¨Îı¾µãFeatureCursorʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } hr = m_pFeatClassText->CreateFeatureBuffer(&m_pTextFeatureBuffer); if (FAILED(hr)) { sInfoText.Format("´´½¨Îı¾FeautureBufferʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } } else { sInfoText.Format("´´½¨TextÒªËØÀàʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); return FALSE; } } //À©Õ¹ÊôÐÔ±í hr = CreateExtendTable(pFtWS, CComBSTR("ExtendTable"), &m_pExtendTable); if (m_pExtendTable != NULL) { hr = m_pExtendTable->Insert(VARIANT_TRUE, &m_pExtentTableRowCursor); if (FAILED(hr)) { sInfoText.Format("´´½¨TableBufferʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } hr = m_pExtendTable->CreateRowBuffer(&m_pExtentTableRowBuffer); if (FAILED(hr)) { sInfoText.Format("´´½¨TableCursorʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } } else { sInfoText.Format("´´½¨ExtendTableʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); return FALSE; } m_bFinishedCreateFtCls = TRUE; return TRUE; } catch (...) { return FALSE; } } ////////////////////////////////////////////////////////////////////////// //¼òÒªÃèÊö : Öð¸ö¶ÁÈ¡CADÎļþ //ÊäÈë²ÎÊý : //·µ »Ø Öµ : //ÐÞ¸ÄÈÕÖ¾ : ////////////////////////////////////////////////////////////////////////// BOOL XDWGReader::ReadFile(LPCTSTR lpdwgFilename) { try { //Éú³ÉÄ¿±êGDBͼ²ã if (!m_bFinishedCreateFtCls) { if (!CreateTargetAllFeatureClass()) { WriteLog("´´½¨Ä¿±êÒªËØÀà³öÏÖÒì³££¬ÎÞ·¨½øÐиñʽת»»¡£"); return FALSE; } } //Çå³ý²»¶ÁµÄͼ²ãÁбí m_UnReadLayers.RemoveAll(); //´ò¿ªCADÎļþ²¢¶ÁÈ¡ //µÃµ½DWGͼÃûºÍÈÕÖ¾ÎļþÃû CString szDatasetName ; CString szLogFileName; int index; CString sFileName = lpdwgFilename; sFileName = sFileName.Mid(sFileName.ReverseFind('\\') + 1); index = ((CString) lpdwgFilename).ReverseFind('\\'); int ilength = ((CString) lpdwgFilename).GetLength(); szDatasetName = CString(lpdwgFilename).Right(ilength - 1 - index); index = szDatasetName.ReverseFind('.'); szDatasetName = szDatasetName.Left(index); m_strDwgName = szDatasetName; // ¼Ç¼¿ªÊ¼´¦Àíʱ¼ä CTime tStartTime = CTime::GetCurrentTime(); CString sInfoText; sInfoText.Format("¿ªÊ¼¶Á %s Îļþ.", lpdwgFilename); WriteLog(sInfoText); if (m_pProgressBar != NULL) { m_pProgressBar->SetPos(0); CString sProgressText; sProgressText.Format("ÕýÔÚ¶ÁÈ¡%s, ÇëÉÔºò...", lpdwgFilename); m_pProgressBar->SetWindowText(sProgressText); } OdDbDatabasePtr pDb; pDb = svcs.readFile(lpdwgFilename, false, false, Oda::kShareDenyReadWrite); if (pDb.isNull()) { WriteLog("DWGÎļþΪ¿Õ!"); } // ´ÓdwgÎļþ»ñµÃ·¶Î§ sInfoText.Format("ͼ·ù·¶Î§: ×îСX×ø±ê:%f, ×î´óX×ø±ê:%f, ×îСY×ø±ê:%f, ×î´óY×ø±ê:%f \n", 0.9 * pDb->getEXTMIN().x, 1.1 * pDb->getEXTMAX().x, 0.9 * pDb->getEXTMIN().y, 1.1 * pDb->getEXTMAX().y); WriteLog(sInfoText); //¶ÁCADÎļþ ReadBlock(pDb); pDb.release(); //¼Ç¼Íê³Éʱ¼ä CTime tEndTime = CTime::GetCurrentTime(); CTimeSpan span = tEndTime - tStartTime; sInfoText.Format("%sÎļþת»»Íê³É!¹²ºÄʱ%dʱ%d·Ö%dÃë.", lpdwgFilename, span.GetHours(), span.GetMinutes(), span.GetSeconds()); WriteLog(sInfoText); WriteLog("=============================================================="); return TRUE; } catch (...) { CString sErr; sErr.Format("%sÎļþ²»´æÔÚ»òÕý´¦ÓÚ´ò¿ª×´Ì¬£¬ÎÞ·¨½øÐÐÊý¾Ý¶ÁÈ¡£¬Çë¼ì²é¡£", lpdwgFilename); WriteLog(sErr); return FALSE; } } /******************************************************************** ¼òÒªÃèÊö : ÉèÖÃÈÕÖ¾´æ·Å·¾¶ ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÈÕ ÆÚ : 2008/09/27,BeiJing. ×÷ Õß : ×ÚÁÁ <zongliang@Hy.com.cn> ÐÞ¸ÄÈÕÖ¾ : *********************************************************************/ void XDWGReader::PutLogFilePath(CString sLogFile) { m_pLogRec = new CLogRecorder(sLogFile); m_sLogFilePath = sLogFile; } //дÈÕÖ¾Îļþ void XDWGReader::WriteLog(CString sLog) { if (m_pLogRec == NULL) { return; } if (!sLog.IsEmpty()) { m_pLogRec->WriteLog(sLog); } } //½áÊøDWGµÄ¶ÁÈ¡¹¤×÷ BOOL XDWGReader::CommitReadDwg() { //ÊÍ·ÅÓõ½µÄ¶ÔÏó ReleaseAOs(); if (m_pLogRec != NULL) { m_pLogRec->CloseFile(); } return TRUE; } void XDWGReader::ReadHeader(OdDbDatabase* pDb) { OdString sName = pDb->getFilename(); CString sInfoText; sInfoText.Format("Database was loaded from:%s", sName.c_str()); WriteLog(sInfoText); OdDb::DwgVersion vVer = pDb->originalFileVersion(); sInfoText.Format("File version is: %s", OdDb::DwgVersionToStr(vVer)); WriteLog(sInfoText); sInfoText.Format("Header Variables: %f,%f", pDb->getLTSCALE(), pDb->getATTMODE()); WriteLog(sInfoText); OdDbDate d = pDb->getTDCREATE(); short month, day, year, hour, min, sec, msec; d.getDate(month, day, year); d.getTime(hour, min, sec, msec); sInfoText.Format(" TDCREATE: %d-%d-%d,%d:%d:%d", month, day, year, hour, min, sec); WriteLog(sInfoText); d = pDb->getTDUPDATE(); d.getDate(month, day, year); d.getTime(hour, min, sec, msec); sInfoText.Format(" TDCREATE: %d-%d-%d,%d:%d:%d", month, day, year, hour, min, sec); WriteLog(sInfoText); } void XDWGReader::ReadSymbolTable(OdDbObjectId tableId) { OdDbSymbolTablePtr pTable = tableId.safeOpenObject(); CString sInfoText; sInfoText.Format("±íÃû:%s", pTable->isA()->name()); WriteLog(sInfoText); OdDbSymbolTableIteratorPtr pIter = pTable->newIterator(); for (pIter->start(); !pIter->done(); pIter->step()) { OdDbSymbolTableRecordPtr pTableRec = pIter->getRecordId().safeOpenObject(); CString TableRecName; TableRecName.Format("%s", pTableRec->getName().c_str()); TableRecName.MakeUpper(); sInfoText.Format(" %s<%s>", TableRecName, pTableRec->isA()->name()); WriteLog(sInfoText); } } void XDWGReader::ReadLayers(OdDbDatabase* pDb) { OdDbLayerTablePtr pLayers = pDb->getLayerTableId().safeOpenObject(); CString sInfoText; sInfoText.Format("²ãÃû:%s", pLayers->desc()->name()); WriteLog(sInfoText); OdDbSymbolTableIteratorPtr pIter = pLayers->newIterator(); for (pIter->start(); !pIter->done(); pIter->step()) { OdDbLayerTableRecordPtr pLayer = pIter->getRecordId().safeOpenObject(); CString LayerName; LayerName.Format("%s", pLayer->desc()->name()); LayerName.MakeUpper(); sInfoText.Format(" %s<%s>,layercolor:%d,%s,%s,%s,%s", pLayer->getName().c_str(), LayerName, pLayer->colorIndex(), pLayer->isOff() ? "Off" : "On", pLayer->isLocked() ? "Locked" : "Unlocked", pLayer->isFrozen() ? "Frozen" : "UnFrozen", pLayer->isDependent() ? "Dep. on XRef" : "Not dep. on XRef"); WriteLog(sInfoText); } } /************************************************************************ ¼òÒªÃèÊö : ¶ÁDWGÀ©Õ¹ÊôÐÔ,²¢Ð´Èëµ½À©Õ¹ÊôÐÔ±íÖÐ ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ void XDWGReader::ReadExtendAttribs(OdResBuf* xIter, CString sEntityHandle) { if (xIter == 0 || m_pExtendTable == NULL) return; CMapStringToPtr mapExtraRes; //±£´æËùÓÐÓ¦Óü°À©Õ¹ÊôÐÔ (Ó¦ÓÃÃû+CStringList*) //Registered Application Name CString sAppName; CString sExtendValue; //CStringList lstExtendValues;//ËùÓÐÀ©Õ¹ÊôÐÔ,ÓÃ[]ºÅ·Ö¸ô OdResBuf* xIterLoop = xIter; for (; xIterLoop != 0; xIterLoop = xIterLoop->next()) { int code = xIterLoop->restype(); switch (OdDxfCode::_getType(code)) { case OdDxfCode::Name: case OdDxfCode::String: sExtendValue.Format("%s", xIterLoop->getString().c_str()); break; case OdDxfCode::Bool: sExtendValue.Format("%d", xIterLoop->getBool()); break; case OdDxfCode::Integer8: sExtendValue.Format("%d", xIterLoop->getInt8()); break; case OdDxfCode::Integer16: sExtendValue.Format("%d", xIterLoop->getInt16()); break; case OdDxfCode::Integer32: sExtendValue.Format("%d", xIterLoop->getInt32()); break; case OdDxfCode::Double: sExtendValue.Format("%f", xIterLoop->getDouble()); break; case OdDxfCode::Angle: sExtendValue.Format("%f", xIterLoop->getDouble()); break; case OdDxfCode::Point: { OdGePoint3d p = xIterLoop->getPoint3d(); sExtendValue.Format("%f,%f,%f", p.x, p.y, p.z); } break; case OdDxfCode::BinaryChunk: sExtendValue = "<Binary Data>"; break; case OdDxfCode::Handle: case OdDxfCode::LayerName: sExtendValue.Format("%s", xIterLoop->getString().c_str()); break; case OdDxfCode::ObjectId: case OdDxfCode::SoftPointerId: case OdDxfCode::HardPointerId: case OdDxfCode::SoftOwnershipId: case OdDxfCode::HardOwnershipId: { OdDbHandle h = xIterLoop->getHandle(); sExtendValue.Format("%s", h.ascii()); } break; case OdDxfCode::Unknown: default: sExtendValue = "Unknown"; break; } //Registered Application Name if (code == OdResBuf::kDxfRegAppName) { sAppName = sExtendValue; //Éú³É¶ÔÓ¦ÓÚ¸ÃÓ¦ÓõÄStringList CStringList* pLstExtra = new CStringList(); mapExtraRes.SetAt(sAppName, pLstExtra); } else if (code == OdResBuf::kDxfXdAsciiString || code == OdResBuf::kDxfXdReal) { void* rValue; if (mapExtraRes.Lookup(sAppName, rValue)) { CStringList* pLstExtra = (CStringList*)rValue; //±£´æµ½¶ÔÓ¦ÓÚ¸ÃAPPNameµÄListÖÐ pLstExtra->AddTail(sExtendValue); } } } POSITION mapPos = mapExtraRes.GetStartPosition(); while (mapPos) { CString sAppName; void* rValue; mapExtraRes.GetNextAssoc(mapPos, sAppName, rValue); CStringList* pList = (CStringList*) rValue; HRESULT hr; long lFieldIndex; CComBSTR bsStr; CComVariant vtVal; //Éú³ÉÀ©Õ¹ÊôÐÔ×Ö·û´® POSITION pos = pList->GetHeadPosition(); if (pos != NULL) { CString sAllValues = "[" + pList->GetNext(pos) + "]"; while (pos != NULL) { sAllValues = sAllValues + "[" + pList->GetNext(pos) + "]"; } //Add Extend data to Extend Table bsStr = "Handle"; m_pExtendTable->FindField(bsStr, &lFieldIndex); vtVal = sEntityHandle; m_pExtentTableRowBuffer->put_Value(lFieldIndex, vtVal); bsStr = "BaseName"; m_pExtendTable->FindField(bsStr, &lFieldIndex); vtVal = m_strDwgName; m_pExtentTableRowBuffer->put_Value(lFieldIndex, vtVal); bsStr = "XDataName"; m_pExtendTable->FindField(bsStr, &lFieldIndex); sAppName.MakeUpper(); vtVal = sAppName; m_pExtentTableRowBuffer->put_Value(lFieldIndex, vtVal); bsStr = "XDataValue"; m_pExtendTable->FindField(bsStr, &lFieldIndex); vtVal = sAllValues; m_pExtentTableRowBuffer->put_Value(lFieldIndex, vtVal); hr = m_pExtentTableRowCursor->InsertRow(m_pExtentTableRowBuffer, &m_TableId); if (FAILED(hr)) { WriteLog("À©Õ¹ÊôÐÔ¶Áȡʧ°Ü:" + CatchErrorInfo()); } } m_pExtentTableRowCursor->Flush(); vtVal.Clear(); bsStr.Empty(); pList->RemoveAll(); delete pList; } mapExtraRes.RemoveAll(); } /******************************************************************** ¼òÒªÃèÊö : ÖØÃüÃûͼ²ãÃû£¬Õë¶Ô¼ÃÄÏÏîÄ¿µãºÍÏßÔÚͬÒÔͼ²ãÏ£¬·ÖÀë³öÏßÒªËØµ½Ö¸¶¨Í¼²ãÏ ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : *********************************************************************/ /*void XDWGReader::RenameEntityLayerName(CString sDwgOriLayerName, IFeatureBuffer*& pFeatBuffer) { if (m_lstRenameLayers.GetCount() <= 0) { return; } //ÖØÐÂÖ¸¶¨Í¼²ã£¬°ÑÏß²ã·Åµ½ÏàÓ¦µÄ¸¨ÖúÏßͼ²ãÖÐÈ¥ POSITION pos = m_lstRenameLayers.GetHeadPosition(); while (pos != NULL) { RenameLayerRecord* pRenameRec = m_lstRenameLayers.GetNext(pos); if (pRenameRec->sDWG_LAYERNAME_CONTAINS.IsEmpty()||pRenameRec->sNEW_DWG_LAYERNAME.IsEmpty()||pRenameRec->sNEW_LAYERTYPE.IsEmpty()) { continue; } if (pRenameRec->sNEW_LAYERTYPE.CompareNoCase("Line") == 0) { CStringList lstKeys; CString sKeyStr; CString sLayerNameContains = pRenameRec->sDWG_LAYERNAME_CONTAINS; int iPos = sLayerNameContains.Find(','); while (iPos != -1) { sKeyStr = sLayerNameContains.Mid(0, iPos); sLayerNameContains = sLayerNameContains.Mid(iPos + 1); iPos = sLayerNameContains.Find(','); lstKeys.AddTail(sKeyStr); } sKeyStr = sLayerNameContains; lstKeys.AddTail(sKeyStr); bool bFindKey = true; for (int ki=0; ki< lstKeys.GetCount(); ki++) { sKeyStr = lstKeys.GetAt(lstKeys.FindIndex(ki)); if (sDwgOriLayerName.Find(sKeyStr) == -1) { bFindKey = false; break; } } //Èç¹û°üº¬ËùÓÐÌØÕ÷Öµ£¬Ôò¸üÃû if (bFindKey) { AddAttributes("Layer", pRenameRec->sNEW_DWG_LAYERNAME, pFeatBuffer); break; } } } } */ /******************************************************************** ¼òÒªÃèÊö : ²åÈë×¢¼ÇÒªËØ ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : *********************************************************************/ void XDWGReader::InsertAnnoFeature(OdRxObject* pEnt) { HRESULT hr; OdDbEntityPtr pOdDbEnt = pEnt; if (pOdDbEnt.isNull()) return; CString sEntType = pOdDbEnt->isA()->name(); if (sEntType.Compare("AcDbMText") == 0 || sEntType.Compare("AcDbText") == 0 || sEntType.Compare("AcDbAttribute") == 0) { // Ìí¼ÓÊôÐÔ AddBaseAttributes(pOdDbEnt, "Annotation", m_pAnnoFeatureBuffer); //CString sTempVal; CString sText = ""; double dHeight = 0; double dWeight = 0; double dAngle = 0; OdGePoint3d textPos; //¶ÔÆëµã OdGePoint3d alignPoint; esriTextHorizontalAlignment horizAlign = esriTHALeft; esriTextVerticalAlignment vertAlign = esriTVABaseline; CString sTextStyle = "STANDARD"; CString sHeight = "0"; CString sElevation = "0"; CString sThickness = "0"; CString sOblique = "0"; if (sEntType.Compare("AcDbMText") == 0) { OdDbMTextPtr pMText = OdDbMTextPtr(pEnt); //Îı¾ÄÚÈÝ sText = pMText->contents(); int iPos = sText.ReverseFind(';'); sText = sText.Mid(iPos + 1); sText.Replace("{", ""); sText.Replace("}", ""); //Îı¾·ç¸ñ OdDbSymbolTableRecordPtr symbolbRec = OdDbSymbolTableRecordPtr(pMText->textStyle().safeOpenObject()); if (!symbolbRec.isNull()) { sTextStyle.Format("%s", symbolbRec->getName()); } //¸ß¶È sHeight.Format("%f", pMText->textHeight()); //¸ß³ÌÖµ sElevation.Format("%f", pMText->location().z); ////Éú³É×¢¼ÇÐèÒªµÄ²ÎÊý//// //½Ç¶È dAngle = pMText->rotation(); //¸ßºÍ¿í dHeight = pMText->textHeight(); dWeight = pMText->width(); //λÖõã textPos = pMText->location(); //ÉèÖÃ¶ÔÆë·½Ê½ if (pMText->horizontalMode() == OdDb::kTextLeft) { horizAlign = esriTHALeft; } else if (pMText->horizontalMode() == OdDb::kTextCenter) { horizAlign = esriTHACenter; } else if (pMText->horizontalMode() == OdDb::kTextRight) { horizAlign = esriTHARight; } else if (pMText->horizontalMode() == OdDb::kTextFit) { horizAlign = esriTHAFull; } if (pMText->verticalMode() == OdDb::kTextBase) { vertAlign = esriTVABaseline; } else if (pMText->verticalMode() == OdDb::kTextBottom) { vertAlign = esriTVABottom; } else if (pMText->verticalMode() == OdDb::kTextTop) { vertAlign = esriTVATop; } else if (pMText->verticalMode() == OdDb::kTextVertMid) { vertAlign = esriTVACenter; } } else if (sEntType.Compare("AcDbText") == 0 || sEntType.Compare("AcDbAttribute") == 0) { OdDbTextPtr pText = OdDbTextPtr(pEnt); //Îı¾ÄÚÈÝ sText = pText->textString(); //Îı¾·ç¸ñ OdDbSymbolTableRecordPtr symbolbRec = OdDbSymbolTableRecordPtr(pText->textStyle().safeOpenObject()); if (!symbolbRec.isNull()) { sTextStyle.Format("%s", symbolbRec->getName()); } //¸ß³ÌÖµ sElevation.Format("%f", pText->position().z); //¸ß¶È sHeight.Format("%f", pText->height()); //ºñ¶È sThickness.Format("%.f", pText->thickness()); //Çã½Ç sOblique.Format("%f", pText->oblique()); ////Éú³É×¢¼ÇÐèÒªµÄ²ÎÊý//// //½Ç¶È dAngle = pText->rotation(); dHeight = pText->height(); dWeight = 0; textPos = pText->position(); alignPoint = pText->alignmentPoint(); //if (textPos.x <= 0.0001 && textPos.y <= 0.0001) //Èç¹ûûÓÐ¶ÔÆëµã£¬ÔòʹÓÃλÖõã //{ // textPos = pText->position(); //} CString tempstr; tempstr.Format("%f", alignPoint.x); AddAttributes("AlignPtX", tempstr, m_pAnnoFeatureBuffer); tempstr.Format("%f", alignPoint.y); AddAttributes("AlignPtY", tempstr, m_pAnnoFeatureBuffer); //OdGePoint3dArray boundingPoints; //pText->getBoundingPoints(boundingPoints); //OdGePoint3d topLeft = boundingPoints[0]; //OdGePoint3d topRight = boundingPoints[1]; //OdGePoint3d bottomLeft = boundingPoints[2]; //OdGePoint3d bottomRight = boundingPoints[3]; //ÉèÖÃ¶ÔÆë·½Ê½ if (pText->horizontalMode() == OdDb::kTextLeft) { horizAlign = esriTHALeft; } else if (pText->horizontalMode() == OdDb::kTextCenter) { horizAlign = esriTHACenter; } else if (pText->horizontalMode() == OdDb::kTextRight) { horizAlign = esriTHARight; } else if (pText->horizontalMode() == OdDb::kTextFit) { horizAlign = esriTHAFull; } if (pText->verticalMode() == OdDb::kTextBase) { vertAlign = esriTVABaseline; } else if (pText->verticalMode() == OdDb::kTextBottom) { vertAlign = esriTVABottom; } else if (pText->verticalMode() == OdDb::kTextTop) { vertAlign = esriTVATop; } else if (pText->verticalMode() == OdDb::kTextVertMid) { vertAlign = esriTVACenter; } } //ÉèÖÃ×¢¼ÇÎı¾·ç¸ñ AddAttributes("TextStyle", sTextStyle, m_pAnnoFeatureBuffer); AddAttributes("Height", sHeight, m_pAnnoFeatureBuffer); AddAttributes("Elevation", sElevation, m_pAnnoFeatureBuffer); AddAttributes("Thickness", sThickness, m_pAnnoFeatureBuffer); AddAttributes("Oblique", sOblique, m_pAnnoFeatureBuffer); //´´½¨ Element ITextElementPtr pTextElement = MakeTextElementByStyle(sText, dAngle, dHeight, textPos.x, textPos.y, m_dAnnoScale, horizAlign, vertAlign); IElementPtr pElement = pTextElement; IAnnotationFeaturePtr pTarAnnoFeat = m_pAnnoFeatureBuffer; hr = pTarAnnoFeat->put_Annotation(pElement); PutExtendAttribsValue(m_pAnnoFeatureBuffer, OdDbEntityPtr(pEnt)->xData()); CComVariant OID; hr = m_pAnnoFeatureCursor->InsertFeature(m_pAnnoFeatureBuffer, &OID); if (FAILED(hr)) { CString sInfoText; sInfoText = "Annotation¶ÔÏóдÈëµ½PGDBʧ°Ü." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } } ////////////////////////////////////////////////////////////////////////// //¼òÒªÃèÊö : ²åÈëCADÊôÐÔ¶ÔÏó //ÊäÈë²ÎÊý : //·µ »Ø Öµ : //ÐÞ¸ÄÈÕÖ¾ : ////////////////////////////////////////////////////////////////////////// void XDWGReader::InsertDwgAttribFeature(OdRxObject* pEnt) { HRESULT hr; OdDbEntityPtr pOdDbEnt = pEnt; if (pOdDbEnt.isNull()) return; CString sEntType = pOdDbEnt->isA()->name(); if (strcmp(sEntType, "AcDbAttributeDefinition") == 0) { // Ìí¼ÓÊôÐÔ AddBaseAttributes(pOdDbEnt, "Annotation", m_pAnnoFeatureBuffer); //CString sTempVal; CString sText = ""; double dHeight = 0; double dWeight = 0; double dAngle = 0; OdGePoint3d textPos; esriTextHorizontalAlignment horizAlign = esriTHALeft; esriTextVerticalAlignment vertAlign = esriTVABaseline; CString sTextStyle = "STANDARD"; CString sHeight = "0"; CString sElevation = "0"; CString sThickness = "0"; CString sOblique = "0"; OdDbAttributeDefinitionPtr pText = OdDbAttributeDefinitionPtr(pEnt); //Îı¾ÄÚÈÝ CString sTag = pText->tag(); CString sPrompt = pText->prompt(); sText = sTag; //Îı¾·ç¸ñ OdDbSymbolTableRecordPtr symbolbRec = OdDbSymbolTableRecordPtr(pText->textStyle().safeOpenObject()); if (!symbolbRec.isNull()) { sTextStyle.Format("%s", symbolbRec->getName()); } //¸ß³ÌÖµ sElevation.Format("%f", pText->position().z); //¸ß¶È sHeight.Format("%f", pText->height()); //ºñ¶È sThickness.Format("%.f", pText->thickness()); //Çã½Ç sOblique.Format("%f", pText->oblique()); ////Éú³É×¢¼ÇÐèÒªµÄ²ÎÊý//// //½Ç¶È dAngle = pText->rotation(); dHeight = pText->height(); dWeight = 0; textPos = pText->alignmentPoint(); if (textPos.x <= 0.0001 && textPos.y <= 0.0001) //Èç¹ûûÓÐ¶ÔÆëµã£¬ÔòʹÓÃλÖõã { textPos = pText->position(); } //ÉèÖÃ¶ÔÆë·½Ê½ if (pText->horizontalMode() == OdDb::kTextLeft) { horizAlign = esriTHALeft; } else if (pText->horizontalMode() == OdDb::kTextCenter) { horizAlign = esriTHACenter; } else if (pText->horizontalMode() == OdDb::kTextRight) { horizAlign = esriTHARight; } else if (pText->horizontalMode() == OdDb::kTextFit) { horizAlign = esriTHAFull; } if (pText->verticalMode() == OdDb::kTextBase) { vertAlign = esriTVABaseline; } else if (pText->verticalMode() == OdDb::kTextBottom) { vertAlign = esriTVABottom; } else if (pText->verticalMode() == OdDb::kTextTop) { vertAlign = esriTVATop; } else if (pText->verticalMode() == OdDb::kTextVertMid) { vertAlign = esriTVACenter; } //ÉèÖÃ×¢¼ÇÎı¾·ç¸ñ AddAttributes("TextStyle", sTextStyle, m_pAnnoFeatureBuffer); AddAttributes("Height", sHeight, m_pAnnoFeatureBuffer); AddAttributes("Elevation", sElevation, m_pAnnoFeatureBuffer); AddAttributes("Thickness", sThickness, m_pAnnoFeatureBuffer); AddAttributes("Oblique", sOblique, m_pAnnoFeatureBuffer); //´´½¨ Element ITextElementPtr pTextElement = MakeTextElementByStyle(sText, dAngle, dHeight, textPos.x, textPos.y, m_dAnnoScale, horizAlign, vertAlign); IElementPtr pElement = pTextElement; IAnnotationFeaturePtr pTarAnnoFeat = m_pAnnoFeatureBuffer; hr = pTarAnnoFeat->put_Annotation(pElement); PutExtendAttribsValue(m_pAnnoFeatureBuffer, OdDbEntityPtr(pEnt)->xData()); CComVariant OID; hr = m_pAnnoFeatureCursor->InsertFeature(m_pAnnoFeatureBuffer, &OID); if (FAILED(hr)) { CString sInfoText; sInfoText = "Annotation¶ÔÏóдÈëµ½PGDBʧ°Ü." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } } /******************************************************************** ¼òÒªÃèÊö : Ìí¼ÓÀ©Õ¹ÊôÐÔÖµ ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : *********************************************************************/ BOOL XDWGReader::PutExtendAttribsValue(IFeatureBuffer*& pFtBuf, OdResBuf* xIter) { if (m_IsJoinXDataAttrs == FALSE || m_Regapps.GetCount() <= 0 || xIter == NULL) { return FALSE; } CMapStringToPtr mapExtraRes; //±£´æËùÓÐÓ¦Óü°À©Õ¹ÊôÐÔ (Ó¦ÓÃÃû+CStringList*) //Registered Application Name CString sAppName; CString sExtendValue; //CStringList lstExtendValues;//ËùÓÐÀ©Õ¹ÊôÐÔ,ÓÃ,ºÅ·Ö¸ô OdResBuf* xIterLoop = xIter; for (; xIterLoop != 0; xIterLoop = xIterLoop->next()) { int code = xIterLoop->restype(); switch (OdDxfCode::_getType(code)) { case OdDxfCode::Name: case OdDxfCode::String: sExtendValue.Format("%s", xIterLoop->getString().c_str()); break; case OdDxfCode::Bool: sExtendValue.Format("%d", xIterLoop->getBool()); break; case OdDxfCode::Integer8: sExtendValue.Format("%d", xIterLoop->getInt8()); break; case OdDxfCode::Integer16: sExtendValue.Format("%d", xIterLoop->getInt16()); break; case OdDxfCode::Integer32: sExtendValue.Format("%d", xIterLoop->getInt32()); break; case OdDxfCode::Double: sExtendValue.Format("%f", xIterLoop->getDouble()); break; case OdDxfCode::Angle: sExtendValue.Format("%f", xIterLoop->getDouble()); break; case OdDxfCode::Point: { OdGePoint3d p = xIterLoop->getPoint3d(); sExtendValue.Format("%f,%f,%f", p.x, p.y, p.z); } break; case OdDxfCode::BinaryChunk: sExtendValue = "<Binary Data>"; break; case OdDxfCode::Handle: case OdDxfCode::LayerName: sExtendValue.Format("%s", xIterLoop->getString().c_str()); break; case OdDxfCode::ObjectId: case OdDxfCode::SoftPointerId: case OdDxfCode::HardPointerId: case OdDxfCode::SoftOwnershipId: case OdDxfCode::HardOwnershipId: { OdDbHandle h = xIterLoop->getHandle(); sExtendValue.Format("%s", h.ascii()); } break; case OdDxfCode::Unknown: default: sExtendValue = "Unknown"; break; } //Registered Application Name if (code == OdResBuf::kDxfRegAppName) { sAppName = sExtendValue; //Éú³É¶ÔÓ¦ÓÚ¸ÃÓ¦ÓõÄStringList CStringList* pLstExtra = new CStringList(); mapExtraRes.SetAt(sAppName, pLstExtra); } else if (code == OdResBuf::kDxfXdAsciiString || code == OdResBuf::kDxfXdReal) { void* rValue; if (mapExtraRes.Lookup(sAppName, rValue)) { CStringList* pLstExtra = (CStringList*) rValue; //±£´æµ½¶ÔÓ¦ÓÚ¸ÃAPPNameµÄListÖÐ pLstExtra->AddTail(sExtendValue); } } } //µÃµ½×Ö¶Î IFieldsPtr pFields; pFtBuf->get_Fields(&pFields); POSITION mapPos = mapExtraRes.GetStartPosition(); while (mapPos) { CString sAppName; void* rValue; mapExtraRes.GetNextAssoc(mapPos, sAppName, rValue); CStringList* pList = (CStringList*) rValue; long lIdx = 0; pFields->FindField(CComBSTR(sAppName), &lIdx); if (lIdx != -1) { CString sAllValues = ""; //Éú³ÉÀ©Õ¹ÊôÐÔ×Ö·û´® POSITION pos = pList->GetHeadPosition(); if (pos != NULL) { sAllValues = pList->GetNext(pos); while (pos != NULL) { sAllValues = sAllValues + "," + pList->GetNext(pos) ; } pFtBuf->put_Value(lIdx, CComVariant(sAllValues)); } } pList->RemoveAll(); delete pList; } mapExtraRes.RemoveAll(); return TRUE; } ////////////////////////////////////////////////////////////////////////// //¼òÒªÃèÊö : ¶ÁCADµÄÿ¸öʵÌåÒªËØ //ÊäÈë²ÎÊý : //·µ »Ø Öµ : //ÐÞ¸ÄÈÕÖ¾ : ////////////////////////////////////////////////////////////////////////// void XDWGReader::ReadEntity(OdDbObjectId id) { OdDbEntityPtr pEnt = id.safeOpenObject(); OdDbLayerTableRecordPtr pLayerTableRecord = pEnt->layerId().safeOpenObject(); CString sInfoText; if ((pLayerTableRecord->isOff() || pLayerTableRecord->isLocked() || pLayerTableRecord->isFrozen()) && (m_IsReadInvisible == FALSE)) { //±ÜÃâÈÕÖ¾ÖØ¸´ÄÚÈÝ CString sUnReadLayer = pEnt->layer().c_str(); POSITION pos = m_UnReadLayers.Find(sUnReadLayer); if (pos == NULL) { m_UnReadLayers.AddTail(sUnReadLayer); sInfoText.Format("<%s>²ãÒªËØ²»¿ÉÊÓ²»´¦Àí!", sUnReadLayer); WriteLog(sInfoText); } m_lUnReadEntityNum++; } else { OdDbHandle hTmp; char szEntityHandle[50] = {0}; hTmp = pEnt->getDbHandle(); hTmp.getIntoAsciiBuffer(szEntityHandle); //¼Ç¼µ±Ç°handleÖµ m_sEntityHandle = szEntityHandle; //Çå¿ÕFeatureBuffer CleanAllFeatureBuffers(); OdSmartPtr<OdDbEntity_Dumper> pEntDumper = pEnt; IGeometryPtr pShape; HRESULT hr; CComVariant OID; pEntDumper->m_DwgReader = this; // »ñµÃ¼¸ºÎÊý¾Ý pShape = pEntDumper->dump(pEnt); if (pShape == NULL) { m_lUnReadEntityNum++; return ; } //ÐÞÕý¿Õ¼ä²Î¿¼ hr = pShape->Project(m_pSpRef); // Îı¾ CString sEntType = OdDbEntityPtr(pEnt)->isA()->name(); if ((strcmp(sEntType, "AcDbMText") == 0) || (strcmp(sEntType, "AcDbText") == 0) || (strcmp(sEntType, "AcDbShape") == 0)) { if (m_IsCreateAnnotation) { //²åÈë×¢¼Ç¶ÔÏó InsertAnnoFeature(pEnt); } else { hr = m_pTextFeatureBuffer->putref_Shape(pShape); if (SUCCEEDED(hr)) { AddBaseAttributes(pEnt, "Annotation", m_pTextFeatureBuffer); //±àÂë¶ÔÕÕ if (CompareCodes(m_pTextFeatureBuffer)) { PutExtendAttribsValue(m_pTextFeatureBuffer, pEnt->xData()); hr = m_pTextFeatureCursor->InsertFeature(m_pTextFeatureBuffer, &OID); if (FAILED(hr)) { sInfoText = "Text¶ÔÏóдÈëµ½PGDBʧ°Ü¡£" + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } } else { sInfoText = "Text¶ÔÏó×ø±ê²»ÕýÈ·¡£" + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } } else { esriGeometryType shapeType; pShape->get_GeometryType(&shapeType); if (shapeType == esriGeometryPoint) //µã { hr = m_pPointFeatureBuffer->putref_Shape(pShape); if (SUCCEEDED(hr)) { AddBaseAttributes(pEnt, "Point", m_pPointFeatureBuffer); //±àÂë¶ÔÕÕ if (CompareCodes(m_pPointFeatureBuffer)) { PutExtendAttribsValue(m_pPointFeatureBuffer, pEnt->xData()); hr = m_pPointFeatureCursor->InsertFeature(m_pPointFeatureBuffer, &OID); if (FAILED(hr)) { sInfoText = "Point¶ÔÏóдÈëµ½PGDBʧ°Ü." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } } else { sInfoText = "Point¶ÔÏó×ø±ê²»ÕýÈ·." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } if (strcmp(pEnt->isA()->name(), "AcDbBlockReference") == 0) m_lBlockNum++; } else if (shapeType == esriGeometryPolyline) //Ïß { hr = m_pLineFeatureBuffer->putref_Shape(pShape); if (SUCCEEDED(hr)) { AddBaseAttributes(pEnt, "Line", m_pLineFeatureBuffer); CString sDwgLayer; sDwgLayer.Format("%s", pEnt->layer().c_str()); if (CompareCodes(m_pLineFeatureBuffer)) { PutExtendAttribsValue(m_pLineFeatureBuffer, pEnt->xData()); hr = m_pLineFeatureCursor->InsertFeature(m_pLineFeatureBuffer, &OID); if (FAILED(hr)) { IFieldsPtr pFlds; m_pLineFeatureBuffer->get_Fields(&pFlds); long numFields; pFlds->get_FieldCount(&numFields); for (int t = 0; t < numFields; t++) { CComVariant tVal; IFieldPtr pFld; pFlds->get_Field(t, &pFld); CComBSTR bsName; pFld->get_Name(&bsName); m_pLineFeatureBuffer->get_Value(t, &tVal); } sInfoText = "Line¶ÔÏóдÈëµ½PGDBʧ°Ü." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } } else { sInfoText = "Line¶ÔÏó×ø±ê²»ÕýÈ·." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } // Èç¹û±ÕºÏ¾ÍÔÙÉú³ÉÃæ VARIANT_BOOL isclosed; IPolylinePtr pPolyline(CLSID_Polyline); pPolyline = pShape; pPolyline->get_IsClosed(&isclosed); if (isclosed && m_IsLine2Polygon) { IPolygonPtr pPolygon(CLSID_Polygon); ((ISegmentCollectionPtr) pPolygon)->AddSegmentCollection((ISegmentCollectionPtr) pPolyline); IAreaPtr pArea = (IAreaPtr)pPolygon; double dArea = 0.0; pArea->get_Area(&dArea); if (dArea < 0.0) { pPolygon->ReverseOrientation(); } hr = m_pPolygonFeatureBuffer->putref_Shape((IGeometryPtr)pPolygon); if (SUCCEEDED(hr)) { AddBaseAttributes(pEnt, "Polygon", m_pPolygonFeatureBuffer); //±àÂë¶ÔÕÕ if (CompareCodes(m_pPolygonFeatureBuffer)) { //¹Ò½ÓÀ©Õ¹ÊôÐÔ PutExtendAttribsValue(m_pPolygonFeatureBuffer, pEnt->xData()); hr = m_pPolygonFeatureCursor->InsertFeature(m_pPolygonFeatureBuffer, &OID); if (FAILED(hr)) { sInfoText = "Polygon¶ÔÏóдÈëµ½PGDBʧ°Ü." + CatchErrorInfo(); WriteLog(sInfoText); } } } else { sInfoText = "Polyline¶ÔÏó×ø±ê²»ÕýÈ·." + CatchErrorInfo(); WriteLog(sInfoText); } } } else if (shapeType == esriGeometryPolygon) //Ãæ¡¢Ìî³ä { if(m_IsReadPolygon) { IPolygonPtr pPolygon(CLSID_Polygon); pPolygon = pShape; IAreaPtr pArea = (IAreaPtr)pPolygon; double dArea = 0.0; pArea->get_Area(&dArea); if (dArea < 0.0) { pPolygon->ReverseOrientation(); } hr = m_pPolygonFeatureBuffer->putref_Shape((IGeometryPtr)pPolygon); if (SUCCEEDED(hr)) { AddBaseAttributes(pEnt, "Polygon", m_pPolygonFeatureBuffer); PutExtendAttribsValue(m_pPolygonFeatureBuffer, pEnt->xData()); hr = m_pPolygonFeatureCursor->InsertFeature(m_pPolygonFeatureBuffer, &OID); if (FAILED(hr)) { sInfoText = "Polygon¶ÔÏóдÈëµ½PGDBʧ°Ü." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } else { sInfoText = "Polygon¶ÔÏó×ø±ê²»ÕýÈ·." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } } else { sInfoText.Format("%sͼ²ãÖÐHandleֵΪ:%s µÄÒªËØÎÞ·¨´¦Àí.", pEnt->layer().c_str(), szEntityHandle); WriteLog(sInfoText); //ÎÞ·¨Ê¶±ð¼ÆÊý¼Ó1 m_lUnReadEntityNum++; } } //¶ÁÈ¡À©Õ¹ÊôÐÔµ½À©Õ¹ÊôÐÔ±í ReadExtendAttribs(pEnt->xData(), szEntityHandle); } } //¶ÁCADÎļþ void XDWGReader::ReadBlock(OdDbDatabase* pDb) { // Open ModelSpace OdDbBlockTableRecordPtr pBlock = pDb->getModelSpaceId().safeOpenObject(); // ³õʼ»¯ m_lBlockNum = 0; m_bn = -1; m_lEntityNum = 0; //ÎÞ·¨¶ÁÈ¡µÄʵÌå¸öÊý m_lUnReadEntityNum = 0; m_vID = 0; if (m_StepNum < 0) m_StepNum = 5000; // Get an entity iterator OdDbObjectIteratorPtr pEntIter = pBlock->newIterator(); for (; !pEntIter->done(); pEntIter->step()) { m_lEntityNum++; } //É趨½ø¶ÈÌõ·¶Î§ if (m_pProgressBar) { m_pProgressBar->SetRange(0, m_lEntityNum); m_pProgressBar->SetPos(0); } pEntIter.release(); // For each entity in the block pEntIter = pBlock->newIterator(); int iReadCount = 0; for (; !pEntIter->done(); pEntIter->step()) { try { ReadEntity(pEntIter->objectId()); } catch (...) { char szEntityHandle[50] = {0}; pEntIter->objectId().getHandle().getIntoAsciiBuffer(szEntityHandle); CString sErr; sErr.Format("¶ÁÈ¡HandleΪ%sµÄʵÌå³öÏÖÒì³£.", szEntityHandle); WriteLog(sErr); } //É趨½ø¶ÈÌõ²½³¤ if (m_pProgressBar) { m_pProgressBar->StepIt(); } if (++iReadCount % m_StepNum == 0) { if (m_pPointFeatureCursor) m_pPointFeatureCursor->Flush(); if (m_pTextFeatureCursor) m_pTextFeatureCursor->Flush(); if (m_pLineFeatureCursor) m_pLineFeatureCursor->Flush(); if (m_pAnnoFeatureCursor) m_pAnnoFeatureCursor->Flush(); if (m_pPolygonFeatureCursor) m_pPolygonFeatureCursor->Flush(); if (m_pExtentTableRowCursor) m_pExtentTableRowCursor->Flush(); } } if (m_pPointFeatureCursor) m_pPointFeatureCursor->Flush(); if (m_pTextFeatureCursor) m_pTextFeatureCursor->Flush(); if (m_pLineFeatureCursor) m_pLineFeatureCursor->Flush(); if (m_pAnnoFeatureCursor) m_pAnnoFeatureCursor->Flush(); if (m_pPolygonFeatureCursor) m_pPolygonFeatureCursor->Flush(); if (m_pExtentTableRowCursor) m_pExtentTableRowCursor->Flush(); pEntIter.release(); CString sResult; sResult.Format("´¦ÀíÒªËØ×ÜÊý:%d", m_lEntityNum - m_lUnReadEntityNum); WriteLog(sResult); } // arcgis Ïà¹Øº¯Êý HRESULT XDWGReader::AddBaseAttributes(OdDbEntity* pEnt, LPCTSTR strEnType, IFeatureBuffer*& pFeatureBuffer) { long lindex; int ival ; CString strval; IFieldsPtr ipFields; char buff[20]; OdDbHandle hTmp; hTmp = pEnt->getDbHandle(); hTmp.getIntoAsciiBuffer(buff); if (pFeatureBuffer == NULL) return S_FALSE; pFeatureBuffer->get_Fields(&ipFields); //µÃµ½esri¼¸ºÎÀàÐÍ CComBSTR bsStr; CComVariant vtVal; bsStr = g_szEntityType; ipFields->FindField(bsStr, &lindex); vtVal = strEnType; pFeatureBuffer->put_Value(lindex, vtVal); //µÃµ½dwg¼¸ºÎÀàÐÍ bsStr = "DwgGeometry"; ipFields->FindField(bsStr, &lindex); vtVal = pEnt->isA()->name(); pFeatureBuffer->put_Value(lindex, vtVal); // µÃµ½dwgʵÌå±àºÅ bsStr = "Handle"; ipFields->FindField(bsStr, &lindex); vtVal = buff; pFeatureBuffer->put_Value(lindex, vtVal); // µÃµ½dwgͼÃû£¬¼´dwgÎļþÃû¡£ÒÔÈ·±£handleΨһ bsStr = "BaseName"; ipFields->FindField(bsStr, &lindex); vtVal = m_strDwgName; pFeatureBuffer->put_Value(lindex, vtVal); // µÃµ½dwg²ãÃû bsStr = "Layer"; ipFields->FindField(bsStr, &lindex); strval.Format("%s", pEnt->layer().c_str()); strval.MakeUpper(); vtVal = strval; pFeatureBuffer->put_Value(lindex, vtVal); // TRACE("Put Layer(AddBaseAttributes): "+ strval+" \r\n"); // µÃµ½dwg·ûºÅÑÕÉ«,Ö»Äܵõ½²ãµÄÑÕÉ«£¬Ó¦¸ÃÊÇÿ¸öÒªËØµÄ bsStr = "Color"; ipFields->FindField(bsStr, &lindex); if (pEnt->colorIndex() > 255 || pEnt->colorIndex() < 1) { OdDbLayerTableRecordPtr pLayer = pEnt->layerId().safeOpenObject(); ival = pLayer->colorIndex(); } else ival = pEnt->colorIndex(); vtVal = ival; pFeatureBuffer->put_Value(lindex, vtVal); // µÃµ½ Linetype £¬¼Ç¼ÏßÐÍ bsStr = "Linetype"; ipFields->FindField(bsStr, &lindex); strval.Format("%s", pEnt->linetype().c_str()); strval.MakeUpper(); vtVal = strval; pFeatureBuffer->put_Value(lindex, vtVal); //¶ÔÏó¿É¼ûÐÔ£¨¿ÉÑ¡£©£º0 = ¿É¼û£»1 = ²»¿É¼û // kInvisible 1 kVisible 0 bsStr = "Visible"; ipFields->FindField(bsStr, &lindex); if (pEnt->visibility() == 1) { ival = 0; } else { ival = 1; } vtVal = ival; pFeatureBuffer->put_Value(lindex, vtVal); //À©Õ¹ÊôÐÔFeatureUID //bsStr = "FEATURE_UID"; //ipFields->FindField(bsStr, &lindex); //if (lindex != -1) //{ // CString sFeatureUID = ReadFeatureUID(pEnt->xData()); // vtVal = sFeatureUID; // pFeatureBuffer->put_Value(lindex, vtVal); //} vtVal.Clear(); bsStr.Empty(); return 0; } void XDWGReader::AddAttributes(LPCTSTR csFieldName, LPCTSTR csFieldValue, IFeatureBuffer*& pFeatureBuffer) { try { long lindex; IFieldsPtr ipFields; CString strval; if (pFeatureBuffer == NULL) return; pFeatureBuffer->get_Fields(&ipFields); CComBSTR bsStr = csFieldName; ipFields->FindField(bsStr, &lindex); if (lindex != -1) { CComVariant vtVal; //°Ñ»¡¶Èֵת»»Îª½Ç¶ÈÖµ if (m_bConvertAngle && (strcmp("Angle", csFieldName) == 0)) { double dRadian = atof(csFieldValue); double dAngle = dRadian * g_dAngleParam; vtVal = dAngle; } else { vtVal = csFieldValue; } HRESULT hr = pFeatureBuffer->put_Value(lindex, vtVal); vtVal.Clear(); } bsStr.Empty(); } catch (...) { CString sError; sError.Format("%s×Ö¶ÎдÈë%sֵʱ³ö´í.", csFieldName, csFieldValue); WriteLog(sError); } } void XDWGReader::CleanAllFeatureBuffers() { if (m_pAnnoFeatureBuffer) CleanFeatureBuffer(m_pAnnoFeatureBuffer); if (m_pTextFeatureBuffer) CleanFeatureBuffer(m_pTextFeatureBuffer); if (m_pLineFeatureBuffer) CleanFeatureBuffer(m_pLineFeatureBuffer); if (m_pPointFeatureBuffer) CleanFeatureBuffer(m_pPointFeatureBuffer); if (m_pPolygonFeatureBuffer) CleanFeatureBuffer(m_pPolygonFeatureBuffer); } //void XDWGReader::BlockIniAttributes() //{ // if (m_pTextFeatureBuffer) // IniBlockAttributes(m_pTextFeatureBuffer); // if (m_pLineFeatureBuffer) // IniBlockAttributes(m_pLineFeatureBuffer); // if (m_pPointFeatureBuffer) // IniBlockAttributes(m_pPointFeatureBuffer); // if (m_pPolygonFeatureBuffer) // IniBlockAttributes(m_pPolygonFeatureBuffer); //} ////////////////////////////////////////////////////////////////////////// //ÕÒ³ö²¢½â¾öÄÚ´æÐ¹Â©ÎÊÌâ by zl void XDWGReader::CleanFeatureBuffer(IFeatureBuffer* pFeatureBuffer) { if (pFeatureBuffer == NULL) return; //ÊÍ·ÅÄÚ´æ IGeometryPtr pShape; HRESULT hr = pFeatureBuffer->get_Shape(&pShape); if (SUCCEEDED(hr)) { if (pShape != NULL) { pShape->SetEmpty(); } } IFieldsPtr ipFields; long iFieldCount; VARIANT_BOOL isEditable; esriFieldType fieldType; VARIANT emptyVal; ::VariantInit(&emptyVal); CComVariant emptyStr = ""; pFeatureBuffer->get_Fields(&ipFields); ipFields->get_FieldCount(&iFieldCount); for (int i = 0; i < iFieldCount; i++) { IFieldPtr pFld; ipFields->get_Field(i, &pFld); pFld->get_Editable(&isEditable); pFld->get_Type(&fieldType); if (isEditable == VARIANT_TRUE && fieldType != esriFieldTypeGeometry) { if (fieldType == esriFieldTypeString) { pFeatureBuffer->put_Value(i, emptyStr); } else { pFeatureBuffer->put_Value(i, emptyVal); } } } } //void XDWGReader::IniBlockAttributes(IFeatureBuffer* pFeatureBuffer) //{ // long lindex; // // double dbval; // CString strval; // IFieldsPtr ipFields; // if (pFeatureBuffer == NULL) // return; // // //ÊÍ·ÅÄÚ´æ // IGeometry* pShape; // HRESULT hr = pFeatureBuffer->get_Shape(&pShape); // if (SUCCEEDED(hr)) // { // if (pShape != NULL) // { // pShape->SetEmpty(); // } // } // // // Çå¿Õ£¬·ñÔò»á±£Áôǰһ¸öµÄÊôÐÔ // pFeatureBuffer->get_Fields(&ipFields); // CComBSTR bsStr; // CComVariant vtVal; // bsStr = "Thickness"; // ipFields->FindField(bsStr, &lindex); // if (lindex != -1) // { // vtVal = 0; // pFeatureBuffer->put_Value(lindex, vtVal); // } // // bsStr = "Scale"; // ipFields->FindField(bsStr, &lindex); // if (lindex != -1) // { // vtVal = 0; // pFeatureBuffer->put_Value(lindex, vtVal); // } // // bsStr = "Angle"; // ipFields->FindField(bsStr, &lindex); // if (lindex != -1) // { // vtVal = 0; // pFeatureBuffer->put_Value(lindex, vtVal); // } // // bsStr = "Elevation"; // ipFields->FindField(bsStr, &lindex); // if (lindex != -1) // { // vtVal = 0; // pFeatureBuffer->put_Value(lindex, vtVal); // } // // bsStr = "Width"; // ipFields->FindField(bsStr, &lindex); // if (lindex != -1) // { // vtVal = 0; // pFeatureBuffer->put_Value(lindex, vtVal); // } // // bsStr.Empty(); // // //IniExtraAttributes(pFeatureBuffer, ipFields); // // return; //} //void XDWGReader::OpenLogFile() //{ // //if (m_pLogRec != NULL) // //{ // // WinExec("Notepad.exe " + m_sLogFilePath, SW_SHOW); // //} // // //if (m_LogList.GetCount() > 0) // //{ // // COleDateTime dtCur = COleDateTime::GetCurrentTime(); // // CString sName = dtCur.Format("%y%m%d_%H%M%S"); // // CString sLogFileName; // // sLogFileName.Format("%sDwgת»»ÈÕÖ¾_%s.log", GetLogPath(), sName); // // // CStdioFile f3(sLogFileName, CFile::modeCreate | CFile::modeWrite | CFile::typeText); // // for (POSITION pos = m_LogList.GetHeadPosition(); pos != NULL;) // // { // // f3.WriteString(m_LogList.GetNext(pos) + "\n"); // // } // // f3.Close(); // // WinExec("Notepad.exe " + sLogFileName, SW_SHOW); // // m_LogList.RemoveAll(); // //} //} CString XDWGReader::CatchErrorInfo() { IErrorInfoPtr ipError; CComBSTR bsStr; CString sError; ::GetErrorInfo(0, &ipError); if (ipError) { ipError->GetDescription(&bsStr); sError = bsStr; } CString sRetErr; sRetErr.Format("¶ÁÈ¡HandleֵΪ:%s µÄ¶ÔÏóʱ³ö´í.´íÎóÔ­Òò:%s", m_sEntityHandle, sError); return sRetErr; } HRESULT XDWGReader::CreateDwgPointFields(ISpatialReference* ipSRef, IFields** ppfields) { IFieldsPtr ipFields; ipFields.CreateInstance(CLSID_Fields); IFieldsEditPtr ipFieldsEdit(ipFields); IFieldPtr ipField; ipField.CreateInstance(CLSID_Field); IFieldEditPtr ipFieldEdit(ipField); // create the geometry field IGeometryDefPtr ipGeomDef(CLSID_GeometryDef); IGeometryDefEditPtr ipGeomDefEdit(ipGeomDef); // assign the geometry definiton properties. ipGeomDefEdit->put_GeometryType(esriGeometryPoint); ipGeomDefEdit->put_GridCount(1); //double dGridSize = 1000; //VARIANT_BOOL bhasXY; //ipSRef->HasXYPrecision(&bhasXY); //if (bhasXY) //{ // double xmin, ymin, xmax, ymax, dArea; // ipSRef->GetDomain(&xmin, &xmax, &ymin, &ymax); // dArea = (xmax - xmin) * (ymax - ymin); // dGridSize = sqrt(dArea / 100); //} //if (dGridSize <= 0) // dGridSize = 1000; ipGeomDefEdit->put_GridSize(0, DEFAULT_GIS_GRID_SIZE); ipGeomDefEdit->put_AvgNumPoints(2); ipGeomDefEdit->put_HasM(VARIANT_FALSE); ipGeomDefEdit->put_HasZ(VARIANT_FALSE); ipGeomDefEdit->putref_SpatialReference(ipSRef); ipFieldEdit->put_Name(CComBSTR(L"SHAPE")); ipFieldEdit->put_AliasName(CComBSTR(L"SHAPE")); ipFieldEdit->put_Type(esriFieldTypeGeometry); ipFieldEdit->putref_GeometryDef(ipGeomDef); ipFieldsEdit->AddField(ipField); // create the object id field ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"OBJECTID")); ipFieldEdit->put_AliasName(CComBSTR(L"OBJECT ID")); ipFieldEdit->put_Type(esriFieldTypeOID); ipFieldsEdit->AddField(ipField); // ´´½¨ Entity £¬¼Ç¼esriʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(g_szEntityType)); ipFieldEdit->put_AliasName(CComBSTR(g_szEntityType)); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ DwgGeometry £¬¼Ç¼DWGʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_AliasName(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ Handle £¬¼Ç¼DWGʵÌå±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Handle")); ipFieldEdit->put_AliasName(CComBSTR(L"Handle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ BaseName £¬¼Ç¼DWGʵÌå²ãÃû¼´DWGÎļþÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"BaseName")); ipFieldEdit->put_AliasName(CComBSTR(L"BaseName")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Layer £¬¼Ç¼DWGʵÌå²ãÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Layer")); ipFieldEdit->put_AliasName(CComBSTR(L"Layer")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Color £¬¼Ç¼DWGʵÌå·ûºÅÑÕÉ« ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Color")); ipFieldEdit->put_AliasName(CComBSTR(L"Color")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Linetype £¬¼Ç¼ÏßÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Linetype")); ipFieldEdit->put_AliasName(CComBSTR(L"Linetype")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Thickness £¬¼Ç¼DWGʵÌåºñ¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Thickness")); ipFieldEdit->put_AliasName(CComBSTR(L"Thickness")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Scale £¬¼Ç¼DWGʵÌå·ûºÅ±ÈÀý´óС ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Scale")); ipFieldEdit->put_AliasName(CComBSTR(L"Scale")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Elevation £¬¼Ç¼DWGʵÌå¸ß³ÌÖµ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Elevation")); ipFieldEdit->put_AliasName(CComBSTR(L"Elevation")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Blockname £¬¼Ç¼BlockÃû×Ö ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blockname")); ipFieldEdit->put_AliasName(CComBSTR(L"Blockname")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Blocknumber £¬¼Ç¼ÿ¸öBlock±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blocknumber")); ipFieldEdit->put_AliasName(CComBSTR(L"Blocknumber")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Angle £¬¼Ç¼DWGʵÌåÐýת½Ç¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Angle")); ipFieldEdit->put_AliasName(CComBSTR(L"Angle")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Visible £¬¼Ç¼DWGʵÌåÊÇ·ñ¿É¼û£¬0²»¿É¼û£¬1¿É¼û ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Visible")); ipFieldEdit->put_AliasName(CComBSTR(L"Visible")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); *ppfields = ipFields.Detach(); return 0; } HRESULT XDWGReader::CreateDwgLineFields(ISpatialReference* ipSRef, IFields** ppfields) { IFieldsPtr ipFields; ipFields.CreateInstance(CLSID_Fields); IFieldsEditPtr ipFieldsEdit(ipFields); IFieldPtr ipField; ipField.CreateInstance(CLSID_Field); IFieldEditPtr ipFieldEdit(ipField); // create the geometry field IGeometryDefPtr ipGeomDef(CLSID_GeometryDef); IGeometryDefEditPtr ipGeomDefEdit(ipGeomDef); // assign the geometry definiton properties. ipGeomDefEdit->put_GeometryType(esriGeometryPolyline); ipGeomDefEdit->put_GridCount(1); //double dGridSize = 1000; //VARIANT_BOOL bhasXY; //ipSRef->HasXYPrecision(&bhasXY); //if (bhasXY) //{ // double xmin, ymin, xmax, ymax, dArea; // ipSRef->GetDomain(&xmin, &xmax, &ymin, &ymax); // dArea = (xmax - xmin) * (ymax - ymin); // dGridSize = sqrt(dArea / 100); //} //if (dGridSize <= 0) // dGridSize = 1000; ipGeomDefEdit->put_GridSize(0, DEFAULT_GIS_GRID_SIZE); ipGeomDefEdit->put_AvgNumPoints(2); ipGeomDefEdit->put_HasM(VARIANT_FALSE); ipGeomDefEdit->put_HasZ(VARIANT_FALSE); ipGeomDefEdit->putref_SpatialReference(ipSRef); ipFieldEdit->put_Name(CComBSTR(L"SHAPE")); ipFieldEdit->put_AliasName(CComBSTR(L"SHAPE")); ipFieldEdit->put_Type(esriFieldTypeGeometry); ipFieldEdit->putref_GeometryDef(ipGeomDef); ipFieldsEdit->AddField(ipField); // create the object id field ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"OBJECTID")); ipFieldEdit->put_AliasName(CComBSTR(L"OBJECT ID")); ipFieldEdit->put_Type(esriFieldTypeOID); ipFieldsEdit->AddField(ipField); // ´´½¨ Entity £¬¼Ç¼esriʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(g_szEntityType)); ipFieldEdit->put_AliasName(CComBSTR(g_szEntityType)); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ DwgGeometry £¬¼Ç¼DWGʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_AliasName(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ Handle £¬¼Ç¼DWGʵÌå±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Handle")); ipFieldEdit->put_AliasName(CComBSTR(L"Handle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ BaseName £¬¼Ç¼DWGʵÌå²ãÃû¼´DWGÎļþÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"BaseName")); ipFieldEdit->put_AliasName(CComBSTR(L"BaseName")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Layer £¬¼Ç¼DWGʵÌå²ãÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Layer")); ipFieldEdit->put_AliasName(CComBSTR(L"Layer")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Color £¬¼Ç¼DWGÏßʵÌåÑÕÉ« ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Color")); ipFieldEdit->put_AliasName(CComBSTR(L"Color")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Linetype £¬¼Ç¼DWGÏßʵÌåÏßÐÍÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Linetype")); ipFieldEdit->put_AliasName(CComBSTR(L"Linetype")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Elevation £¬¼Ç¼DWGʵÌå¸ß³ÌÖµ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Elevation")); ipFieldEdit->put_AliasName(CComBSTR(L"Elevation")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Thickness £¬¼Ç¼DWGʵÌåºñ¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Thickness")); ipFieldEdit->put_AliasName(CComBSTR(L"Thickness")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Width £¬¼Ç¼DWGʵÌåÏß¿í ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Width")); ipFieldEdit->put_AliasName(CComBSTR(L"Width")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Blockname £¬¼Ç¼BlockÃû×Ö ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blockname")); ipFieldEdit->put_AliasName(CComBSTR(L"Blockname")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Blocknumber £¬¼Ç¼ÿ¸öBlock±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blocknumber")); ipFieldEdit->put_AliasName(CComBSTR(L"Blocknumber")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Visible £¬¼Ç¼DWGʵÌåÊÇ·ñ¿É¼û£¬0²»¿É¼û£¬1¿É¼û ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Visible")); ipFieldEdit->put_AliasName(CComBSTR(L"Visible")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); *ppfields = ipFields.Detach(); return 0; } HRESULT XDWGReader::CreateDwgPolygonFields(ISpatialReference* ipSRef, IFields** ppfields) { IFieldsPtr ipFields; ipFields.CreateInstance(CLSID_Fields); IFieldsEditPtr ipFieldsEdit(ipFields); IFieldPtr ipField; ipField.CreateInstance(CLSID_Field); IFieldEditPtr ipFieldEdit(ipField); ipFieldEdit->put_Name(CComBSTR(L"SHAPE")); ipFieldEdit->put_Type(esriFieldTypeGeometry); // create the geometry field IGeometryDefPtr ipGeomDef(CLSID_GeometryDef); IGeometryDefEditPtr ipGeomDefEdit; ipGeomDefEdit = ipGeomDef; // assign the geometry definiton properties. ipGeomDefEdit->put_GeometryType(esriGeometryPolygon); ipGeomDefEdit->put_GridCount(1); ipGeomDefEdit->put_AvgNumPoints(2); ipGeomDefEdit->put_HasM(VARIANT_FALSE); ipGeomDefEdit->put_HasZ(VARIANT_FALSE); //double dGridSize = 1000; //VARIANT_BOOL bhasXY; //ipSRef->HasXYPrecision(&bhasXY); //if (bhasXY) //{ // double xmin, ymin, xmax, ymax, dArea; // ipSRef->GetDomain(&xmin, &xmax, &ymin, &ymax); // dArea = (xmax - xmin) * (ymax - ymin); // dGridSize = sqrt(dArea / 100); //} //if (dGridSize <= 0) // dGridSize = 1000; ipGeomDefEdit->put_GridSize(0, DEFAULT_GIS_GRID_SIZE); ipGeomDefEdit->putref_SpatialReference(ipSRef); ipFieldEdit->putref_GeometryDef(ipGeomDef); ipFieldsEdit->AddField(ipField); // create the object id field ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"OBJECTID")); ipFieldEdit->put_AliasName(CComBSTR(L"OBJECT ID")); ipFieldEdit->put_Type(esriFieldTypeOID); ipFieldsEdit->AddField(ipField); // ´´½¨ Entity £¬¼Ç¼esriʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(g_szEntityType)); ipFieldEdit->put_AliasName(CComBSTR(g_szEntityType)); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ DwgGeometry £¬¼Ç¼DWGʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_AliasName(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ Handle £¬¼Ç¼DWGʵÌå±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Handle")); ipFieldEdit->put_AliasName(CComBSTR(L"Handle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ BaseName £¬¼Ç¼DWGʵÌå²ãÃû¼´DWGÎļþÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"BaseName")); ipFieldEdit->put_AliasName(CComBSTR(L"BaseName")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Layer £¬¼Ç¼DWGʵÌå²ãÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Layer")); ipFieldEdit->put_AliasName(CComBSTR(L"Layer")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Color £¬¼Ç¼DWGÏßʵÌåÑÕÉ« ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Color")); ipFieldEdit->put_AliasName(CComBSTR(L"Color")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Linetype £¬¼Ç¼DWGÏßʵÌåÏßÐÍÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Linetype")); ipFieldEdit->put_AliasName(CComBSTR(L"Linetype")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Elevation £¬¼Ç¼DWGʵÌå¸ß³ÌÖµ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Elevation")); ipFieldEdit->put_AliasName(CComBSTR(L"Elevation")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Thickness £¬¼Ç¼DWGʵÌåºñ¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Thickness")); ipFieldEdit->put_AliasName(CComBSTR(L"Thickness")); //ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Width £¬¼Ç¼DWGʵÌåÏß¿í ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Width")); ipFieldEdit->put_AliasName(CComBSTR(L"Width")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Blockname £¬¼Ç¼BlockÃû×Ö ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blockname")); ipFieldEdit->put_AliasName(CComBSTR(L"Blockname")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Blocknumber £¬¼Ç¼ÿ¸öBlock±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blocknumber")); ipFieldEdit->put_AliasName(CComBSTR(L"Blocknumber")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Visible £¬¼Ç¼DWGʵÌåÊÇ·ñ¿É¼û£¬0²»¿É¼û£¬1¿É¼û ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Visible")); ipFieldEdit->put_AliasName(CComBSTR(L"Visible")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); *ppfields = ipFields.Detach(); return 0; } HRESULT XDWGReader::CreateDwgTextPointFields(ISpatialReference* ipSRef, IFields** ppfields) { IFieldsPtr ipFields; ipFields.CreateInstance(CLSID_Fields); IFieldsEditPtr ipFieldsEdit(ipFields); IFieldPtr ipField; ipField.CreateInstance(CLSID_Field); IFieldEditPtr ipFieldEdit(ipField); // create the geometry field IGeometryDefPtr ipGeomDef(CLSID_GeometryDef); IGeometryDefEditPtr ipGeomDefEdit(ipGeomDef); // assign the geometry definiton properties. ipGeomDefEdit->put_GeometryType(esriGeometryPoint); ipGeomDefEdit->put_GridCount(1); //double dGridSize = 1000; //VARIANT_BOOL bhasXY; //ipSRef->HasXYPrecision(&bhasXY); //if (bhasXY) //{ // double xmin, ymin, xmax, ymax, dArea; // ipSRef->GetDomain(&xmin, &xmax, &ymin, &ymax); // dArea = (xmax - xmin) * (ymax - ymin); // dGridSize = sqrt(dArea / 100); //} //if (dGridSize <= 0) // dGridSize = 1000; ipGeomDefEdit->put_GridSize(0, DEFAULT_GIS_GRID_SIZE); ipGeomDefEdit->put_AvgNumPoints(2); ipGeomDefEdit->put_HasM(VARIANT_FALSE); ipGeomDefEdit->put_HasZ(VARIANT_FALSE); ipGeomDefEdit->putref_SpatialReference(ipSRef); ipFieldEdit->put_Name(CComBSTR(L"SHAPE")); ipFieldEdit->put_AliasName(CComBSTR(L"SHAPE")); ipFieldEdit->put_Type(esriFieldTypeGeometry); ipFieldEdit->putref_GeometryDef(ipGeomDef); ipFieldsEdit->AddField(ipField); // create the object id field ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"OBJECTID")); ipFieldEdit->put_AliasName(CComBSTR(L"OBJECT ID")); ipFieldEdit->put_Type(esriFieldTypeOID); ipFieldsEdit->AddField(ipField); // ´´½¨ Entity £¬¼Ç¼esriʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(g_szEntityType)); ipFieldEdit->put_AliasName(CComBSTR(g_szEntityType)); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ DwgGeometry £¬¼Ç¼DWGʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_AliasName(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ Handle £¬¼Ç¼DWGʵÌå±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Handle")); ipFieldEdit->put_AliasName(CComBSTR(L"Handle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ BaseName £¬¼Ç¼DWGʵÌå²ãÃû¼´DWGÎļþÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"BaseName")); ipFieldEdit->put_AliasName(CComBSTR(L"BaseName")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Layer £¬¼Ç¼DWGʵÌå²ãÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Layer")); ipFieldEdit->put_AliasName(CComBSTR(L"Layer")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Color £¬¼Ç¼DWGÏßʵÌåÑÕÉ« ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Color")); ipFieldEdit->put_AliasName(CComBSTR(L"Color")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Linetype £¬¼Ç¼DWGÏßʵÌåÏßÐÍÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Linetype")); ipFieldEdit->put_AliasName(CComBSTR(L"Linetype")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Thickness £¬¼Ç¼DWGʵÌåºñ¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Thickness")); ipFieldEdit->put_AliasName(CComBSTR(L"Thickness")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Blockname £¬¼Ç¼BlockÃû×Ö ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blockname")); ipFieldEdit->put_AliasName(CComBSTR(L"Blockname")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Blocknumber £¬¼Ç¼ÿ¸öBlock±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blocknumber")); ipFieldEdit->put_AliasName(CComBSTR(L"Blocknumber")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Angle £¬¼Ç¼DWGÎÄ×ÖʵÌåÐýת½Ç¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Angle")); ipFieldEdit->put_AliasName(CComBSTR(L"Angle")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ TextString £¬¼Ç¼ DWGÎÄ×ÖʵÌå×ÖÄÚÈÝ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"TextString")); ipFieldEdit->put_AliasName(CComBSTR(L"TextString")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(255); ipFieldsEdit->AddField(ipField); // ´´½¨ Height £¬¼Ç¼DWGÎÄ×ÖʵÌå×Ö¸ß ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Height")); ipFieldEdit->put_AliasName(CComBSTR(L"Height")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ WidthFactor £¬ // is an additional scaling applied in the x direction which makes the text either fatter or thinner. ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"WidthFactor")); ipFieldEdit->put_AliasName(CComBSTR(L"WidthFactor")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Oblique £¬Çãб½Ç¶È // is an obliquing angle to be applied to the text, which causes it to "lean" either to the right or left. ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Oblique")); ipFieldEdit->put_AliasName(CComBSTR(L"Oblique")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ VerticalMode £¬¼Ç¼DWGÎÄ×ÖʵÌå×Ö¶ÔÆë·½Ê½ // kTextBase 0 kTextBottom 1 kTextVertMid 2 kTextTop 3 ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"VtMode")); ipFieldEdit->put_AliasName(CComBSTR(L"VtMode")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ HorizontalMode £¬¼Ç¼DWGÎÄ×ÖʵÌå×Ö¶ÔÆë·½Ê½ //kTextLeft 0 kTextCenter 1 kTextRight 2 kTextAlign 3 // kTextMid 4 kTextFit 5 ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"HzMode")); ipFieldEdit->put_AliasName(CComBSTR(L"HzMode")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ AlignmentPointX ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"AlignPtX")); ipFieldEdit->put_AliasName(CComBSTR(L"AlignPtX")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ AlignmentPointY ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"AlignPtY")); ipFieldEdit->put_AliasName(CComBSTR(L"AlignPtY")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ BoundingPointMinX ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"PtMinX")); ipFieldEdit->put_AliasName(CComBSTR(L"PtMinX")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ BoundingPointMinY ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"PtMinY")); ipFieldEdit->put_AliasName(CComBSTR(L"PtMinY")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ BoundingPointMaxX ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"PtMaxX")); ipFieldEdit->put_AliasName(CComBSTR(L"PtMaxX")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ BoundingPointMaxY ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"PtMaxY")); ipFieldEdit->put_AliasName(CComBSTR(L"PtMaxY")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ BigFontname £¬¼Ç¼ DWGÎÄ×ÖʵÌå×ÖÌå ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"BigFontname")); ipFieldEdit->put_AliasName(CComBSTR(L"BigFontname")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ ShapeFilename £¬¼Ç¼ DWGÎÄ×ÖʵÌå×ÖÌå ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"ShapeFilename")); ipFieldEdit->put_AliasName(CComBSTR(L"ShapeFilename")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ ShapeName £¬¼Ç¼ DWGÎÄ×ÖʵÌå×ÖÌå ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"ShapeName")); ipFieldEdit->put_AliasName(CComBSTR(L"ShapeName")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Visible £¬¼Ç¼DWGʵÌåÊÇ·ñ¿É¼û£¬0²»¿É¼û£¬1¿É¼û ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Visible")); ipFieldEdit->put_AliasName(CComBSTR(L"Visible")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); *ppfields = ipFields.Detach(); return 0; } ////////////////////////////////////////////////////////////////////////// //¼òÒªÃèÊö : ´´½¨×¢¼Çͼ²ã×Ö¶Î //ÊäÈë²ÎÊý : //·µ »Ø Öµ : //ÐÞ¸ÄÈÕÖ¾ : ////////////////////////////////////////////////////////////////////////// HRESULT XDWGReader::CreateDwgAnnotationFields(ISpatialReference* ipSRef, IFields** ppfields) { HRESULT hr; IObjectClassDescriptionPtr pOCDesc(CLSID_AnnotationFeatureClassDescription); IFieldsPtr pReqFields; pOCDesc->get_RequiredFields(&pReqFields); //ÉèÖÿռä²Î¿¼ if (ipSRef != NULL) { long numFields; pReqFields->get_FieldCount(&numFields); for (int i = 0; i < numFields; i++) { IFieldPtr pField; pReqFields->get_Field(i, &pField); esriFieldType fldType; pField->get_Type(&fldType); if (fldType == esriFieldTypeGeometry) { IFieldEditPtr pEdtField = pField; IGeometryDefPtr pGeoDef; hr = pEdtField->get_GeometryDef(&pGeoDef); IGeometryDefEditPtr pEdtGeoDef = pGeoDef; hr = pEdtGeoDef->putref_SpatialReference(ipSRef); hr = pEdtField->putref_GeometryDef(pGeoDef); break; } } } IFieldsEditPtr ipFieldsEdit = pReqFields; //´´½¨CADÎļþÖÐ×¢¼Çͼ²ã×Ö¶Î IFieldEditPtr ipFieldEdit; IFieldPtr ipField; // ´´½¨ Entity £¬¼Ç¼esriʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR("Entity_Type")); ipFieldEdit->put_AliasName(CComBSTR("Entity_Type")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ Handle £¬¼Ç¼DWGʵÌå±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Handle")); ipFieldEdit->put_AliasName(CComBSTR(L"Handle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ BaseName £¬¼Ç¼DWGʵÌå²ãÃû¼´DWGÎļþÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"BaseName")); ipFieldEdit->put_AliasName(CComBSTR(L"BaseName")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Layer £¬¼Ç¼DWGʵÌå²ãÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Layer")); ipFieldEdit->put_AliasName(CComBSTR(L"Layer")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Color £¬¼Ç¼DWGʵÌå·ûºÅÑÕÉ« ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Color")); ipFieldEdit->put_AliasName(CComBSTR(L"Color")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Thickness £¬¼Ç¼DWGʵÌåºñ¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Thickness")); ipFieldEdit->put_AliasName(CComBSTR(L"Thickness")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Elevation £¬¼Ç¼DWGʵÌå¸ß³ÌÖµ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Elevation")); ipFieldEdit->put_AliasName(CComBSTR(L"Elevation")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Height £¬¼Ç¼¸ß¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Height")); ipFieldEdit->put_AliasName(CComBSTR(L"Height")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ TextStyle £¬¼Ç¼ÎÄ×ÖÑùʽ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"TextStyle")); ipFieldEdit->put_AliasName(CComBSTR(L"TextStyle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Oblique £¬¼Ç¼Çã½Ç ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Oblique")); ipFieldEdit->put_AliasName(CComBSTR(L"Oblique")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ AlignmentPointX ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"AlignPtX")); ipFieldEdit->put_AliasName(CComBSTR(L"AlignPtX")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ AlignmentPointY ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"AlignPtY")); ipFieldEdit->put_AliasName(CComBSTR(L"AlignPtY")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); *ppfields = ipFieldsEdit.Detach(); return 0; } /************************************************************************ ¼òÒªÃèÊö : ´´½¨À©Õ¹ÊôÐÔ±í ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ HRESULT XDWGReader::CreateExtendTable(IFeatureWorkspace* pFeatWorkspace, BSTR bstrName, ITable** pTable) { HRESULT hr; if (pFeatWorkspace == NULL) return E_FAIL; // Ö»´´½¨£ºBaseName--ͼÃû£»Handle--ÒªËØID;XDataName--À©Õ¹ÊôÐÔÃû³Æ;XDataNum--À©Õ¹ÊôÐÔ±àºÅ;XDataValue--À©Õ¹ËµÃ÷Öµ hr = pFeatWorkspace->OpenTable(bstrName, pTable); // Èç¹û´ò²»¿ªtable¾ÍÈÏΪ²»´æÔÚ¾ÍÖØ½¨table if (*pTable == NULL) { IFieldsPtr ipFields; ipFields.CreateInstance(CLSID_Fields); IFieldsEditPtr ipIndexFields; ipIndexFields.CreateInstance(CLSID_Fields); IFieldsEditPtr ipFieldsEdit = ipFields; if (ipFieldsEdit == NULL) return E_FAIL; // Add a field for the user name IFieldEditPtr ipField; hr = ipField.CreateInstance(CLSID_Field); if (FAILED(hr)) return hr; hr = ipField->put_Name(CComBSTR(L"Handle")); if (FAILED(hr)) return hr; hr = ipField->put_Type(esriFieldTypeString); if (FAILED(hr)) return hr; hr = ipField->put_Length(150); if (FAILED(hr)) return hr; hr = ipField->put_Required(VARIANT_TRUE); if (FAILED(hr)) return hr; hr = ipFieldsEdit->AddField(ipField); if (FAILED(hr)) return hr; //Ìí¼ÓË÷Òý×Ö¶Î1 hr = ipIndexFields->AddField(ipField); if (FAILED(hr)) return hr; hr = ipField.CreateInstance(CLSID_Field); if (FAILED(hr)) return hr; hr = ipField->put_Name(CComBSTR(L"BaseName")); if (FAILED(hr)) return hr; hr = ipField->put_Type(esriFieldTypeString); if (FAILED(hr)) return hr; hr = ipField->put_Length(250); if (FAILED(hr)) return hr; hr = ipField->put_Required(VARIANT_TRUE); if (FAILED(hr)) return hr; hr = ipFieldsEdit->AddField(ipField); if (FAILED(hr)) return hr; //Ìí¼ÓË÷Òý×Ö¶Î2 hr = ipIndexFields->AddField(ipField); if (FAILED(hr)) return hr; hr = ipField.CreateInstance(CLSID_Field); if (FAILED(hr)) return hr; hr = ipField->put_Name(CComBSTR(L"XDataName")); if (FAILED(hr)) return hr; hr = ipField->put_Type(esriFieldTypeString); if (FAILED(hr)) return hr; hr = ipField->put_Length(250); if (FAILED(hr)) return hr; hr = ipFieldsEdit->AddField(ipField); if (FAILED(hr)) return hr; // 2050 Ϊ×î´óÈÝÁ¿ hr = ipField.CreateInstance(CLSID_Field); if (FAILED(hr)) return hr; hr = ipField->put_Name(CComBSTR(L"XDataValue")); if (FAILED(hr)) return hr; hr = ipField->put_Type(esriFieldTypeString); if (FAILED(hr)) return hr; hr = ipField->put_Length(65535); if (FAILED(hr)) return hr; hr = ipFieldsEdit->AddField(ipField); if (FAILED(hr)) return hr; // Try to Create the table hr = pFeatWorkspace->CreateTable(bstrName, ipFields, NULL, NULL, NULL, pTable); if (FAILED(hr)) return hr; IIndexEditPtr ipIndexEdit; ipIndexEdit.CreateInstance(CLSID_Index); ipIndexEdit->putref_Fields(ipIndexFields); hr = (*pTable)->AddIndex(ipIndexEdit); if (FAILED(hr)) return hr; } return S_OK; } HRESULT XDWGReader::CreateDatasetFeatureClass(IFeatureWorkspace* pFWorkspace, IFeatureDataset* pFDS, IFields* pFields, BSTR bstrName, esriFeatureType featType, IFeatureClass*& ppFeatureClass) { if (!pFDS && !pFWorkspace) return S_FALSE; BSTR bstrConfigWord = L""; IFieldPtr ipField; CComBSTR bstrShapeFld; esriFieldType fieldType; long lNumFields; pFields->get_FieldCount(&lNumFields); for (int i = 0; i < lNumFields; i++) { pFields->get_Field(i, &ipField); ipField->get_Type(&fieldType); if (esriFieldTypeGeometry == fieldType) { ipField->get_Name(&bstrShapeFld); break; } } HRESULT hr; if (pFDS) { hr = pFDS->CreateFeatureClass(bstrName, pFields, 0, 0, featType, bstrShapeFld, 0, &ppFeatureClass); } else { // Ö±½Ó´ò¿ªFeatureClass,Èç¹û²»³É¹¦¾ÍÔÙ´´½¨ hr = pFWorkspace->OpenFeatureClass(bstrName, &ppFeatureClass); if (ppFeatureClass == NULL) hr = pFWorkspace->CreateFeatureClass(bstrName, pFields, 0, 0, featType, bstrShapeFld, 0, &ppFeatureClass); } return hr; } void XDWGReader::GetGeometryDef(IFeatureClass* pClass, IGeometryDef** pDef) { try { BSTR shapeName; pClass->get_ShapeFieldName(&shapeName); IFieldsPtr pFields; pClass->get_Fields(&pFields); long lGeomIndex; pFields->FindField(shapeName, &lGeomIndex); IFieldPtr pField; pFields->get_Field(lGeomIndex, &pField); pField->get_GeometryDef(pDef); } catch (...) { } } BOOL XDWGReader::IsResetDomain(IFeatureWorkspace* pFWorkspace, CString szFCName) { IWorkspace2Ptr iws2(pFWorkspace); VARIANT_BOOL isexist = FALSE; if (iws2) { iws2->get_NameExists(esriDTFeatureClass, CComBSTR(szFCName), &isexist); } return isexist; } void XDWGReader::ResetDomain(IFeatureWorkspace* pFWorkspace, CString szFCName, ISpatialReference* ipSRef) { IGeometryDefPtr ipGeomDef; ISpatialReferencePtr ipOldSRef; double mOldMinX, mOldMinY, mOldMaxY, mOldMaxX; double mMinX, mMinY, mMaxY, mMaxX; double mNewMinX, mNewMinY, mNewMaxY, mNewMaxX, dFX, dFY, mNewXYScale ; HRESULT hr; pFWorkspace->OpenFeatureClass(CComBSTR(szFCName), &m_pFeatClassPolygon); GetGeometryDef(m_pFeatClassPolygon, &ipGeomDef); pFWorkspace->OpenFeatureClass(CComBSTR(szFCName), &m_pFeatClassPoint); GetGeometryDef(m_pFeatClassPoint, &ipGeomDef); pFWorkspace->OpenFeatureClass(CComBSTR(szFCName), &m_pFeatClassLine); GetGeometryDef(m_pFeatClassLine, &ipGeomDef); //pFWorkspace->OpenFeatureClass(CComBSTR(szFCName), &m_pFeatClassText); //GetGeometryDef(m_pFeatClassText, &ipGeomDef); ipGeomDef->get_SpatialReference(&ipOldSRef); ipOldSRef->GetDomain(&mOldMinX, &mOldMaxX, &mOldMinY, &mOldMaxY); ipSRef->GetDomain(&mMinX, &mMaxX, &mMinY, &mMaxY); if (mMinX < mOldMinX) mNewMinX = mMinX; else mNewMinX = mOldMinX; if (mMinY < mOldMinY) mNewMinY = mMinY; else mNewMinY = mOldMinY; if (mMaxX > mOldMaxX) mNewMaxX = mMaxX; else mNewMaxX = mOldMaxX; if (mMaxY > mOldMaxY) mNewMaxY = mMaxY; else mNewMaxY = mOldMaxY; ipOldSRef->SetDomain(mNewMinX, mNewMaxX, mNewMinY, mNewMaxY); ipOldSRef->GetFalseOriginAndUnits(&dFX, &dFY, &mNewXYScale); ipOldSRef->GetDomain(&mNewMinX, &mNewMaxX, &mNewMinY, &mNewMaxY); IGeometryDefEditPtr ipGeomDefEdit(ipGeomDef); hr = ipGeomDefEdit->putref_SpatialReference(ipOldSRef); if (FAILED(hr)) { WriteLog(CatchErrorInfo()); } } // bsplineËã·¨ /********************************************************************* ²Î¿¼: n - ¿ØÖƵãÊý - 1 t - the polynomialµÈ¼¶ + 1 control - ¿ØÖƵã×ø±ê¼¯ output - Êä³öÄâºÏµã×ø±ê¼¯ num_output - Êä³öµãÊý Ìõ¼þ: n+2>t (·ñÔòÎÞÇúÏß) ¿ØÖƵã×ø±ê¼¯ºÍµãÊýÒ»Ö ·ÖÅäÊä³öµã¼¯µãÊýºÍ num_outputÒ»Ö **********************************************************************/ void XDWGReader::Bspline(int n, int t, DwgPoint* control, DwgPoint* output, int num_output) { int* u; double increment, interval; DwgPoint calcxyz; int output_index; u = new int[n + t + 1]; ComputeIntervals(u, n, t); increment = (double) (n - t + 2) / (num_output - 1); // how much parameter goes up each time interval = 0; for (output_index = 0; output_index < num_output - 1; output_index++) { ComputePoint(u, n, t, interval, control, &calcxyz); output[output_index].x = calcxyz.x; output[output_index].y = calcxyz.y; output[output_index].z = calcxyz.z; interval = interval + increment; // increment our parameter } output[num_output - 1].x = control[n].x; // put in the last DwgPoint output[num_output - 1].y = control[n].y; output[num_output - 1].z = control[n].z; delete u; } double XDWGReader::Blend(int k, int t, int* u, double v) // calculate the blending value { double value; if (t == 1) // base case for the recursion { if ((u[k] <= v) && (v < u[k + 1])) value = 1; else value = 0; } else { if ((u[k + t - 1] == u[k]) && (u[k + t] == u[k + 1])) // check for divide by zero { value = 0; } else if (u[k + t - 1] == u[k]) // if a term's denominator is zero,use just the other { value = (u[k + t] - v) / (u[k + t] - u[k + 1]) * Blend(k + 1, t - 1, u, v); } else if (u[k + t] == u[k + 1]) { value = (v - u[k]) / (u[k + t - 1] - u[k]) * Blend(k, t - 1, u, v); } else { value = (v - u[k]) / (u[k + t - 1] - u[k]) * Blend(k, t - 1, u, v) + (u[k + t] - v) / (u[k + t] - u[k + 1]) * Blend(k + 1, t - 1, u, v); } } return value; } void XDWGReader::ComputeIntervals(int* u, int n, int t) // figure out the knots { int j; for (j = 0; j <= n + t; j++) { if (j < t) u[j] = 0; else if ((t <= j) && (j <= n)) u[j] = j - t + 1; else if (j > n) u[j] = n - t + 2; // if n-t=-2 then we're screwed, everything goes to 0 } } void XDWGReader::ComputePoint(int* u, int n, int t, double v, DwgPoint* control, DwgPoint* output) { int k; double temp; // initialize the variables that will hold our outputted DwgPoint output->x = 0; output->y = 0; output->z = 0; for (k = 0; k <= n; k++) { temp = Blend(k, t, u, v); // same blend is used for each dimension coordinate output->x = output->x + (control[k]).x * temp; output->y = output->y + (control[k]).y * temp; output->z = output->z + (control[k]).z * temp; } } /************************************************************************ ¼òÒªÃèÊö : Ìí¼ÓÀ©Õ¹ÊôÐÔ×Ö¶Î ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ void XDWGReader::AddExtraFields(CStringList* pRegapps) { if (pRegapps == NULL) return; if (m_IsJoinXDataAttrs == FALSE || pRegapps->GetCount() <= 0) { return; } m_Regapps.AddTail(pRegapps); } /************************************************************************ ¼òÒªÃèÊö : ³õʼ»¯±àÂë¶ÔÕÕ±í ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ //void XDWGReader::InitCompareCodes(ITable* pCompareTable) //{ //if (pCompareTable==NULL) return; // CleanCompareCodes(); // //IFeatureWorkspacePtr ipFeatureWorkspace = API_GetSysWorkspace(); // //if (ipFeatureWorkspace == NULL) // //{ // // AfxMessageBox("´ò¿ªÏµÍ³±í³ö´í£¡", MB_ICONERROR); // // return; // //} // //ITablePtr pCompareTable; // //ipFeatureWorkspace->OpenTable(CComBSTR("CAD2GDB"), &pCompareTable); // //if (pCompareTable == NULL) // //{ // // AfxMessageBox("±àÂë¶ÔÕÕ±í²»´æÔÚ£¬ÎÞ·¨½øÐбàÂë¶ÔÕÕ¡£", MB_ICONERROR); // // return; // //} // CComBSTR bsStr; // IEsriCursorPtr ipCursor; // pCompareTable->Search(NULL, VARIANT_FALSE, &ipCursor); // if (ipCursor != NULL) // { // long lFieldIndex = -1; // IEsriRowPtr ipRow; // IFieldsPtr pFields = NULL; // ipCursor->NextRow(&ipRow); // while (ipRow != NULL) // { // CComVariant vt; // XDwg2GdbRecord* pTbRow = new XDwg2GdbRecord(); // lFieldIndex = -1; // ipRow->get_Fields(&pFields); // bsStr = "DWG_LAYER"; // pFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // ipRow->get_Value(lFieldIndex, &vt); // if (vt.vt != VT_EMPTY && vt.vt != VT_NULL) // { // pTbRow->DWG_LAYER = (CString) vt.bstrVal; // } // } // bsStr = "DWG_BLOCKNAME"; // pFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // ipRow->get_Value(lFieldIndex, &vt); // if (vt.vt != VT_EMPTY && vt.vt != VT_NULL) // { // pTbRow->DWG_BLOCKNAME = (CString) vt.bstrVal; // } // } // bsStr = "GDB_LAYER"; // pFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // ipRow->get_Value(lFieldIndex, &vt); // if (vt.vt != VT_EMPTY && vt.vt != VT_NULL) // { // pTbRow->GDB_LAYER = (CString) vt.bstrVal; // } // } // bsStr = "YSDM"; // pFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // ipRow->get_Value(lFieldIndex, &vt); // if (vt.vt != VT_EMPTY && vt.vt != VT_NULL) // { // pTbRow->YSDM = (CString) vt.bstrVal; // } // } // bsStr = "YSMC"; // pFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // ipRow->get_Value(lFieldIndex, &vt); // if (vt.vt != VT_EMPTY && vt.vt != VT_NULL) // { // pTbRow->YSMC = (CString) vt.bstrVal; // } // } // ipCursor->NextRow(&ipRow); // //¼ÓÈë¶ÔÕÕÖµ // m_aryCodes.Add(pTbRow); // } // } // bsStr.Empty(); //} /************************************************************************ ¼òÒªÃèÊö : ´ÓFeatureBufferÖеõ½¸ø¶¨×Ö¶ÎÃûµÄÖµ ÊäÈë²ÎÊý : pFeatureBuffer£ºÔ´pFeatureBuffer, sFieldName£ºÐèҪȡֵµÄ×Ö¶ÎÃû ·µ »Ø Öµ : ¸Ã×Ö¶ÎÔÚFeatureBufferÖеÄÖµ ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ CString XDWGReader::GetFeatureBufferFieldValue(IFeatureBuffer*& pFeatureBuffer, CString sFieldName) { CComVariant vtFieldValue; CString sFieldValue; long lIndex; IFieldsPtr pFields; pFeatureBuffer->get_Fields(&pFields); CComBSTR bsStr = sFieldName; pFields->FindField(bsStr, &lIndex); bsStr.Empty(); if (lIndex == -1) { sFieldValue = ""; } else { pFeatureBuffer->get_Value(lIndex, &vtFieldValue); switch (vtFieldValue.vt) { case VT_EMPTY: case VT_NULL: sFieldValue = ""; break; case VT_BOOL: sFieldValue = vtFieldValue.boolVal == TRUE ? "1" : "0"; break; case VT_UI1: sFieldValue.Format("%d", vtFieldValue.bVal); break; case VT_I2: sFieldValue.Format("%d", vtFieldValue.iVal); break; case VT_I4: sFieldValue.Format("%d", vtFieldValue.lVal); break; case VT_R4: { long lVal = vtFieldValue.fltVal; sFieldValue.Format("%d", lVal); } break; case VT_R8: { long lVal = vtFieldValue.dblVal; sFieldValue.Format("%d", lVal); } break; case VT_BSTR: sFieldValue = vtFieldValue.bstrVal; break; default: sFieldValue = ""; break; } } return sFieldValue; } /************************************************************************ ¼òÒªÃèÊö : ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ //void XDWGReader::PutExtraAttributes(IFeatureBuffer*& pFeatureBuffer, XDwg2GdbRecord* pCode) //{ // HRESULT hr; // LONG lFieldIndex; // // IFieldsPtr ipFields; // pFeatureBuffer->get_Fields(&ipFields); // // // CComBSTR bsStr; // CComVariant vtVal; // // bsStr = "GDB_LAYER"; // ipFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // vtVal = pCode->GDB_LAYER; // hr = pFeatureBuffer->put_Value(lFieldIndex, vtVal); // } // // bsStr = "YSDM"; // ipFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // vtVal = pCode->YSDM; // hr = pFeatureBuffer->put_Value(lFieldIndex, vtVal); // } // // bsStr = "YSMC"; // ipFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // vtVal = pCode->YSMC; // hr = pFeatureBuffer->put_Value(lFieldIndex, vtVal); // } // // //bsStr = "SymbolCode"; // //ipFields->FindField(bsStr, &lFieldIndex); // //if (lFieldIndex != -1) // //{ // // vtVal = pCode->SymbolCode; // // hr = pFeatureBuffer->put_Value(lFieldIndex, vtVal); // //} // // bsStr.Empty(); //} //supported by feature classes in ArcSDE and feature classes and tables in File Geodatabase. It improves performance of data loading. HRESULT XDWGReader::BeginLoadOnlyMode(IFeatureClass*& pTargetClass) { //if (pTargetClass == NULL) //{ // return S_FALSE; //} //IFeatureClassLoadPtr pClassLoad(pTargetClass); //if (pClassLoad) //{ // ISchemaLockPtr pSchemaLock(pTargetClass); // if (pSchemaLock) // { // if (SUCCEEDED(pSchemaLock->ChangeSchemaLock(esriExclusiveSchemaLock))) // { // VARIANT_BOOL bLoadOnly; // pClassLoad->get_LoadOnlyMode(&bLoadOnly); // if (!bLoadOnly) // return pClassLoad->put_LoadOnlyMode(VARIANT_TRUE); // else // return S_OK; // } // } //} //return S_FALSE; return S_OK; } HRESULT XDWGReader::EndLoadOnlyMode(IFeatureClass*& pTargetClass) { //if (pTargetClass == NULL) //{ // return S_FALSE; //} //IFeatureClassLoadPtr pClassLoad(pTargetClass); //if (pClassLoad) //{ // ISchemaLockPtr pSchemaLock(pTargetClass); // if (pSchemaLock) // { // if (SUCCEEDED(pSchemaLock->ChangeSchemaLock(esriSharedSchemaLock))) // { // VARIANT_BOOL bLoadOnly; // pClassLoad->get_LoadOnlyMode(&bLoadOnly); // if (bLoadOnly) // return pClassLoad->put_LoadOnlyMode(VARIANT_FALSE); // else // return S_OK; // } // } //} //return S_FALSE; return S_OK; } void XDWGReader::ReleaseFeatureBuffer(IFeatureBufferPtr& pFeatureBuffer) { if (pFeatureBuffer == NULL) { return; } //ÊÍ·ÅÄÚ´æ IGeometry* pShape; HRESULT hr = pFeatureBuffer->get_Shape(&pShape); if (SUCCEEDED(hr)) { if (pShape != NULL) { pShape->SetEmpty(); } } } /************************************************************************ ¼òÒªÃèÊö : ±àÂë¶ÔÕÕ ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ BOOL XDWGReader::CompareCodes(IFeatureBuffer*& pFeatureBuffer) { return TRUE; //try //{ // if (pFeatureBuffer == NULL) // return FALSE; // int iCompareCodes = m_aryCodes.GetSize(); // if (iCompareCodes <= 0) // { // return TRUE; // } // //CString sThickness = GetFeatureBufferFieldValue(pFeatureBuffer, "Thickness"); // CString sBlockname = GetFeatureBufferFieldValue(pFeatureBuffer, "Blockname"); // CString sLayer = GetFeatureBufferFieldValue(pFeatureBuffer, "Layer"); // CString sEntityType = GetFeatureBufferFieldValue(pFeatureBuffer, g_szEntityType); // //µã£±Blockname->DWG_BLOCKNAME // //µã£²Layer->DWG_LAYER // //Ïߣ¬Layer->DWG_LAYER // XDwg2GdbRecord* pDwg2GdbRecord = NULL; // IGeometryPtr pGeometry; // pFeatureBuffer->get_Shape(&pGeometry); // if (pGeometry == NULL) // { // return FALSE; // } // esriFeatureType featType; // IFeaturePtr pFeat; // pFeat = pFeatureBuffer; // if (pFeat != NULL) // { // pFeat->get_FeatureType(&featType); // } // else // { // featType = esriFTSimple; // } // //×¢¼Çͼ²ã // if (featType == esriFTAnnotation) // { // if (!sLayer.IsEmpty()) // { // for (int i = 0; i < iCompareCodes; i++) // { // pDwg2GdbRecord = m_aryCodes.GetAt(i); // if (pDwg2GdbRecord->DWG_LAYER.CompareNoCase(sLayer) == 0) // { // PutExtraAttributes(pFeatureBuffer, pDwg2GdbRecord); // return TRUE; // } // } // } // return FALSE; // } // else if (featType == esriFTSimple) //Ò»°ãͼ²ã // { // //HRESULT hr; // CComVariant OID; // esriGeometryType shapeType; // pGeometry->get_GeometryType(&shapeType); // if (shapeType == esriGeometryPoint) // { // //µã£±Blockname->DWG_BLOCKNAME // //µã£²Layer->DWG_LAYER // if (!sBlockname.IsEmpty()) // { // for (int i = 0; i < iCompareCodes; i++) // { // pDwg2GdbRecord = m_aryCodes.GetAt(i); // if (pDwg2GdbRecord->DWG_BLOCKNAME.CompareNoCase(sBlockname) == 0) // { // PutExtraAttributes(pFeatureBuffer, pDwg2GdbRecord); // return TRUE; // } // } // } // else // { // if (!sLayer.IsEmpty()) // { // for (int i = 0; i < iCompareCodes; i++) // { // pDwg2GdbRecord = m_aryCodes.GetAt(i); // if (pDwg2GdbRecord->DWG_LAYER.CompareNoCase(sLayer) == 0) // { // PutExtraAttributes(pFeatureBuffer, pDwg2GdbRecord); // return TRUE; // } // } // } // } // return FALSE; // } // else //if(shapeType == esriGeometryPolyline) // { // //Ïߣ¬Layer->DWG_LAYER // if (!sLayer.IsEmpty()) // { // for (int i = 0; i < iCompareCodes; i++) // { // pDwg2GdbRecord = m_aryCodes.GetAt(i); // if (pDwg2GdbRecord->DWG_LAYER.CompareNoCase(sLayer) == 0) // { // PutExtraAttributes(pFeatureBuffer, pDwg2GdbRecord); // return TRUE; // } // } // } // return FALSE; // } // } //} //catch (...) //{ // CString sError; // sError.Format("±àÂëת»»³ö´í¡£"); // WriteLog(sError); // return FALSE; //} //return FALSE; } /************************************************************************ ¼òÒªÃèÊö : ´´½¨×¢¼ÇÀàÐ͵ÄÒªËØÀà ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ IFeatureClass* XDWGReader::CreateAnnoFtCls(IWorkspace* pWS, CString sAnnoName, IFields* pFields) { HRESULT hr; IFeatureWorkspaceAnnoPtr PFWSAnno = pWS; IGraphicsLayerScalePtr pGLS(CLSID_GraphicsLayerScale); pGLS->put_Units(esriMeters); pGLS->put_ReferenceScale(m_dAnnoScale); //' set up symbol collection ISymbolCollectionPtr pSymbolColl(CLSID_SymbolCollection); ITextSymbolPtr myTxtSym(CLSID_TextSymbol); //Set the font for myTxtSym IFontDispPtr myFont(CLSID_StdFont); IFontPtr pFt = myFont; pFt->put_Name(CComBSTR("Courier New")); CY cy; cy.Hi = 0; cy.Lo = 9; pFt->put_Size(cy); myTxtSym->put_Font(myFont); // Set the Color for myTxtSym to be Dark Red IRgbColorPtr myColor(CLSID_RgbColor); myColor->put_Red(150); myColor->put_Green(0); myColor->put_Blue (0); myTxtSym->put_Color(myColor); // Set other properties for myTxtSym myTxtSym->put_Angle(0); myTxtSym->put_RightToLeft(VARIANT_FALSE); myTxtSym->put_VerticalAlignment(esriTVABaseline); myTxtSym->put_HorizontalAlignment(esriTHAFull); myTxtSym->put_Size(200); //myTxtSym->put_Case(esriTCNormal); ISymbolPtr pSymbol = myTxtSym; pSymbolColl->putref_Symbol(0, pSymbol); //set up the annotation labeling properties including the expression IAnnotateLayerPropertiesPtr pAnnoProps(CLSID_LabelEngineLayerProperties); pAnnoProps->put_FeatureLinked(VARIANT_TRUE); pAnnoProps->put_AddUnplacedToGraphicsContainer(VARIANT_FALSE); pAnnoProps->put_CreateUnplacedElements(VARIANT_TRUE); pAnnoProps->put_DisplayAnnotation(VARIANT_TRUE); pAnnoProps->put_UseOutput(VARIANT_TRUE); ILabelEngineLayerPropertiesPtr pLELayerProps = pAnnoProps; IAnnotationExpressionEnginePtr aAnnoVBScriptEngine(CLSID_AnnotationVBScriptEngine); pLELayerProps->putref_ExpressionParser(aAnnoVBScriptEngine); pLELayerProps->put_Expression(CComBSTR("[DESCRIPTION]")); pLELayerProps->put_IsExpressionSimple(VARIANT_TRUE); pLELayerProps->put_Offset(0); pLELayerProps->put_SymbolID(0); pLELayerProps->putref_Symbol(myTxtSym); IAnnotateLayerTransformationPropertiesPtr pATP = pAnnoProps; double dRefScale; pGLS->get_ReferenceScale(&dRefScale); pATP->put_ReferenceScale(dRefScale); pATP->put_Units(esriMeters); pATP->put_ScaleRatio(1); IAnnotateLayerPropertiesCollectionPtr pAnnoPropsColl(CLSID_AnnotateLayerPropertiesCollection); pAnnoPropsColl->Add(pAnnoProps); //' use the AnnotationFeatureClassDescription co - class to get the list of required fields and the default name of the shape field IObjectClassDescriptionPtr pOCDesc(CLSID_AnnotationFeatureClassDescription); IFeatureClassDescriptionPtr pFDesc = pOCDesc; IUIDPtr pInstCLSID; IUIDPtr pExtCLSID; CComBSTR bsShapeFieldName; pOCDesc->get_InstanceCLSID(&pInstCLSID); pOCDesc->get_ClassExtensionCLSID(&pExtCLSID); pFDesc->get_ShapeFieldName(&bsShapeFieldName); /*IFieldsPtr pReqFields; pOCDesc->get_RequiredFields(&pReqFields); //ÉèÖÿռä²Î¿¼ if (m_pSpRef != NULL) { long numFields; pReqFields->get_FieldCount(&numFields); for (int i = 0; i < numFields; i++) { IFieldPtr pField; pReqFields->get_Field(i, &pField); esriFieldType fldType; pField->get_Type(&fldType); if (fldType == esriFieldTypeGeometry) { IFieldEditPtr pEdtField = pField; IGeometryDefPtr pGeoDef; hr = pEdtField->get_GeometryDef(&pGeoDef); IGeometryDefEditPtr pEdtGeoDef = pGeoDef; hr = pEdtGeoDef->putref_SpatialReference(m_pSpRef); hr = pEdtField->putref_GeometryDef(pGeoDef); break; } } } IFieldsEditPtr ipFieldsEdit = pReqFields; //´´½¨CADÎļþÖÐ×¢¼Çͼ²ã×Ö¶Î IFieldEditPtr ipFieldEdit; IFieldPtr ipField; // ´´½¨ Entity £¬¼Ç¼esriʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR("Entity_Type")); ipFieldEdit->put_AliasName(CComBSTR("Entity_Type")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ Handle £¬¼Ç¼DWGʵÌå±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Handle")); ipFieldEdit->put_AliasName(CComBSTR(L"Handle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ BaseName £¬¼Ç¼DWGʵÌå²ãÃû¼´DWGÎļþÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"BaseName")); ipFieldEdit->put_AliasName(CComBSTR(L"BaseName")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Layer £¬¼Ç¼DWGʵÌå²ãÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Layer")); ipFieldEdit->put_AliasName(CComBSTR(L"Layer")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Color £¬¼Ç¼DWGʵÌå·ûºÅÑÕÉ« ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Color")); ipFieldEdit->put_AliasName(CComBSTR(L"Color")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Thickness £¬¼Ç¼DWGʵÌåºñ¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Thickness")); ipFieldEdit->put_AliasName(CComBSTR(L"Thickness")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Elevation £¬¼Ç¼DWGʵÌå¸ß³ÌÖµ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Elevation")); ipFieldEdit->put_AliasName(CComBSTR(L"Elevation")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Height £¬¼Ç¼¸ß¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Height")); ipFieldEdit->put_AliasName(CComBSTR(L"Height")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ TextStyle £¬¼Ç¼ÎÄ×ÖÑùʽ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"TextStyle")); ipFieldEdit->put_AliasName(CComBSTR(L"TextStyle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Oblique £¬¼Ç¼Çã½Ç ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Oblique")); ipFieldEdit->put_AliasName(CComBSTR(L"Oblique")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField);*/ IFeatureClass* pAnnoFtCls; //' create the new class hr = PFWSAnno->CreateAnnotationClass(CComBSTR(sAnnoName), pFields, pInstCLSID, pExtCLSID, bsShapeFieldName, CComBSTR(""), NULL, 0, pAnnoPropsColl, pGLS, pSymbolColl, VARIANT_TRUE, &pAnnoFtCls); return pAnnoFtCls; } /************************************************************************ ¼òÒªÃèÊö : Éú³É×¢¼ÇElement ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ ITextElement* XDWGReader::MakeTextElementByStyle(CString strText, double dblAngle, double dblHeight, double dblX, double dblY, double ReferenceScale, esriTextHorizontalAlignment horizAlign, esriTextVerticalAlignment vertAlign) { HRESULT hr; ITextElementPtr pTextElement; ISimpleTextSymbolPtr pTextSymbol; CString strHeight; pTextSymbol.CreateInstance(CLSID_TextSymbol); //'Set the text symbol font by getting the IFontDisp interface pTextSymbol->put_Font(m_pAnnoTextFont); double mapUnitsInches; IUnitConverterPtr pUnitConverter(CLSID_UnitConverter); pUnitConverter->ConvertUnits(dblHeight, esriMeters, esriInches, &mapUnitsInches); strHeight.Format("%f", (mapUnitsInches * 72) / ReferenceScale); double dSize = atof(strHeight); pTextSymbol->put_Size(dSize); pTextSymbol->put_HorizontalAlignment(horizAlign); pTextSymbol->put_VerticalAlignment(vertAlign); pTextElement.CreateInstance(CLSID_TextElement); hr = pTextElement->put_ScaleText(VARIANT_TRUE); hr = pTextElement->put_Text(CComBSTR(strText)); hr = pTextElement->put_Symbol(pTextSymbol); IElementPtr pElement = pTextElement; IPointPtr pPoint(CLSID_Point); hr = pPoint->PutCoords(dblX, dblY); hr = pElement->put_Geometry(pPoint); if (fabs(dblAngle) > 0) { ITransform2DPtr pTransform2D = pTextElement; pTransform2D->Rotate(pPoint, dblAngle); } return pTextElement.Detach(); } /******************************************************************** ¼òÒªÃèÊö : ÊͷŽӿÚÖ¸Õë ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : *********************************************************************/ int XDWGReader::ReleasePointer(IUnknown*& pInterface) { int iRst = 0; if (pInterface != NULL) { try { iRst = pInterface->Release(); pInterface = NULL; } catch(...) { } } return iRst; } // ÊͷŽӿڶÔÏó void XDWGReader::ReleaseAOs(void) { int iRst = 0; iRst = ReleasePointer((IUnknown*&)m_pPointFeatureCursor); iRst = ReleasePointer((IUnknown*&)m_pTextFeatureCursor); iRst = ReleasePointer((IUnknown*&)m_pLineFeatureCursor); iRst = ReleasePointer((IUnknown*&)m_pAnnoFeatureCursor); iRst = ReleasePointer((IUnknown*&)m_pPolygonFeatureCursor); iRst = ReleasePointer((IUnknown*&)m_pExtentTableRowCursor); iRst = ReleasePointer((IUnknown*&)m_pPointFeatureBuffer); iRst = ReleasePointer((IUnknown*&)m_pTextFeatureBuffer); iRst = ReleasePointer((IUnknown*&)m_pLineFeatureBuffer); iRst = ReleasePointer((IUnknown*&)m_pAnnoFeatureBuffer); iRst = ReleasePointer((IUnknown*&)m_pPolygonFeatureBuffer); iRst = ReleasePointer((IUnknown*&)m_pExtentTableRowBuffer); iRst = ReleasePointer((IUnknown*&)m_pSpRef); iRst = ReleasePointer((IUnknown*&)m_pFeatClassPoint); iRst = ReleasePointer((IUnknown*&)m_pFeatClassText); iRst = ReleasePointer((IUnknown*&)m_pFeatClassLine); iRst = ReleasePointer((IUnknown*&)m_pFeatClassPolygon); iRst = ReleasePointer((IUnknown*&)m_pAnnoFtCls); iRst = ReleasePointer((IUnknown*&)m_pExtendTable); } /******************************************************************** ¼òÒªÃèÊö :³õʼ»¯¶ÔÏóÖ¸Õë ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : *********************************************************************/ void XDWGReader::InitAOPointers(void) { m_pPointFeatureCursor = NULL; m_pTextFeatureCursor = NULL; m_pLineFeatureCursor = NULL; m_pAnnoFeatureCursor = NULL; m_pPolygonFeatureCursor = NULL; m_pExtentTableRowCursor = NULL; m_pPointFeatureBuffer = NULL; m_pTextFeatureBuffer = NULL; m_pLineFeatureBuffer = NULL; m_pAnnoFeatureBuffer = NULL; m_pPolygonFeatureBuffer = NULL; m_pExtentTableRowBuffer = NULL; m_pFeatClassPoint = NULL; m_pFeatClassLine = NULL; m_pFeatClassPolygon = NULL; m_pAnnoFtCls = NULL; m_pExtendTable = NULL; m_pFeatClassText = NULL; }
Java
# Copyright 2019 Virgil Dupras # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import datetime from collections import defaultdict from core.util import dedupe, first as getfirst from core.trans import tr from ..model.date import DateFormat from .base import GUIObject from .import_table import ImportTable from .selectable_list import LinkedSelectableList DAY = 'day' MONTH = 'month' YEAR = 'year' class SwapType: DayMonth = 0 MonthYear = 1 DayYear = 2 DescriptionPayee = 3 InvertAmount = 4 def last_two_digits(year): return year - ((year // 100) * 100) def swapped_date(date, first, second): attrs = {DAY: date.day, MONTH: date.month, YEAR: last_two_digits(date.year)} newattrs = {first: attrs[second], second: attrs[first]} if YEAR in newattrs: newattrs[YEAR] += 2000 return date.replace(**newattrs) def swap_format_elements(format, first, second): # format is a DateFormat swapped = format.copy() elems = swapped.elements TYPE2CHAR = {DAY: 'd', MONTH: 'M', YEAR: 'y'} first_char = TYPE2CHAR[first] second_char = TYPE2CHAR[second] first_index = [i for i, x in enumerate(elems) if x.startswith(first_char)][0] second_index = [i for i, x in enumerate(elems) if x.startswith(second_char)][0] elems[first_index], elems[second_index] = elems[second_index], elems[first_index] return swapped class AccountPane: def __init__(self, iwin, account, target_account, parsing_date_format): self.iwin = iwin self.account = account self._selected_target = target_account self.name = account.name entries = iwin.loader.accounts.entries_for_account(account) self.count = len(entries) self.matches = [] # [[ref, imported]] self.parsing_date_format = parsing_date_format self.max_day = 31 self.max_month = 12 self.max_year = 99 # 2 digits self._match_entries() self._swap_possibilities = set() self._compute_swap_possibilities() def _compute_swap_possibilities(self): entries = list(self.iwin.loader.accounts.entries_for_account(self.account)) if not entries: return self._swap_possibilities = set([(DAY, MONTH), (MONTH, YEAR), (DAY, YEAR)]) for first, second in self._swap_possibilities.copy(): for entry in entries: try: swapped_date(entry.date, first, second) except ValueError: self._swap_possibilities.remove((first, second)) break def _match_entries(self): to_import = list(self.iwin.loader.accounts.entries_for_account(self.account)) reference2entry = {} for entry in (e for e in to_import if e.reference): reference2entry[entry.reference] = entry self.matches = [] if self.selected_target is not None: entries = self.iwin.document.accounts.entries_for_account(self.selected_target) for entry in entries: if entry.reference in reference2entry: other = reference2entry[entry.reference] if entry.reconciled: self.iwin.import_table.dont_import.add(other) to_import.remove(other) del reference2entry[entry.reference] else: other = None if other is not None or not entry.reconciled: self.matches.append([entry, other]) self.matches += [[None, entry] for entry in to_import] self._sort_matches() def _sort_matches(self): self.matches.sort(key=lambda t: t[0].date if t[0] is not None else t[1].date) def bind(self, existing, imported): [match1] = [m for m in self.matches if m[0] is existing] [match2] = [m for m in self.matches if m[1] is imported] assert match1[1] is None assert match2[0] is None match1[1] = match2[1] self.matches.remove(match2) def can_swap_date_fields(self, first, second): # 'day', 'month', 'year' return (first, second) in self._swap_possibilities or (second, first) in self._swap_possibilities def match_entries_by_date_and_amount(self, threshold): delta = datetime.timedelta(days=threshold) unmatched = ( to_import for ref, to_import in self.matches if ref is None) unmatched_refs = ( ref for ref, to_import in self.matches if to_import is None) amount2refs = defaultdict(list) for entry in unmatched_refs: amount2refs[entry.amount].append(entry) for entry in unmatched: if entry.amount not in amount2refs: continue potentials = amount2refs[entry.amount] for ref in potentials: if abs(ref.date - entry.date) <= delta: self.bind(ref, entry) potentials.remove(ref) self._sort_matches() def unbind(self, existing, imported): [match] = [m for m in self.matches if m[0] is existing and m[1] is imported] match[1] = None self.matches.append([None, imported]) self._sort_matches() @property def selected_target(self): return self._selected_target @selected_target.setter def selected_target(self, value): self._selected_target = value self._match_entries() # This is a modal window that is designed to be re-instantiated on each import # run. It is shown modally by the UI as soon as its created on the UI side. class ImportWindow(GUIObject): # --- View interface # close() # close_selected_tab() # set_swap_button_enabled(enabled: bool) # update_selected_pane() # show() # def __init__(self, mainwindow, target_account=None): super().__init__() if not hasattr(mainwindow, 'loader'): raise ValueError("Nothing to import!") self.mainwindow = mainwindow self.document = mainwindow.document self.app = self.document.app self._selected_pane_index = 0 self._selected_target_index = 0 def setfunc(index): self.view.set_swap_button_enabled(self.can_perform_swap()) self.swap_type_list = LinkedSelectableList(items=[ "<placeholder> Day <--> Month", "<placeholder> Month <--> Year", "<placeholder> Day <--> Year", tr("Description <--> Payee"), tr("Invert Amounts"), ], setfunc=setfunc) self.swap_type_list.selected_index = SwapType.DayMonth self.panes = [] self.import_table = ImportTable(self) self.loader = self.mainwindow.loader self.target_accounts = [ a for a in self.document.accounts if a.is_balance_sheet_account()] self.target_accounts.sort(key=lambda a: a.name.lower()) accounts = [] for account in self.loader.accounts: if account.is_balance_sheet_account(): entries = self.loader.accounts.entries_for_account(account) if len(entries): new_name = self.document.accounts.new_name(account.name) if new_name != account.name: self.loader.accounts.rename_account(account, new_name) accounts.append(account) parsing_date_format = DateFormat.from_sysformat(self.loader.parsing_date_format) for account in accounts: target = target_account if target is None and account.reference: target = getfirst( t for t in self.target_accounts if t.reference == account.reference ) self.panes.append( AccountPane(self, account, target, parsing_date_format)) # --- Private def _can_swap_date_fields(self, first, second): # 'day', 'month', 'year' pane = self.selected_pane if pane is None: return False return pane.can_swap_date_fields(first, second) def _invert_amounts(self, apply_to_all): if apply_to_all: panes = self.panes else: panes = [self.selected_pane] for pane in panes: entries = self.loader.accounts.entries_for_account(pane.account) txns = dedupe(e.transaction for e in entries) for txn in txns: for split in txn.splits: split.amount = -split.amount self.import_table.refresh() def _refresh_target_selection(self): if not self.panes: return target = self.selected_pane.selected_target self._selected_target_index = 0 if target is not None: try: self._selected_target_index = self.target_accounts.index(target) + 1 except ValueError: pass def _refresh_swap_list_items(self): if not self.panes: return items = [] basefmt = self.selected_pane.parsing_date_format for first, second in [(DAY, MONTH), (MONTH, YEAR), (DAY, YEAR)]: swapped = swap_format_elements(basefmt, first, second) items.append("{} --> {}".format(basefmt.iso_format, swapped.iso_format)) self.swap_type_list[:3] = items def _swap_date_fields(self, first, second, apply_to_all): # 'day', 'month', 'year' assert self._can_swap_date_fields(first, second) if apply_to_all: panes = [p for p in self.panes if p.can_swap_date_fields(first, second)] else: panes = [self.selected_pane] def switch_func(txn): txn.date = swapped_date(txn.date, first, second) self._swap_fields(panes, switch_func) # Now, lets' change the date format on these panes for pane in panes: basefmt = self.selected_pane.parsing_date_format swapped = swap_format_elements(basefmt, first, second) pane.parsing_date_format = swapped pane._sort_matches() self.import_table.refresh() self._refresh_swap_list_items() def _swap_description_payee(self, apply_to_all): if apply_to_all: panes = self.panes else: panes = [self.selected_pane] def switch_func(txn): txn.description, txn.payee = txn.payee, txn.description self._swap_fields(panes, switch_func) def _swap_fields(self, panes, switch_func): seen = set() for pane in panes: entries = self.loader.accounts.entries_for_account(pane.account) txns = dedupe(e.transaction for e in entries) for txn in txns: if txn.affected_accounts() & seen: # We've already swapped this txn in a previous pane. continue switch_func(txn) seen.add(pane.account) self.import_table.refresh() def _update_selected_pane(self): self.import_table.refresh() self._refresh_swap_list_items() self.view.update_selected_pane() self.view.set_swap_button_enabled(self.can_perform_swap()) # --- Override def _view_updated(self): if self.document.can_restore_from_prefs(): self.restore_view() # XXX Logically, we should call _update_selected_pane() but doing so # make tests fail. to investigate. self._refresh_target_selection() self.view.update_selected_pane() self._refresh_swap_list_items() self.import_table.refresh() # --- Public def can_perform_swap(self): index = self.swap_type_list.selected_index if index == SwapType.DayMonth: return self._can_swap_date_fields(DAY, MONTH) elif index == SwapType.MonthYear: return self._can_swap_date_fields(MONTH, YEAR) elif index == SwapType.DayYear: return self._can_swap_date_fields(DAY, YEAR) else: return True def close_pane(self, index): was_selected = index == self.selected_pane_index del self.panes[index] if not self.panes: self.view.close() return self._selected_pane_index = min(self._selected_pane_index, len(self.panes) - 1) if was_selected: self._update_selected_pane() def import_selected_pane(self): pane = self.selected_pane matches = pane.matches matches = [ (e, ref) for ref, e in matches if e is not None and e not in self.import_table.dont_import] if pane.selected_target is not None: # We import in an existing account, adjust all the transactions accordingly target_account = pane.selected_target else: target_account = None self.document.import_entries(target_account, pane.account, matches) self.mainwindow.revalidate() self.close_pane(self.selected_pane_index) self.view.close_selected_tab() def match_entries_by_date_and_amount(self, threshold): self.selected_pane.match_entries_by_date_and_amount(threshold) self.import_table.refresh() def perform_swap(self, apply_to_all=False): index = self.swap_type_list.selected_index if index == SwapType.DayMonth: self._swap_date_fields(DAY, MONTH, apply_to_all=apply_to_all) elif index == SwapType.MonthYear: self._swap_date_fields(MONTH, YEAR, apply_to_all=apply_to_all) elif index == SwapType.DayYear: self._swap_date_fields(DAY, YEAR, apply_to_all=apply_to_all) elif index == SwapType.DescriptionPayee: self._swap_description_payee(apply_to_all=apply_to_all) elif index == SwapType.InvertAmount: self._invert_amounts(apply_to_all=apply_to_all) def restore_view(self): self.import_table.columns.restore_columns() # --- Properties @property def selected_pane(self): return self.panes[self.selected_pane_index] if self.panes else None @property def selected_pane_index(self): return self._selected_pane_index @selected_pane_index.setter def selected_pane_index(self, value): if value >= len(self.panes): return self._selected_pane_index = value self._refresh_target_selection() self._update_selected_pane() @property def selected_target_account(self): return self.selected_pane.selected_target @property def selected_target_account_index(self): return self._selected_target_index @selected_target_account_index.setter def selected_target_account_index(self, value): target = self.target_accounts[value - 1] if value > 0 else None self.selected_pane.selected_target = target self._selected_target_index = value self.import_table.refresh() @property def target_account_names(self): return [tr('< New Account >')] + [a.name for a in self.target_accounts]
Java
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.content; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.content.res.Configuration; import android.content.res.Resources; import android.database.DatabaseErrorHandler; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.UserHandle; import android.view.DisplayAdjustments; import android.view.Display; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /** * Proxying implementation of Context that simply delegates all of its calls to * another Context. Can be subclassed to modify behavior without changing * the original Context. */ public class ContextWrapper extends Context { Context mBase; public ContextWrapper(Context base) { mBase = base; } /** * Set the base context for this ContextWrapper. All calls will then be * delegated to the base context. Throws * IllegalStateException if a base context has already been set. * * @param base The new base context for this wrapper. */ protected void attachBaseContext(Context base) { if (mBase != null) { throw new IllegalStateException("Base context already set"); } mBase = base; } /** * @return the base context as set by the constructor or setBaseContext */ public Context getBaseContext() { return mBase; } @Override public AssetManager getAssets() { return mBase.getAssets(); } @Override public Resources getResources() { return mBase.getResources(); } @Override public PackageManager getPackageManager() { return mBase.getPackageManager(); } @Override public ContentResolver getContentResolver() { return mBase.getContentResolver(); } @Override public Looper getMainLooper() { return mBase.getMainLooper(); } @Override public Context getApplicationContext() { return mBase.getApplicationContext(); } @Override public void setTheme(int resid) { mBase.setTheme(resid); } /** @hide */ @Override public int getThemeResId() { return mBase.getThemeResId(); } @Override public Resources.Theme getTheme() { return mBase.getTheme(); } @Override public ClassLoader getClassLoader() { return mBase.getClassLoader(); } @Override public String getPackageName() { return mBase.getPackageName(); } /** @hide */ @Override public String getBasePackageName() { return mBase.getBasePackageName(); } /** @hide */ @Override public String getOpPackageName() { return mBase.getOpPackageName(); } @Override public ApplicationInfo getApplicationInfo() { return mBase.getApplicationInfo(); } @Override public String getPackageResourcePath() { return mBase.getPackageResourcePath(); } @Override public String getPackageCodePath() { return mBase.getPackageCodePath(); } /** @hide */ @Override public File getSharedPrefsFile(String name) { return mBase.getSharedPrefsFile(name); } @Override public SharedPreferences getSharedPreferences(String name, int mode) { return mBase.getSharedPreferences(name, mode); } @Override public FileInputStream openFileInput(String name) throws FileNotFoundException { return mBase.openFileInput(name); } @Override public FileOutputStream openFileOutput(String name, int mode) throws FileNotFoundException { return mBase.openFileOutput(name, mode); } @Override public boolean deleteFile(String name) { return mBase.deleteFile(name); } @Override public File getFileStreamPath(String name) { return mBase.getFileStreamPath(name); } @Override public String[] fileList() { return mBase.fileList(); } @Override public File getFilesDir() { return mBase.getFilesDir(); } @Override public File getNoBackupFilesDir() { return mBase.getNoBackupFilesDir(); } @Override public File getExternalFilesDir(String type) { return mBase.getExternalFilesDir(type); } @Override public File[] getExternalFilesDirs(String type) { return mBase.getExternalFilesDirs(type); } @Override public File getObbDir() { return mBase.getObbDir(); } @Override public File[] getObbDirs() { return mBase.getObbDirs(); } @Override public File getCacheDir() { return mBase.getCacheDir(); } @Override public File getCodeCacheDir() { return mBase.getCodeCacheDir(); } @Override public File getExternalCacheDir() { return mBase.getExternalCacheDir(); } @Override public File[] getExternalCacheDirs() { return mBase.getExternalCacheDirs(); } @Override public File[] getExternalMediaDirs() { return mBase.getExternalMediaDirs(); } @Override public File getDir(String name, int mode) { return mBase.getDir(name, mode); } @Override public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory) { return mBase.openOrCreateDatabase(name, mode, factory); } @Override public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory, DatabaseErrorHandler errorHandler) { return mBase.openOrCreateDatabase(name, mode, factory, errorHandler); } @Override public boolean deleteDatabase(String name) { return mBase.deleteDatabase(name); } @Override public File getDatabasePath(String name) { return mBase.getDatabasePath(name); } @Override public String[] databaseList() { return mBase.databaseList(); } @Override public Drawable getWallpaper() { return mBase.getWallpaper(); } @Override public Drawable peekWallpaper() { return mBase.peekWallpaper(); } @Override public int getWallpaperDesiredMinimumWidth() { return mBase.getWallpaperDesiredMinimumWidth(); } @Override public int getWallpaperDesiredMinimumHeight() { return mBase.getWallpaperDesiredMinimumHeight(); } @Override public void setWallpaper(Bitmap bitmap) throws IOException { mBase.setWallpaper(bitmap); } @Override public void setWallpaper(InputStream data) throws IOException { mBase.setWallpaper(data); } @Override public void clearWallpaper() throws IOException { mBase.clearWallpaper(); } @Override public void startActivity(Intent intent) { mBase.startActivity(intent); } /** @hide */ @Override public void startActivityAsUser(Intent intent, UserHandle user) { mBase.startActivityAsUser(intent, user); } @Override public void startActivity(Intent intent, Bundle options) { mBase.startActivity(intent, options); } /** @hide */ @Override public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) { mBase.startActivityAsUser(intent, options, user); } @Override public void startActivities(Intent[] intents) { mBase.startActivities(intents); } @Override public void startActivities(Intent[] intents, Bundle options) { mBase.startActivities(intents, options); } /** @hide */ @Override public void startActivitiesAsUser(Intent[] intents, Bundle options, UserHandle userHandle) { mBase.startActivitiesAsUser(intents, options, userHandle); } @Override public void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) throws IntentSender.SendIntentException { mBase.startIntentSender(intent, fillInIntent, flagsMask, flagsValues, extraFlags); } @Override public void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options) throws IntentSender.SendIntentException { mBase.startIntentSender(intent, fillInIntent, flagsMask, flagsValues, extraFlags, options); } @Override public void sendBroadcast(Intent intent) { mBase.sendBroadcast(intent); } @Override public void sendBroadcast(Intent intent, String receiverPermission) { mBase.sendBroadcast(intent, receiverPermission); } /** @hide */ @Override public void sendBroadcast(Intent intent, String receiverPermission, int appOp) { mBase.sendBroadcast(intent, receiverPermission, appOp); } @Override public void sendOrderedBroadcast(Intent intent, String receiverPermission) { mBase.sendOrderedBroadcast(intent, receiverPermission); } @Override public void sendOrderedBroadcast( Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendOrderedBroadcast(intent, receiverPermission, resultReceiver, scheduler, initialCode, initialData, initialExtras); } /** @hide */ @Override public void sendOrderedBroadcast( Intent intent, String receiverPermission, int appOp, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendOrderedBroadcast(intent, receiverPermission, appOp, resultReceiver, scheduler, initialCode, initialData, initialExtras); } @Override public void sendBroadcastAsUser(Intent intent, UserHandle user) { mBase.sendBroadcastAsUser(intent, user); } @Override public void sendBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission) { mBase.sendBroadcastAsUser(intent, user, receiverPermission); } @Override public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendOrderedBroadcastAsUser(intent, user, receiverPermission, resultReceiver, scheduler, initialCode, initialData, initialExtras); } /** @hide */ @Override public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, int appOp, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendOrderedBroadcastAsUser(intent, user, receiverPermission, appOp, resultReceiver, scheduler, initialCode, initialData, initialExtras); } @Override public void sendStickyBroadcast(Intent intent) { mBase.sendStickyBroadcast(intent); } @Override public void sendStickyOrderedBroadcast( Intent intent, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendStickyOrderedBroadcast(intent, resultReceiver, scheduler, initialCode, initialData, initialExtras); } @Override public void removeStickyBroadcast(Intent intent) { mBase.removeStickyBroadcast(intent); } @Override public void sendStickyBroadcastAsUser(Intent intent, UserHandle user) { mBase.sendStickyBroadcastAsUser(intent, user); } @Override public void sendStickyOrderedBroadcastAsUser(Intent intent, UserHandle user, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendStickyOrderedBroadcastAsUser(intent, user, resultReceiver, scheduler, initialCode, initialData, initialExtras); } @Override public void removeStickyBroadcastAsUser(Intent intent, UserHandle user) { mBase.removeStickyBroadcastAsUser(intent, user); } @Override public Intent registerReceiver( BroadcastReceiver receiver, IntentFilter filter) { return mBase.registerReceiver(receiver, filter); } @Override public Intent registerReceiver( BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler) { return mBase.registerReceiver(receiver, filter, broadcastPermission, scheduler); } /** @hide */ @Override public Intent registerReceiverAsUser( BroadcastReceiver receiver, UserHandle user, IntentFilter filter, String broadcastPermission, Handler scheduler) { return mBase.registerReceiverAsUser(receiver, user, filter, broadcastPermission, scheduler); } @Override public void unregisterReceiver(BroadcastReceiver receiver) { mBase.unregisterReceiver(receiver); } @Override public ComponentName startService(Intent service) { return mBase.startService(service); } @Override public boolean stopService(Intent name) { return mBase.stopService(name); } /** @hide */ @Override public ComponentName startServiceAsUser(Intent service, UserHandle user) { return mBase.startServiceAsUser(service, user); } /** @hide */ @Override public boolean stopServiceAsUser(Intent name, UserHandle user) { return mBase.stopServiceAsUser(name, user); } @Override public boolean bindService(Intent service, ServiceConnection conn, int flags) { return mBase.bindService(service, conn, flags); } /** @hide */ @Override public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags, UserHandle user) { return mBase.bindServiceAsUser(service, conn, flags, user); } @Override public void unbindService(ServiceConnection conn) { mBase.unbindService(conn); } @Override public boolean startInstrumentation(ComponentName className, String profileFile, Bundle arguments) { return mBase.startInstrumentation(className, profileFile, arguments); } @Override public Object getSystemService(String name) { return mBase.getSystemService(name); } @Override public int checkPermission(String permission, int pid, int uid) { return mBase.checkPermission(permission, pid, uid); } /** @hide */ @Override public int checkPermission(String permission, int pid, int uid, IBinder callerToken) { return mBase.checkPermission(permission, pid, uid, callerToken); } @Override public int checkCallingPermission(String permission) { return mBase.checkCallingPermission(permission); } @Override public int checkCallingOrSelfPermission(String permission) { return mBase.checkCallingOrSelfPermission(permission); } @Override public void enforcePermission( String permission, int pid, int uid, String message) { mBase.enforcePermission(permission, pid, uid, message); } @Override public void enforceCallingPermission(String permission, String message) { mBase.enforceCallingPermission(permission, message); } @Override public void enforceCallingOrSelfPermission( String permission, String message) { mBase.enforceCallingOrSelfPermission(permission, message); } @Override public void grantUriPermission(String toPackage, Uri uri, int modeFlags) { mBase.grantUriPermission(toPackage, uri, modeFlags); } @Override public void revokeUriPermission(Uri uri, int modeFlags) { mBase.revokeUriPermission(uri, modeFlags); } @Override public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) { return mBase.checkUriPermission(uri, pid, uid, modeFlags); } /** @hide */ @Override public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags, IBinder callerToken) { return mBase.checkUriPermission(uri, pid, uid, modeFlags, callerToken); } @Override public int checkCallingUriPermission(Uri uri, int modeFlags) { return mBase.checkCallingUriPermission(uri, modeFlags); } @Override public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) { return mBase.checkCallingOrSelfUriPermission(uri, modeFlags); } @Override public int checkUriPermission(Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags) { return mBase.checkUriPermission(uri, readPermission, writePermission, pid, uid, modeFlags); } @Override public void enforceUriPermission( Uri uri, int pid, int uid, int modeFlags, String message) { mBase.enforceUriPermission(uri, pid, uid, modeFlags, message); } @Override public void enforceCallingUriPermission( Uri uri, int modeFlags, String message) { mBase.enforceCallingUriPermission(uri, modeFlags, message); } @Override public void enforceCallingOrSelfUriPermission( Uri uri, int modeFlags, String message) { mBase.enforceCallingOrSelfUriPermission(uri, modeFlags, message); } @Override public void enforceUriPermission( Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags, String message) { mBase.enforceUriPermission( uri, readPermission, writePermission, pid, uid, modeFlags, message); } @Override public Context createPackageContext(String packageName, int flags) throws PackageManager.NameNotFoundException { return mBase.createPackageContext(packageName, flags); } /** @hide */ @Override public Context createPackageContextAsUser(String packageName, int flags, UserHandle user) throws PackageManager.NameNotFoundException { return mBase.createPackageContextAsUser(packageName, flags, user); } /** @hide */ public Context createApplicationContext(ApplicationInfo application, int flags) throws PackageManager.NameNotFoundException { return mBase.createApplicationContext(application, flags); } /** @hide */ @Override public int getUserId() { return mBase.getUserId(); } @Override public Context createConfigurationContext(Configuration overrideConfiguration) { return mBase.createConfigurationContext(overrideConfiguration); } @Override public Context createDisplayContext(Display display) { return mBase.createDisplayContext(display); } @Override public boolean isRestricted() { return mBase.isRestricted(); } /** @hide */ @Override public DisplayAdjustments getDisplayAdjustments(int displayId) { return mBase.getDisplayAdjustments(displayId); } }
Java
The C-BGP Routing Solver == C-BGP is an efficient solver for BGP, the de facto standard protocol used for exchanging routing information accross domains in the Internet. BGP was initially described in RFC1771 in 1995. It has since undergone several updates recently standardized in RFC4271 (2006). C-BGP is aimed at computing the outcome of the BGP decision process in networks composed of several routers. For this purpose, it takes into account the routers' configuration, the externally received BGP routes and the network topology. It supports the complete BGP decision process, versatile import and export filters, route-reflection, and experimental attributes such as redistribution communities. It is easily configurable through a CISCO-like command-line interface. C-BGP has been described in an IEEE Network magazine paper entitled "Modeling the Routing of an Autonomous System with C-BGP" (please refer to this paper when you cite C-BGP). C-BGP can be used as a research tool to experiment with modified decision processes and additional BGP route attributes. It can also be used by the operator of an ISP network to evaluate the impact of logical and topological changes on the routing tables computed in its routers. Topological changes include links and routers failures. Logical changes include changes in the configuration of the routers such as input/output routing policies or IGP link weights. Thanks to its efficiency, C-BGP can be used on large topologies with sizes of the same order of magnitude than the Internet. For the moment, we mainly use it to study interdomain traffic engineering techniques and to model the network of ISPs. The original version of C-BGP was written by Bruno Quoitin within the Computer Science and Engineering Department at Universite Catholique de Louvain (UCL), in Belgium. It has since been contributed by others (see the AUTHORS file for a complete list). C-BGP is written in C language. It is mainly used and tested on Linux and Mac OS X. It has also been used on other platforms such as FreeBSD, Solaris and even under Windows, using the cygwin API. It should compile on most POSIX compliant environment. C-BGP is Open-Source and provided under the GPL license for academic use. The text of the GPL license is available in the COPYING file included in this distribution. Commercial use of C-BGP is covered by a separate license since version 2.0.0. WHERE TO OBTAIN LIBGDS & CBGP == The main location is now sourceforge. http://sourceforge.net/projects/c-bgp/ http://sourceforge.net/projects/libgds Older version can be obtained from http://cbgp.info.ucl.ac.be http://libgds.info.ucl.ac.be REQUIRED LIBRARIES AND TOOLS == - a decent version of gcc and GNU make - the pcre library: perl compatible regular expressions - the readline library: this is optional, but it greatly enhances the cbgp experience :-) - libz and libbz2 - pkg-config Note that for libraries, you will need to install the actual library and the header files to be able to link against the library. These header files are usually available in a "-devel" package. HOW TO BUILD LIBGDS & CBGP == 1). build libgds tar xvzf libgdz-x.x.x.tar.gz cd libgds-x.x.x # at this stage you can specify an alternative installation directory # with --prefix=<path>, the default being /usr/local ./configure make clean make # before installing, please check the section below that talks about # testing make install Note: if you installed libgds in a non-standard directory, you will need to make sure that pkg-config is able to find libgds. This is usually done by adding the libgds install directory to pkg-config using the PKG_CONFIG_PATH environment variable. For example, if libgds was installed in /home/foo/local, you will need to add it to the PKG_CONFIG_PATH variable as follows: export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/home/foo/local/lib/pkgconfig you can then test that pkg-config is able to find libgds by issuing the following command: pkg-config libgds --modversion the above command should return the version of the installed libgds library 2). builds cbgp tar xvzf cbgp-x.x.x.tar.gz cd cbgp-x.x.x # at this stage, several options can be used (use --help to obtain # the complete list. important options are # --with-readline=<path> to specify where the readline library is located # --with-pcre=<path> to specify where the pcre library is located # --with-jni to allow the java native interface to compile ./configure make clean make # before installing, please check the section below that talks about # testing make install HOW TO TEST IF LIBGDS & CBGP ARE FUNCTIONNAL == 1). run internal unit tests libgds and cbgp source repository contains several unit test functions that can be run with a single line * libgds: make check * cbgp: make check most tests should succeed. A final line is provided that summarizes the number of tests and how many failed among them. At the time of this writing, the following numbers were reported: * libgds: FAILURES=0 / SKIPPED=2 / TESTS=153 * cbgp: FAILURES=1 / SKIPPED=5 / TESTS=188 if the numbers you obtain deviate significantly from the above numbers, you should become suspicious and look more carefully) 2). run external black-box tests cbgp comes with a (huge) perl script that runs several cbgp scripts and observe their behaviour and results. to run these tests, you should move to the "./valid" subdirectory in the cbgp main directory and run "./cbgp-validation.pl --no-cache". this can take some time depending on the platform. 3). run cbgp the final test consists in running cbgp. at this point it might be interesting to check if cbgp was correctly linked with the readline library. it should provide auto-completion for most cbgp commands as well as a history of all the commands typed in the cbgp console. a simple test is done as follows for the version just compiled (not yet installed) # assuming you are in the root cbgp directory ../src/cbgp C-BGP Routing Solver version 2.0.0-rc3 Copyright (C) 2002-2010 Bruno Quoitin Networking Lab Computer Science Institute University of Mons (UMONS) Mons, Belgium This software is free for personal and educational uses. See file COPYING for details. help is bound to '?' key cbgp> init. cbgp> here you can now type "sh" then press the "tabulation" key. it should complete with "show". press again the tabulation key twice and it should list the sub-commands of "show" cbgp> sh <tab> cbgp> show <tab><tab> comm-hash-content comm-hash-size comm-hash-stat commands mem-limit mrt path-hash-content path-hash-size path-hash-stat version in case auto-completion and/or history do not seem to work, check the results of the "./configure" script for warnings related to the version and features of the readline library that was detected. in case the wrong version of the readline library was chosen, you can specify where to find the correct version by using the "--with-readline==<path>" option with the "./configure" script. for example, on my machine, i need to run ./configure -with-readline=/opt/local
Java
#### 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)
Java
// Copyright (c) François Paradis // This file is part of Mox, a card game simulator. // // Mox is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 3 of the License. // // Mox is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Mox. If not, see <http://www.gnu.org/licenses/>. using System; using Mox.Events; using Mox.Flow; namespace Mox.Database.Library { public abstract class ZoneChangeTriggeredAbility : 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 IsTriggeringSourceZone(Zone zone) { return true; } private bool IsTriggeringTargetZone(Game game, ZoneChangeContext zoneChangeContext) { return zoneChangeContext.Card.Resolve(game).Zone.ZoneId == TriggerZone; } public override bool CanPushOnStack(Game game, object zoneChangeContext) { return IsTriggeringTargetZone(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 (IsTriggeringTargetZone(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) && IsTriggeringSourceZone(e.OldZone) && e.NewZone.ZoneId == TriggerZone) { Trigger(new ZoneChangeContext(e.Card)); } } #endregion } }
Java
package com.thomasjensen.checkstyle.addons.checks; /* * Checkstyle-Addons - Additional Checkstyle checks * Copyright (c) 2015-2020, the Checkstyle Addons contributors * * This program is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License, version 3, as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this * program. If not, see <http://www.gnu.org/licenses/>. */ 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 IllegalArgumentException("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 IllegalArgumentException("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(); } }
Java
#include "Board.h" #include <iostream> using namespace std; void Board::enumExts( ) { if(ptester->hasUnboundedHorizAttacks()) { 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; }
Java
/* * $Id: LeftJoin.java,v 1.2 2006/04/09 12:13:12 laddi Exp $ * Created on 5.10.2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ 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; /** * * Last modified: $Date: 2006/04/09 12:13:12 $ by $Author: laddi $ * * @author <a href="mailto:gummi@idega.com">Gudmundur Agust Saemundsson</a> * @version $Revision: 1.2 $ */ 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); } }
Java
<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.WindowsDefaultLocation 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
Java
--- title: "मेरा इस्तीफा राफेल को लेकर हुआ है : तारिक अनवर" layout: item category: ["politics"] date: 2018-09-29T04:19:03.930Z image: 1538214543927tariq.jpg --- <p>नई दिल्ली: राष्ट्रवादी कांग्रेस पार्टी (एनसीपी) और लोकसभा सदस्यता से इस्तीफा दे चुके वरिष्ठ नेता तारिक अनवर का कहना है कि &#39;मेरी नाराजगी राफेल को लेकर पार्टी से है. देश में राफेल घोटाला हुआ, लेकिन जो पवार साहब (शरद पवार) का बयान आया वह ठीक नहीं था. मेरा इस्तीफा राफेल को लेकर हुआ है.&#39;</p> <p>तारिक अनवर से जब पूछा गया कि अब एनसीपी कह रही है कि पवार साहब का इंटरव्यू तोड़मरोड़ के दिखाया गया? तो अनवर ने कहा कि यह क्लेरिफिकेशन देने में एनसीपी ने बहुत देर कर दी है. अब मैं अपना फैसला ले चुका हूं.</p> <p>कयास लग रहे हैं कि आप कांग्रेस में जा रहे हैं? इस सवाल पर तारिक अनवर ने कहा कि अभी कुछ कहना जल्दबाज़ी होगी. मैं दिल्ली आया हूं, कार्यकर्ताओं से बात करूंगा. पर जो करूंगा वह बीजेपी के खिलाफ होगा.</p> <p>जब उनसे पूछा कि महागठबंधन में भी क्या आपकी कोई भूमिका रहेगी अब? तो तारिक अनवर ने कहा कि हां मेरी सारी लाइक माइंडेड पार्टियों को साथ लेने की कोशिश रहेगी. राफेल देश में बड़ा घोटाला है.</p>
Java
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.descriptorExpression.ClassExpression; import it.emarolab.owloop.descriptor.construction.descriptorGround.ClassGround; import it.emarolab.owloop.descriptor.utility.individualDescriptor.LinkIndividualDesc; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLNamedIndividual; import java.util.List; /** * This is an example of a 'simple' Class Descriptor that implements 1 ClassExpression (aka {@link ClassExpression}) interface: * <ul> * <li><b>{@link ClassExpression.Instance}</b>: to describe an Individual of a Class.</li> * </ul> * * See {@link FullClassDesc} for an example of a 'compound' Class Descriptor that implements all ClassExpressions (aka {@link ClassExpression}). * <p> * <div style="text-align:center;"><small> * <b>File</b>: it.emarolab.owloop.core.Axiom <br> * <b>Licence</b>: GNU GENERAL PUBLIC LICENSE. Version 3, 29 June 2007 <br> * <b>Authors</b>: Buoncompagni Luca (luca.buoncompagni@edu.unige.it), Syed Yusha Kareem (kareem.syed.yusha@dibris.unige.it) <br> * <b>affiliation</b>: EMAROLab, DIBRIS, University of Genoa. <br> * <b>date</b>: 01/05/19 <br> * </small></div> */ 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 getIndividualDescriptor(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"; } }
Java
// -*- Mode: Go; indent-tabs-mode: t -*- /* * Copyright (C) 2016 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ 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 RequestStoreMacaroon = requestStoreMacaroon DischargeAuthCaveat = dischargeAuthCaveat RefreshDischargeMacaroon = refreshDischargeMacaroon RequestStoreDeviceNonce = requestStoreDeviceNonce RequestDeviceSession = requestDeviceSession LoginCaveatID = loginCaveatID JsonContentType = jsonContentType SnapActionFields = snapActionFields ) // MockDefaultRetryStrategy mocks the retry strategy used by several store requests func MockDefaultRetryStrategy(t *testutil.BaseTest, strategy retry.Strategy) { originalDefaultRetryStrategy := defaultRetryStrategy defaultRetryStrategy = strategy t.AddCleanup(func() { defaultRetryStrategy = originalDefaultRetryStrategy }) } func MockConnCheckStrategy(t *testutil.BaseTest, strategy retry.Strategy) { originalConnCheckStrategy := connCheckStrategy connCheckStrategy = strategy t.AddCleanup(func() { connCheckStrategy = originalConnCheckStrategy }) } 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 } }
Java
using System; using System.Threading; using System.Windows.Input; namespace WpfAsyncPack.Internal { internal sealed class CancelAsyncCommand : ICommand { private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); private bool _isCommandExecuting; public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public CancellationToken Token => _cancellationTokenSource.Token; void ICommand.Execute(object parameter) { _cancellationTokenSource.Cancel(); RaiseCanExecuteChanged(); } bool ICommand.CanExecute(object parameter) { return _isCommandExecuting && !_cancellationTokenSource.IsCancellationRequested; } public void NotifyCommandStarting() { _isCommandExecuting = true; if (_cancellationTokenSource.IsCancellationRequested) { _cancellationTokenSource = new CancellationTokenSource(); RaiseCanExecuteChanged(); } } public void NotifyCommandFinished() { _isCommandExecuting = false; RaiseCanExecuteChanged(); } private static void RaiseCanExecuteChanged() { CommandManager.InvalidateRequerySuggested(); } } }
Java
<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>
Java
<?php /** * The file that defines the core plugin class * * A class definition that includes attributes and functions used across both the * public-facing side of the site and the admin area. * * @link http://stephanetauziede.com * @since 1.0.0 * * @package Wp_Startup_Press_Room * @subpackage Wp_Startup_Press_Room/includes */ /** * The core plugin class. * * This is used to define internationalization, 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 Wp_Startup_Press_Room * @subpackage Wp_Startup_Press_Room/includes * @author Stephane Tauziede <stauziede@gmail.com> */ class Wp_Startup_Press_Room { /** * The loader that's responsible for maintaining and registering all hooks that power * the plugin. * * @since 1.0.0 * @access protected * @var Wp_Startup_Press_Room_Loader $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 = 'wp-startup-press-room'; $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: * * - Wp_Startup_Press_Room_Loader. Orchestrates the hooks of the plugin. * - Wp_Startup_Press_Room_i18n. Defines internationalization functionality. * - Wp_Startup_Press_Room_Admin. Defines all hooks for the admin area. * - Wp_Startup_Press_Room_Public. 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/class-wp-startup-press-room-loader.php'; /** * The class responsible for defining internationalization functionality * of the plugin. */ require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-wp-startup-press-room-i18n.php'; /** * The class responsible for defining all actions that occur in the admin area. */ require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/class-wp-startup-press-room-admin.php'; /** * The class responsible for PR options page in the admin area. */ require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/class-wp-startup-press-room-options.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/class-wp-startup-press-room-public.php'; $this->loader = new Wp_Startup_Press_Room_Loader(); // Required files for registering the post type and taxonomies. require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-post-type-registrations.php'; require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-post-type-metaboxes.php'; // Instantiate registration class, so we can add it as a dependency to main plugin class. $post_type_registrations = new PR_Post_Type_Registrations; // Register callback that is fired when the plugin is activated. register_activation_hook( __FILE__, array( $post_type, 'activate' ) ); // Initialize registrations for post-activation requests. $post_type_registrations->init(); // Initialize metaboxes //$post_type_metaboxes = new PR_Meta_Box; //$post_type_metaboxes->init(); } /** * Define the locale for this plugin for internationalization. * * Uses the Wp_Startup_Press_Room_i18n 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 Wp_Startup_Press_Room_i18n(); $this->loader->add_action( 'plugins_loaded', $plugin_i18n, 'load_plugin_textdomain' ); } /** * 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 Wp_Startup_Press_Room_Admin( $this->get_plugin_name(), $this->get_version() ); $this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_styles' ); $this->loader->add_action( 'admin_enqueue_scripts', $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 Wp_Startup_Press_Room_Public( $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 internationalization 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 Wp_Startup_Press_Room_Loader 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; } }
Java
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);
Java
/** * Copyright (c) 2006-2014 LOVE Development Team * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. **/ #ifndef LOVE_JOYSTICK_WRAP_JOYSTICK_H #define LOVE_JOYSTICK_WRAP_JOYSTICK_H // 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 w_Joystick_isConnected(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 w_Joystick_getAxisCount(lua_State *L); int w_Joystick_getButtonCount(lua_State *L); int w_Joystick_getHatCount(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 w_Joystick_isGamepad(lua_State *L); int w_Joystick_getGamepadAxis(lua_State *L); int w_Joystick_isGamepadDown(lua_State *L); int w_Joystick_isVibrationSupported(lua_State *L); int w_Joystick_setVibration(lua_State *L); int w_Joystick_getVibration(lua_State *L); extern "C" int luaopen_joystick(lua_State *L); } // joystick } // love #endif // LOVE_JOYSTICK_SDL_WRAP_JOYSTICK_H
Java
/* Copyright (C) 2011 Srivats P. This file is part of "Ostinato" This is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ #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 QXmlStreamAttributes &attributes, OstProto::Protocol *pbProto, OstProto::Stream *stream); virtual void postProtocolHandler(OstProto::Protocol *pbProto, OstProto::Stream *stream); protected: PdmlEthProtocol(); }; #endif
Java
/* * Copyright 2013, winocm. <winocm@icloud.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * If you are going to use this software in any form that does not involve * releasing the source to this project or improving it, let me know beforehand. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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> /** * pe_arm_init_interrupts * * Initialize the SoC dependent interrrupt controller. */ uint32_t pe_arm_init_interrupts(__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; } /** * pe_arm_init_timebase * * Initialize the SoC dependent timebase. */ uint32_t pe_arm_init_timebase(__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; } /** * pe_arm_dispatch_interrupt * * Dispatch IRQ requests to the SoC specific handler. */ boolean_t pe_arm_dispatch_interrupt(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(); } /** * pe_arm_set_timer_enabled * * Set platform timer enabled status. */ void pe_arm_set_timer_enabled(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 PE_i_can_has_debugger(uint32_t * pe_debug) { if (pe_debug) { if (debug_enabled) *pe_debug = 1; else *pe_debug = 0; } return debug_enabled; } uint32_t PE_get_security_epoch(void) { return 0; }
Java
<?php /* * AJGL CSV RFC Component * * Copyright (C) Antonio J. García Lagar <aj@garcialagar.es> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Ajgl\Csv\Rfc\Tests\Spl; use Ajgl\Csv\Rfc\Spl\SplFileObject; /** * @author Antonio J. García Lagar <aj@garcialagar.es> */ class SplFileObjectTest extends AbstractSplFileObjectTest { protected function buildFileObject() { return new SplFileObject('php://temp', 'w+'); } }
Java
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; } }
Java
#!/usr/bin/env python # coding=utf-8 """30. Digit fifth powers https://projecteuler.net/problem=30 Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: > 1634 = 14 \+ 64 \+ 34 \+ 44 > 8208 = 84 \+ 24 \+ 04 \+ 84 > 9474 = 94 \+ 44 \+ 74 \+ 44 As 1 = 14 is not a sum it is not included. The sum of these numbers is 1634 + 8208 + 9474 = 19316. Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. """
Java
#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 HCI_H4_CMD_PREAMBLE_SIZE (4) /* HCI Command opcode group field(OGF) */ #define HCI_GRP_HOST_CONT_BASEBAND_CMDS (0x03 << 10) /* 0x0C00 */ #define HCI_GRP_BLE_CMDS (0x08 << 10) #define HCI_RESET (0x0003 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_BLE_WRITE_ADV_ENABLE (0x000A | HCI_GRP_BLE_CMDS) #define HCI_BLE_WRITE_ADV_PARAMS (0x0006 | HCI_GRP_BLE_CMDS) #define HCI_BLE_WRITE_ADV_DATA (0x0008 | HCI_GRP_BLE_CMDS) #define HCIC_PARAM_SIZE_WRITE_ADV_ENABLE (1) #define HCIC_PARAM_SIZE_BLE_WRITE_ADV_PARAMS (15) #define HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA (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 controller_rcv_pkt_ready(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 esp_vhci_host_callback_t vhci_host_cb = { controller_rcv_pkt_ready, 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 HCI_H4_CMD_PREAMBLE_SIZE; } static uint16_t make_cmd_ble_set_adv_enable (uint8_t *buf, uint8_t adv_enable) { UINT8_TO_STREAM (buf, H4_TYPE_COMMAND); UINT16_TO_STREAM (buf, HCI_BLE_WRITE_ADV_ENABLE); UINT8_TO_STREAM (buf, HCIC_PARAM_SIZE_WRITE_ADV_ENABLE); UINT8_TO_STREAM (buf, adv_enable); return HCI_H4_CMD_PREAMBLE_SIZE + HCIC_PARAM_SIZE_WRITE_ADV_ENABLE; } static uint16_t make_cmd_ble_set_adv_param (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, HCI_BLE_WRITE_ADV_PARAMS); UINT8_TO_STREAM (buf, HCIC_PARAM_SIZE_BLE_WRITE_ADV_PARAMS ); 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 HCI_H4_CMD_PREAMBLE_SIZE + HCIC_PARAM_SIZE_BLE_WRITE_ADV_PARAMS; } static uint16_t make_cmd_ble_set_adv_data(uint8_t *buf, uint8_t data_len, uint8_t *p_data) { UINT8_TO_STREAM (buf, H4_TYPE_COMMAND); UINT16_TO_STREAM (buf, HCI_BLE_WRITE_ADV_DATA); UINT8_TO_STREAM (buf, HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA + 1); memset(buf, 0, HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA); if (p_data != NULL && data_len > 0) { if (data_len > HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA) { data_len = HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA; } UINT8_TO_STREAM (buf, data_len); ARRAY_TO_STREAM (buf, p_data, data_len); } return HCI_H4_CMD_PREAMBLE_SIZE + HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA + 1; } static void hci_cmd_send_reset(void) { uint16_t sz = make_cmd_reset (hci_cmd_buf); esp_vhci_host_send_packet(hci_cmd_buf, sz); } static void hci_cmd_send_ble_adv_start(void) { uint16_t sz = make_cmd_ble_set_adv_enable (hci_cmd_buf, 1); esp_vhci_host_send_packet(hci_cmd_buf, sz); } static void hci_cmd_send_ble_set_adv_param(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 = make_cmd_ble_set_adv_param(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); esp_vhci_host_send_packet(hci_cmd_buf, sz); } static void hci_cmd_send_ble_set_adv_data(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 | BR_EDR_NOT_SUPPORTED 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; // URL Scheme 'https://' 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 = make_cmd_ble_set_adv_data(hci_cmd_buf, adv_data_len, (uint8_t *)adv_data); esp_vhci_host_send_packet(hci_cmd_buf, sz); } /* * @brief: send HCI commands to perform BLE advertising; */ void bleAdvtTask(void *pvParameters) { int cmd_cnt = 0; bool send_avail = false; esp_vhci_host_register_callback(&vhci_host_cb); printf("BLE advt task start\n"); while (1) { vTaskDelay(5000 / portTICK_PERIOD_MS); send_avail = esp_vhci_host_check_send_available(); if (send_avail) { switch (cmd_cnt) { case 0: hci_cmd_send_reset(); ++cmd_cnt; break; case 1: hci_cmd_send_ble_set_adv_param(); ++cmd_cnt; break; case 2: hci_cmd_send_ble_set_adv_data(); ++cmd_cnt; break; case 3: hci_cmd_send_ble_adv_start(); ++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; esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT(); ret = esp_bt_controller_init(&bt_cfg); if (ret) { ESP_LOGE(GATTS_TAG, "%s initialize controller failed\n", __func__); return 1; } ret = esp_bt_controller_enable(ESP_BT_MODE_BTDM); if (ret) { ESP_LOGE(GATTS_TAG, "%s enable controller failed\n", __func__); return 1; } xTaskCreatePinnedToCore(&bleAdvtTask, "bleAdvtTask", 2048, NULL, 5, NULL, 0); return 0; }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- 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> <!-- ========= START OF TOP NAVBAR ======= --> <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/JRPropertyExpression.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="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); 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> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <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"> <!-- =========== FIELD SUMMARY =========== --> <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> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <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> <!-- ========== METHOD SUMMARY =========== --> <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="methods_inherited_from_class_java.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"> <!-- ============ FIELD DETAIL =========== --> <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> <!-- ========= CONSTRUCTOR DETAIL ======== --> <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> <!-- ============ METHOD DETAIL ========== --> <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> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><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="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/JRPropertyExpression.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="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); 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> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <span style="font-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:8pt;font-style:normal;color:#000000;">&copy; 2001 - 2016 TIBCO Software Inc. <a href="http://www.jaspersoft.com" target="_blank" style="color:#000000;">www.jaspersoft.com</a></span> </small></p> </body> </html>
Java
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(IMP_EXPENSIVE_TIMEOUT 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(imp_add_python_tests 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}) get_filename_component(path ${test} ABSOLUTE) GET_FILENAME_COMPONENT(name ${test} NAME) add_test("${modulename}-${name}" ${IMP_TEST_SETUP} python ${path} ${IMP_TEST_ARGUMENTS}) set_tests_properties("${modulename}-${name}" PROPERTIES LABELS "${modulename}-${ttype}-python-${length}") set_tests_properties("${modulename}-${name}" PROPERTIES TIMEOUT ${timeout}) set_tests_properties("${modulename}-${name}" PROPERTIES COST ${IMP_${length}_COST}) if(DEFINED IMP_TESTS_PROPERTIES) set_tests_properties("${modulename}-${name}" PROPERTIES ${IMP_TESTS_PROPERTIES}) endif() endforeach(test) endfunction(imp_add_python_tests) 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}) GET_FILENAME_COMPONENT(name ${test} NAME) GET_FILENAME_COMPONENT(name_we ${test} NAME_WE) add_executable("${modulename}-${name}" ${test}) target_link_libraries("${modulename}-${name}" ${IMP_LINK_LIBRARIES}) set_target_properties("${modulename}-${name}" PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${output}" OUTPUT_NAME ${name_we}) set_property(TARGET "${modulename}-${name}" PROPERTY FOLDER "${modulename}") add_test("${modulename}-${name}" ${IMP_TEST_SETUP} ${output}/${name_we}${CMAKE_EXECUTABLE_SUFFIX} ${IMP_TEST_ARGUMENTS}) set_tests_properties("${modulename}-${name}" PROPERTIES LABELS "${modulename}-${ttype}-cpp-${length}") if(DEFINED IMP_TESTS_PROPERTIES) set_tests_properties("${modulename}-${name}" PROPERTIES ${IMP_TESTS_PROPERTIES}) endif() set_tests_properties("${modulename}-${name}" PROPERTIES TIMEOUT ${timeout}) set_tests_properties("${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}) GET_FILENAME_COMPONENT(name ${test} NAME) GET_FILENAME_COMPONENT(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) imp_add_python_tests(${modulename} "CHEAP" ${ttype} "${py_cheap}") imp_add_python_tests(${modulename} "MEDIUM" ${ttype} "${py_medium}") imp_add_python_tests(${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)
Java
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- qdeclarativepolygonmapitem.cpp --> <title>List of All Members for MapPolygon | Qt Location 5.7</title> <link rel="stylesheet" type="text/css" href="style/offline-simple.css" /> <script type="text/javascript"> window.onload = function(){document.getElementsByTagName("link").item(0).setAttribute("href", "style/offline.css");}; </script> </head> <body> <div class="header" id="qtdocheader"> <div class="main"> <div class="main-rounded"> <div class="navigationbar"> <table><tr> <td ><a href="../qtdoc/supported-platforms-and-configurations.html#qt-5-7">Qt 5.7</a></td><td ><a href="qtlocation-index.html">Qt Location</a></td><td ><a href="qtlocation-qmlmodule.html">QML Types</a></td><td >List of All Members for MapPolygon</td></tr></table><table class="buildversion"><tr> <td id="buildversion" width="100%" align="right">Qt 5.7.0 Reference Documentation</td> </tr></table> </div> </div> <div class="content"> <div class="line"> <div class="content mainContent"> <div class="sidebar"><div class="sidebar-content" id="sidebar-content"></div></div> <h1 class="title">List of All Members for MapPolygon</h1> <p>This is the complete list of members for <a href="qml-qtlocation-mappolygon.html">MapPolygon</a>, including inherited members.</p> <ul> <li class="fn"><b><b><a href="qml-qtlocation-mappolygon.html#border.color-prop">border.color</a></b></b> : color</li> <li class="fn"><b><b><a href="qml-qtlocation-mappolygon.html#border.width-prop">border.width</a></b></b> : int</li> <li class="fn"><b><b><a href="qml-qtlocation-mappolygon.html#color-prop">color</a></b></b> : color</li> <li class="fn"><b><b><a href="qml-qtlocation-mappolygon.html#path-prop">path</a></b></b> : list&lt;coordinate&gt;</li> <li class="fn">void <b><b><a href="qml-qtlocation-mappolygon.html#addCoordinate-method">addCoordinate</a></b></b>(<i>coordinate</i>)</li> <li class="fn">void <b><b><a href="qml-qtlocation-mappolygon.html#removeCoordinate-method">removeCoordinate</a></b></b>(<i>coordinate</i>)</li> </ul> </div> </div> </div> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners.<br> The documentation provided herein is licensed under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.<br> Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners. </p> </div> </body> </html>
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--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> <!-- ========= START OF TOP NAVBAR ======= --> <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> <!-- ========= END OF TOP NAVBAR ========= --> <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> <!-- ======= START OF BOTTOM NAVBAR ====== --> <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="navbar_bottom_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_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
Java
/* Copyright © 2007, 2008, 2009, 2010, 2011 Vladimír Vondruš <mosra@centrum.cz> This file is part of Kompas. Kompas is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 3 only, as published by the Free Software Foundation. Kompas is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License version 3 for more details. */ #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 orphanDirectoryCount = 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)) ++orphanDirectoryCount; } } } Debug() << "Optimization removed" << orphanEntryCount << "orphan entries," << orphanFileCount << "orphan files and" << orphanDirectoryCount << "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)); } }}
Java
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(); } } }
Java
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.get_format_from_width(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
Java
// Decompiled with JetBrains decompiler // Type: StartupSceneAnimDriver // Assembly: Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // MVID: 19851F1B-4780-4223-BA01-2C20F2CD781E // 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 StartupSceneAnimDriver : MonoBehaviour { public WBSpriteText LoadingString; public StartupSceneAnimDriver() { base.\u002Ector(); } [DebuggerHidden] private IEnumerator Start() { // ISSUE: object of a compiler-generated type is created return (IEnumerator) new StartupSceneAnimDriver.\u003CStart\u003Ec__Iterator95() { \u003C\u003Ef__this = this }; } }
Java
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; // https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x804 上介绍了“空白页”项模板 namespace Minedrink_UWP { /// <summary> /// 可用于自身或导航至 Frame 内部的空白页。 /// </summary> public sealed partial class MainPage : Page { public Rect TogglePaneButtonRect { 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.CheckTogglePaneButtonSizeChanged(); var titleBar = Windows.ApplicationModel.Core.CoreApplication.GetCurrentView().TitleBar; titleBar.IsVisibleChanged += TitleBar_IsVisibleChanged; }; this.RootSplitView.RegisterPropertyChangedCallback(SplitView.DisplayModeProperty, (s, a) => { //确保当SplitView的显示模式改变时,更新TogglePaneButton的尺寸 this.CheckTogglePaneButtonSizeChanged(); }); SystemNavigationManager.GetForCurrentView().BackRequested += SyatemNavigationMaganger_BackRequested; SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible; NavMenuList.ItemsSource = navlist; } private void SyatemNavigationMaganger_BackRequested(object sender, BackRequestedEventArgs 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完成或进入平板模式, /// 确保标题栏和App内容间的top 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 TitleBar_IsVisibleChanged(Windows.ApplicationModel.Core.CoreApplicationViewTitleBar sender, object args) { if (!this.isPaddingAdd && sender.IsVisible) { //在标题和内容间增加额外的Padding double extraPadding = (Double)App.Current.Resources["DesktopWindowTopPadding"]; 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 CheckTogglePaneButtonSizeChanged() { if (RootSplitView.DisplayMode == SplitViewDisplayMode.Inline || RootSplitView.DisplayMode == SplitViewDisplayMode.Overlay) { var transform = this.TogglePaneButton.TransformToVisual(this); var rect = transform.TransformBounds(new Rect(0, 0, this.TogglePaneButton.ActualWidth, this.TogglePaneButton.ActualHeight)); this.TogglePaneButtonRect = rect; } else { this.TogglePaneButtonRect = new Rect(); } var handler = this.TogglePaneButtonRectChanged; if (handler != null) { // handler(this, this.TogglePaneButtonRect); handler.DynamicInvoke(this, this.TogglePaneButtonRect); } } //private void MainPage_Loaded(object sender, RoutedEventArgs e) //{ // throw new NotImplementedException(); //} 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) { FocusNavigationDirection direction = FocusNavigationDirection.None; switch (e.Key) { case Windows.System.VirtualKey.Left: case Windows.System.VirtualKey.GamepadDPadLeft: case Windows.System.VirtualKey.GamepadLeftThumbstickLeft: case Windows.System.VirtualKey.NavigationLeft: direction = FocusNavigationDirection.Left; break; case Windows.System.VirtualKey.Right: case Windows.System.VirtualKey.GamepadDPadRight: case Windows.System.VirtualKey.GamepadLeftThumbstickRight: case Windows.System.VirtualKey.NavigationRight: direction = FocusNavigationDirection.Right; break; case Windows.System.VirtualKey.Up: case Windows.System.VirtualKey.GamepadDPadUp: case Windows.System.VirtualKey.GamepadLeftThumbstickUp: case Windows.System.VirtualKey.NavigationUp: direction = FocusNavigationDirection.Up; break; case Windows.System.VirtualKey.Down: case Windows.System.VirtualKey.GamepadDPadDown: case Windows.System.VirtualKey.GamepadLeftThumbstickDown: case Windows.System.VirtualKey.NavigationDown: direction = FocusNavigationDirection.Down; break; } if (direction != FocusNavigationDirection.None) { var contorl = FocusManager.FindNextFocusableElement(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 RootSplitView_PaneClosed(SplitView sender, object args) { NavPaneDivider.Visibility = Visibility.Collapsed; // Prevent focus from moving to elements when they're not visible on screen FeedbackNavPaneButton.IsTabStop = false; SettingsNavPaneButton.IsTabStop = false; } /// <summary> ///通过使用每个项目的关联标签在每个容器上设置AutomationProperties.Name来启用每个导航菜单项上的辅助功能。 /// Enable accessibility on each nav menu item by setting the AutomationProperties.Name on each container /// using the associated Label of each item. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void NavMenuList_ContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args) { if (!args.InRecycleQueue && args.Item != null && args.Item is NavMenuItem) { args.ItemContainer.SetValue(AutomationProperties.NameProperty, ((NavMenuItem)args.Item).Label); } else { args.ItemContainer.ClearValue(AutomationProperties.NameProperty); } } /// <summary> /// 选中导航按钮项后调用 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void NavMenuList_ItemInvoked(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.CurrentSourcePageType) { 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, NavigatingCancelEventArgs 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 TogglePaneButton_Unchecked(object sender, RoutedEventArgs e) { this.CheckTogglePaneButtonSizeChanged(); } private void TogglePaneButton_Checked(object sender, RoutedEventArgs e) { NavPaneDivider.Visibility = Visibility.Visible; this.CheckTogglePaneButtonSizeChanged(); FeedbackNavPaneButton.IsTabStop = true; SettingsNavPaneButton.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); // StreamSocketListener listener = new StreamSocketListener(); // listener.ConnectionReceived += Listener_ConnectionReceived; // //如果需要,调整监听器的控制选项,然后再进行绑定操作。这些选项将被自动应用到连接的StreamSockets, // //这些连接是由传入的连接引起的(即作为ConnectionReceived事件处理程序的参数传递的)。 // //参考StreamSocketListenerControl类'MSDN 有关控制选项的完整列表的文档。 // listener.Control.KeepAlive = false; // //保存Socket,以便随后使用 // CoreApplication.Properties.Add("listener", listener); // //开始监听操作 // try // { // await listener.BindServiceNameAsync("8080"); // Debug.WriteLine("Listening......"); // } // catch (Exception) // { // throw; // } //} //private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs 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.NullReferenceException // 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> TogglePaneButtonRectChanged; /// <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; // } //} }
Java
//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // 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 { // ~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 // pseudo-destructor-expression 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 pseudo-destructor-name (5.2.4) contains a nested-name-specifier, // the type-names are looked up as types in the scope designated by the // nested-name-specifier. In a qualified-id of the form: // // ::[opt] nested-name-specifier ̃ class-name // // where the nested-name-specifier designates a namespace scope, and in // a qualified-id of the form: // // ::opt nested-name-specifier class-name :: ̃ class-name // // the class-names are looked up as types in the scope designated by // the nested-name-specifier. // // Here, we check the first case (completely) and determine whether the // code below is permitted to look at the prefix of the // nested-name-specifier. 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 = isDependentScopeSpecifier(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.hasSameUnqualifiedType(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 // nested-name-specifier (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 (ClassTemplateSpecializationDecl *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { if (Spec->getSpecializedTemplate()->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 TemplateSpecializationType *SpecType = MemberOfType->getAs<TemplateSpecializationType>()) { 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 (DependentTemplateName *DepTemplate = SpecName.getAsDependentTemplateName()) { 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::err_ident_in_pseudo_dtor_not_a_type) << &II; else Diag(NameLoc, diag::err_destructor_class_name); 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.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(), Quals); if (T->getAs<RecordType>() && RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 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 isUnevaluatedOperand = 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::err_incomplete_typeid)) 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()) { isUnevaluatedOperand = 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.getUnqualifiedArrayType(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 (isUnevaluatedOperand) ExprEvalContexts.back().Context = Unevaluated; return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E, SourceRange(TypeidLoc, RParenLoc))); } /// ActOnCXXTypeidOfType - 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::err_need_header_before_typeid)); 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::err_need_header_before_typeid)); 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.getTrivialTypeSourceInfo(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)); } /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. ExprResult Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc)); } /// ActOnCXXThrow - Parse throw expressions. ExprResult Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) { if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex)) return ExprError(); return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc)); } /// CheckCXXThrowOperand - Validate the operand of a throw. bool Sema::CheckCXXThrowOperand(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)); DefaultFunctionArrayConversion(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::err_throw_incomplete_ptr : diag::err_throw_incomplete) << E->getSourceRange())) return true; if (RequireNonAbstractType(ThrowLoc, E->getType(), PDiag(diag::err_throw_abstract_type) << 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 = PerformCopyInitialization(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->hasTrivialDestructor()) return false; CXXDestructorDecl *Destructor = const_cast<CXXDestructorDecl*>(LookupDestructor(RD)); if (!Destructor) return false; MarkDeclarationReferenced(E->getExprLoc(), Destructor); CheckDestructorAccess(E->getExprLoc(), Destructor, PDiag(diag::err_access_dtor_exception) << 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 = getFunctionLevelDeclContext(); 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::err_invalid_this_use)); } /// ActOnCXXTypeConstructExpr - 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::ActOnCXXTypeConstructExpr(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.getTrivialTypeSourceInfo(Ty, SourceLocation()); unsigned NumExprs = exprs.size(); Expr **Exprs = (Expr**)exprs.get(); SourceLocation TyBeginLoc = TypeRange.getBegin(); SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc); if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) { exprs.release(); return Owned(CXXUnresolvedConstructExpr::Create(Context, TypeRange.getBegin(), Ty, LParenLoc, Exprs, NumExprs, RParenLoc)); } if (Ty->isArrayType()) return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type) << FullRange); if (!Ty->isVoidType() && RequireCompleteType(TyBeginLoc, Ty, PDiag(diag::err_invalid_incomplete_type_use) << FullRange)) return ExprError(); if (RequireNonAbstractType(TyBeginLoc, Ty, diag::err_allocation_of_abstract_type)) 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(CXXFunctionalCastExpr::Create(Context, Ty.getNonLValueExprType(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); InitializationSequence 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::err_builtin_func_cast_more_than_one_arg) << FullRange); assert(NumExprs == 0 && "Expected 0 expressions"); // C++ [expr.type.conv]p2: // The expression T(), where T is a simple-type-specifier 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) CXXScalarValueInitExpr(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::err_static_illegal_in_new) << D.getSourceRange()); if (!Chunk.Arr.NumElts) return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) << 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->isIntegerConstantExpr(Context)) { Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst) << NumElts->getSourceRange(); return ExprError(); } } } } //FIXME: Store TypeSourceInfo in CXXNew expression. TypeSourceInfo *TInfo = GetTypeForDeclarator(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.getAsConstantArrayType(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 direct-new-declarator shall have integral // or enumeration type with a non-negative value." if (ArraySize && !ArraySize->isTypeDependent()) { QualType SizeType = ArraySize->getType(); ExprResult ConvertedSize = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize, PDiag(diag::err_array_size_not_integral), PDiag(diag::err_array_size_incomplete_type) << ArraySize->getSourceRange(), PDiag(diag::err_array_size_explicit_conversion), PDiag(diag::note_array_size_conversion), PDiag(diag::err_array_size_ambiguous_conversion), PDiag(diag::note_array_size_conversion), PDiag(getLangOptions().CPlusPlus0x? 0 : diag::ext_array_size_conversion)); if (ConvertedSize.isInvalid()) return ExprError(); ArraySize = ConvertedSize.take(); SizeType = ArraySize->getType(); if (!SizeType->isIntegralOrEnumerationType()) 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->isIntegerConstantExpr(Value, Context, 0, false)) { if (Value < llvm::APSInt( llvm::APInt::getNullValue(Value.getBitWidth()), Value.isUnsigned())) return ExprError(Diag(ArraySize->getSourceRange().getBegin(), diag::err_typecheck_negative_array_size) << ArraySize->getSourceRange()); if (!AllocType->isDependentType()) { unsigned ActiveSizeBits = ConstantArrayType::getNumAddressingBits(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::ext_new_paren_array_nonconst) << 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::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) && FindAllocationFunctions(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 : VariadicDoesNotApply; if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 1, PlaceArgs, NumPlaceArgs, AllPlaceArgs, CallType)) return ExprError(); NumPlaceArgs = AllPlaceArgs.size(); if (NumPlaceArgs > 0) PlaceArgs = &AllPlaceArgs[0]; } bool Init = ConstructorLParen.isValid(); // --- Choosing a constructor --- CXXConstructorDecl *Constructor = 0; Expr **ConsArgs = (Expr**)ConstructorArgs.get(); unsigned NumConsArgs = ConstructorArgs.size(); ASTOwningVector<Expr*> ConvertedConstructorArgs(*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::err_new_array_init_args) << InitRange; return ExprError(); } if (!AllocType->isDependentType() && !Expr::hasAnyTypeDependentArguments(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 direct-initialization. : InitializationKind::CreateDirect(TypeLoc, ConstructorLParen, ConstructorRParen); InitializedEntity Entity = InitializedEntity::InitializeNew(StartLoc, AllocType); InitializationSequence 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 (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(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) ConvertedConstructorArgs.push_back(A->Retain()); } else { // Take the converted initializer. ConvertedConstructorArgs.push_back(FullInit.release()); } } else { // No initialization required. } // Take the converted arguments and use them for the new expression. NumConsArgs = ConvertedConstructorArgs.size(); ConsArgs = (Expr **)ConvertedConstructorArgs.take(); } // Mark the new and delete operators as referenced. if (OperatorNew) MarkDeclarationReferenced(StartLoc, OperatorNew); if (OperatorDelete) MarkDeclarationReferenced(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::err_new_incomplete_type) << R)) return true; else if (RequireNonAbstractType(Loc, AllocType, diag::err_allocation_of_abstract_type)) return true; return false; } /// \brief Determine whether the given function is a non-placement /// deallocation function. static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) { if (FD->isInvalidDecl()) return false; if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) return Method->isUsualDeallocationFunction(); return ((FD->getOverloadedOperator() == OO_Delete || FD->getOverloadedOperator() == OO_Array_Delete) && FD->getNumParams() == 1); } /// FindAllocationFunctions - Finds the overloads of operator new and delete /// that are appropriate for the allocation. bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, bool UseGlobal, QualType AllocType, bool IsArray, Expr **PlaceArgs, unsigned NumPlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete) { // --- Choosing an allocation function --- // 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 // function’s name is operator new and the deallocation function’s // name is operator delete. If the allocated type is an array // type, the allocation function’s name is operator new[] and the // deallocation function’s name is operator delete[]. 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 (FindAllocationOverload(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. DeclareGlobalNewDelete(); DeclContext *TUDecl = Context.getTranslationUnitDecl(); if (FindAllocationOverload(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; } // FindAllocationOverload 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 // deallocation function’s name is looked up in the global // scope. Otherwise, if the allocated type is a class type T or an // array thereof, the deallocation function’s name is looked up in // 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 // deallocation function’s name is looked up in the global scope. 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()) { DeclareGlobalNewDelete(); LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); } 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 ExpectedFunctionType; { 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)); ExpectedFunctionType = 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 (FunctionTemplateDecl *FnTmpl = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { // Perform template argument deduction to try to match the // expected function type. TemplateDeductionInfo Info(Context, StartLoc); if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info)) continue; } else Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); if (Context.hasSameType(Fn->getType(), ExpectedFunctionType)) 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 (isNonPlacementDeallocationFunction(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 && isNonPlacementDeallocationFunction(OperatorDelete)) { Diag(StartLoc, diag::err_placement_new_non_placement_delete) << SourceRange(PlaceArgs[0]->getLocStart(), PlaceArgs[NumPlaceArgs - 1]->getLocEnd()); Diag(OperatorDelete->getLocation(), diag::note_previous_decl) << DeleteName; } else { CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), Matches[0].first); } } return false; } /// FindAllocationOverload - Find an fitting overload for the allocation /// function in the specified scope. bool Sema::FindAllocationOverload(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::err_ovl_no_viable_function_in_call) << Name << Range; } if (R.isAmbiguous()) return true; R.suppressDiagnostics(); OverloadCandidateSet 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 (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), /*ExplicitTemplateArgs=*/0, Args, NumArgs, Candidates, /*SuppressUserConversions=*/false); continue; } FunctionDecl *Fn = cast<FunctionDecl>(D); AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates, /*SuppressUserConversions=*/false); } // Do the resolution. OverloadCandidateSet::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 = PerformCopyInitialization(InitializedEntity::InitializeParameter( FnDecl->getParamDecl(i)), SourceLocation(), Owned(Args[i]->Retain())); if (Result.isInvalid()) return true; Args[i] = Result.takeAs<Expr>(); } Operator = FnDecl; CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl); return false; } case OR_No_Viable_Function: Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) << Name << Range; Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); return true; case OR_Ambiguous: Diag(StartLoc, diag::err_ovl_ambiguous_call) << Name << Range; Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs); return true; case OR_Deleted: Diag(StartLoc, diag::err_ovl_deleted_call) << Best->Function->isDeleted() << Name << Range; Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); return true; } assert(false && "Unreachable, bad result from BestViableFunction"); return true; } /// DeclareGlobalNewDelete - 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::DeclareGlobalNewDelete() { if (GlobalNewDeleteDeclared) 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, getOrCreateStdNamespace(), SourceLocation(), &PP.getIdentifierTable().get("bad_alloc"), SourceLocation(), 0); getStdBadAlloc()->setImplicit(true); } GlobalNewDeleteDeclared = true; QualType VoidPtr = Context.getPointerType(Context.VoidTy); QualType SizeT = Context.getSizeType(); bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew; DeclareGlobalAllocationFunction( Context.DeclarationNames.getCXXOperatorName(OO_New), VoidPtr, SizeT, AssumeSaneOperatorNew); DeclareGlobalAllocationFunction( Context.DeclarationNames.getCXXOperatorName(OO_Array_New), VoidPtr, SizeT, AssumeSaneOperatorNew); DeclareGlobalAllocationFunction( Context.DeclarationNames.getCXXOperatorName(OO_Delete), Context.VoidTy, VoidPtr); DeclareGlobalAllocationFunction( Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), Context.VoidTy, VoidPtr); } /// DeclareGlobalAllocationFunction - Declares a single implicit global /// allocation function if it doesn't already exist. void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, QualType Argument, bool AddMallocAttr) { DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); // 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 HasBadAllocExceptionSpec = (Name.getCXXOverloadedOperator() == OO_New || Name.getCXXOverloadedOperator() == OO_Array_New); if (HasBadAllocExceptionSpec) { assert(StdBadAlloc && "Must have std::bad_alloc declared"); BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); } QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0, true, false, HasBadAllocExceptionSpec? 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.getTranslationUnitDecl()->addDecl(Alloc); } bool Sema::FindDeallocationFunction(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<FunctionTemplateDecl>(ND)) continue; if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction()) Matches.push_back(F.getPair()); } // There's exactly one suitable operator; pick it. if (Matches.size() == 1) { Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl()); CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(), Matches[0]); return false; // We found multiple suitable operators; complain about the ambiguity. } else if (!Matches.empty()) { Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) << Name << RD; for (llvm::SmallVectorImpl<DeclAccessPair>::iterator F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F) Diag((*F)->getUnderlyingDecl()->getLocation(), diag::note_member_declared_here) << Name; return true; } // We did find operator delete/operator delete[] declarations, but // none of them were suitable. if (!Found.empty()) { Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) << Name << RD; for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); F != FEnd; ++F) Diag((*F)->getUnderlyingDecl()->getLocation(), diag::note_member_declared_here) << Name; return true; } // Look for a global declaration. DeclareGlobalNewDelete(); DeclContext *TUDecl = Context.getTranslationUnitDecl(); CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation()); Expr* DeallocArgs[1]; DeallocArgs[0] = &Null; if (FindAllocationOverload(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::err_delete_incomplete_class_type))) return ExprError(); llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions; CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions(); 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<FunctionTemplateDecl>(D)) continue; CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); QualType ConvType = Conv->getConversionType().getNonReferenceType(); if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) ObjectPtrConversions.push_back(Conv); } if (ObjectPtrConversions.size() == 1) { // We have a single conversion to a pointer-to-object type. Perform // that conversion. // TODO: don't redo the conversion calculation. if (!PerformImplicitConversion(Ex, ObjectPtrConversions.front()->getConversionType(), AA_Converting)) { Type = Ex->getType(); } } else if (ObjectPtrConversions.size() > 1) { Diag(StartLoc, diag::err_ambiguous_delete_operand) << Type << Ex->getSourceRange(); for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) NoteOverloadCandidate(ObjectPtrConversions[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::ext_delete_void_ptr_operand) << 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::warn_delete_incomplete) << 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 && FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete)) return ExprError(); if (!RD->hasTrivialDestructor()) if (const CXXDestructorDecl *Dtor = LookupDestructor(RD)) MarkDeclarationReferenced(StartLoc, const_cast<CXXDestructorDecl*>(Dtor)); } if (!OperatorDelete) { // Look for a global declaration. DeclareGlobalNewDelete(); DeclContext *TUDecl = Context.getTranslationUnitDecl(); if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName, &Ex, 1, TUDecl, /*AllowMissing=*/false, OperatorDelete)) return ExprError(); } MarkDeclarationReferenced(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::CheckConditionVariable(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::err_invalid_use_of_function_type) << ConditionVar->getSourceRange()); else if (T->isArrayType()) return ExprError(Diag(ConditionVar->getLocation(), diag::err_invalid_use_of_array_type) << ConditionVar->getSourceRange()); Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar, ConditionVar->getLocation(), ConditionVar->getType().getNonReferenceType()); if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc)) return ExprError(); return Owned(Condition); } /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. bool Sema::CheckCXXBooleanCondition(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 PerformContextuallyConvertToBool(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::IsStringLiteralToNonConstPointerConversion(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 BuildCXXCastArgument(Sema &S, SourceLocation CastLoc, QualType Ty, CastKind Kind, CXXMethodDecl *Method, Expr *From) { switch (Kind) { default: assert(0 && "Unhandled cast kind!"); case CK_ConstructorConversion: { ASTOwningVector<Expr*> ConstructorArgs(S); if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method), MultiExprArg(&From, 1), CastLoc, ConstructorArgs)) return ExprError(); ExprResult Result = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method), move_arg(ConstructorArgs), /*ZeroInit*/ false, CXXConstructExpr::CK_Complete); if (Result.isInvalid()) return ExprError(); return S.MaybeBindToTemporary(Result.takeAs<Expr>()); } case CK_UserDefinedConversion: { 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.BuildCXXMemberCallExpr(From, Method, Method); return S.MaybeBindToTemporary(CE); } } } /// PerformImplicitConversion - 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::PerformImplicitConversion(Expr *&From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, bool IgnoreBaseAccess) { switch (ICS.getKind()) { case ImplicitConversionSequence::StandardConversion: if (PerformImplicitConversion(From, ToType, ICS.Standard, Action, IgnoreBaseAccess)) return true; break; case ImplicitConversionSequence::UserDefinedConversion: { FunctionDecl *FD = ICS.UserDefined.ConversionFunction; CastKind CastKind = CK_Unknown; QualType BeforeToType; if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { CastKind = CK_UserDefinedConversion; // 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 = CK_ConstructorConversion; // 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 (PerformImplicitConversion(From, BeforeToType, ICS.UserDefined.Before, AA_Converting, IgnoreBaseAccess)) return true; } ExprResult CastArg = BuildCXXCastArgument(*this, From->getLocStart(), ToType.getNonReferenceType(), CastKind, cast<CXXMethodDecl>(FD), From); if (CastArg.isInvalid()) return true; From = CastArg.takeAs<Expr>(); return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, AA_Converting, IgnoreBaseAccess); } case ImplicitConversionSequence::AmbiguousConversion: ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), PDiag(diag::err_typecheck_ambiguous_condition) << From->getSourceRange()); return true; case ImplicitConversionSequence::EllipsisConversion: assert(false && "Cannot perform an ellipsis conversion"); return false; case ImplicitConversionSequence::BadConversion: return true; } // Everything went well. return false; } /// PerformImplicitConversion - 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::PerformImplicitConversion(Expr *&From, QualType ToType, const StandardConversionSequence& 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 (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor), MultiExprArg(*this, &From, 1), /*FIXME:ConstructLoc*/SourceLocation(), ConstructorArgs)) return true; ExprResult FromResult = BuildCXXConstructExpr(/*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 = BuildCXXConstructExpr(/*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 = ResolveAddressOfOverloadedFunction(From, ToType, true, Found); if (!Fn) return true; if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin())) return true; From = FixOverloadedFunctionReference(From, Found, Fn); FromType = From->getType(); } // Perform the first implicit conversion. switch (SCS.First) { case ICK_Identity: case ICK_Lvalue_To_Rvalue: // Nothing to do. break; case ICK_Array_To_Pointer: FromType = Context.getArrayDecayedType(FromType); ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay); break; case ICK_Function_To_Pointer: FromType = Context.getPointerType(FromType); ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay); 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 (CheckExceptionSpecCompatibility(From, ToType)) return true; // Nothing else to do. break; case ICK_NoReturn_Adjustment: // If both sides are functions (or pointers/references to them), there could // be incompatible exception declarations. if (CheckExceptionSpecCompatibility(From, ToType)) return true; ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false), CK_NoOp); break; case ICK_Integral_Promotion: case ICK_Integral_Conversion: ImpCastExprToType(From, ToType, CK_IntegralCast); break; case ICK_Floating_Promotion: case ICK_Floating_Conversion: ImpCastExprToType(From, ToType, CK_FloatingCast); break; case ICK_Complex_Promotion: case ICK_Complex_Conversion: ImpCastExprToType(From, ToType, CK_Unknown); break; case ICK_Floating_Integral: if (ToType->isRealFloatingType()) ImpCastExprToType(From, ToType, CK_IntegralToFloating); else ImpCastExprToType(From, ToType, CK_FloatingToIntegral); break; case ICK_Compatible_Conversion: ImpCastExprToType(From, ToType, CK_NoOp); break; case ICK_Pointer_Conversion: { if (SCS.IncompatibleObjC) { // Diagnose incompatible Objective-C conversions Diag(From->getSourceRange().getBegin(), diag::ext_typecheck_convert_incompatible_pointer) << From->getType() << ToType << Action << From->getSourceRange(); } CastKind Kind = CK_Unknown; CXXCastPath BasePath; if (CheckPointerConversion(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 (CheckMemberPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess)) return true; if (CheckExceptionSpecCompatibility(From, ToType)) return true; ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath); break; } case ICK_Boolean_Conversion: { CastKind Kind = CK_Unknown; if (FromType->isMemberPointerType()) Kind = CK_MemberPointerToBoolean; ImpCastExprToType(From, Context.BoolTy, Kind); break; } case ICK_Derived_To_Base: { CXXCastPath BasePath; if (CheckDerivedToBaseConversion(From->getType(), ToType.getNonReferenceType(), From->getLocStart(), From->getSourceRange(), &BasePath, IgnoreBaseAccess)) return true; ImpCastExprToType(From, ToType.getNonReferenceType(), CK_DerivedToBase, CastCategory(From), &BasePath); break; } case ICK_Vector_Conversion: 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 ICK_Lvalue_To_Rvalue: case ICK_Array_To_Pointer: case ICK_Function_To_Pointer: case ICK_Qualification: case ICK_Num_Conversion_Kinds: 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.getNonLValueExprType(Context), CK_NoOp, VK); if (SCS.DeprecatedStringLiteralToCharPtr) Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion) << 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); // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html // 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::err_incomplete_type_used_in_type_trait_expr)) 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::CheckPointerToMemberOperands( 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::err_memptr_rhs_to_incomplete)) 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.hasSameUnqualifiedType(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<CXXScalarValueInitExpr>(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::err_pointer_to_member_type) << 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 "MemberFunctionClosureType" 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.getLValueReferenceType(ToType); InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); if (InitSeq.isDirectReferenceBinding()) { 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.isAtLeastAsQualifiedAs(FTy)) { InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); if (InitSeq.getKind() != InitializationSequence::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); InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); HaveConversion = InitSeq.getKind() != InitializationSequence::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 FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS, SourceLocation Loc) { Expr *Args[2] = { LHS, RHS }; OverloadCandidateSet CandidateSet(Loc); Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet); OverloadCandidateSet::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.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0], Best->Conversions[0], Sema::AA_Converting) || Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1], Best->Conversions[1], Sema::AA_Converting)) break; return false; case OR_No_Viable_Function: Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) << LHS->getType() << RHS->getType() << LHS->getSourceRange() << RHS->getSourceRange(); return true; case OR_Ambiguous: Self.Diag(Loc, diag::err_conditional_ambiguous_ovl) << 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 ConvertForConditional(Sema &Self, Expr *&E, QualType T) { InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(), SourceLocation()); InitializationSequence 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::CXXCheckConditionalOperands(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 (CheckCXXBooleanCondition(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 ... DefaultFunctionArrayLvalueConversion(LHS); DefaultFunctionArrayLvalueConversion(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::err_conditional_void_nonvoid) << (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())) { ImplicitConversionSequence 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::err_conditional_ambiguous) << 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 (ConvertForConditional(*this, LHS, L2RType)) return QualType(); LTy = LHS->getType(); } else if (HaveR2L) { if (ConvertForConditional(*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 (FindConditionalOverload(*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. DefaultFunctionArrayLvalueConversion(LHS); DefaultFunctionArrayLvalueConversion(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 = PerformCopyInitialization(Entity, SourceLocation(), Owned(LHS)); if (LHSCopy.isInvalid()) return QualType(); ExprResult RHSCopy = PerformCopyInitialization(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()) { UsualArithmeticConversions(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 NonStandardCompositeType = false; QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS, isSFINAEContext()? 0 : &NonStandardCompositeType); if (!Composite.isNull()) { if (NonStandardCompositeType) Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands_nonstandard) << LTy << RTy << Composite << LHS->getSourceRange() << RHS->getSourceRange(); return Composite; } // Similarly, attempt to find composite type of two objective-c pointers. Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); if (!Composite.isNull()) return Composite; Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) << 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 NonStandardCompositeType 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 *NonStandardCompositeType /// will be set true. QualType Sema::FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool *NonStandardCompositeType) { if (NonStandardCompositeType) *NonStandardCompositeType = 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->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { if (T2->isMemberPointerType()) ImpCastExprToType(E1, T2, CK_NullToMemberPointer); else ImpCastExprToType(E1, T2, CK_IntegralToPointer); return T2; } if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { if (T1->isMemberPointerType()) ImpCastExprToType(E2, T1, CK_NullToMemberPointer); else ImpCastExprToType(E2, T1, CK_IntegralToPointer); 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> ContainingClassVector; ContainingClassVector 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 (NonStandardCompositeType && 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 (NonStandardCompositeType && 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 && NonStandardCompositeType) { // 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; *NonStandardCompositeType = true; } } } // Rewrap the composites as pointers or member pointers with the union CVRs. ContainingClassVector::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.getMemberPointerType( Context.getQualifiedType(Composite1, Quals), MOC->first); Composite2 = Context.getMemberPointerType( 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()); InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1); InitializationSequence 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); InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1); InitializationSequence 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); InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1); InitializationSequence 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::MaybeBindToTemporary(Expr *E) { if (!Context.getLangOptions().CPlusPlus) return Owned(E); assert(!isa<CXXBindTemporaryExpr>(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->hasTrivialDestructor()) return Owned(E); CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD)); ExprTemporaries.push_back(Temp); if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { MarkDeclarationReferenced(E->getExprLoc(), Destructor); CheckDestructorAccess(E->getExprLoc(), Destructor, PDiag(diag::err_access_dtor_temp) << E->getType()); } // FIXME: Add the temporary to the temporaries vector. return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E)); } Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) { assert(SubExpr && "sub expression can't be null!"); // Check any implicit conversions within the expression. CheckImplicitConversions(SubExpr); unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries; assert(ExprTemporaries.size() >= FirstTemporary); if (ExprTemporaries.size() == FirstTemporary) return SubExpr; Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr, &ExprTemporaries[FirstTemporary], ExprTemporaries.size() - FirstTemporary); ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary, ExprTemporaries.end()); return E; } ExprResult Sema::MaybeCreateCXXExprWithTemporaries(ExprResult SubExpr) { if (SubExpr.isInvalid()) return ExprError(); return Owned(MaybeCreateCXXExprWithTemporaries(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::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor) { // Since this might be a postfix expression, get rid of ParenListExprs. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); if (Result.isInvalid()) return ExprError(); Base = Result.get(); QualType BaseType = Base->getType(); MayBePseudoDestructor = 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); MayBePseudoDestructor = 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 = BuildOverloadedArrowExpr(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::err_operator_arrow_circular); 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 // ActOnMemberReferenceExpr 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 // pseudo-destructor-name. ObjectType = ParsedType(); MayBePseudoDestructor = true; return Owned(Base); } // The object type must be complete (or dependent). if (!BaseType->isDependentType() && RequireCompleteType(OpLoc, BaseType, PDiag(diag::err_incomplete_member_access))) 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::DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr) { SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc); Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call) << isa<CXXPseudoDestructorExpr>(MemExpr) << FixItHint::CreateInsertion(ExpectedLParenLoc, "()"); return ActOnCallExpr(/*Scope*/ 0, MemExpr, /*LPLoc*/ ExpectedLParenLoc, MultiExprArg(), /*CommaLocs*/ 0, /*RPLoc*/ ExpectedLParenLoc); } ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeTypeInfo, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage 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::err_typecheck_member_reference_suggestion) << ObjectType << true << FixItHint::CreateReplacement(OpLoc, "."); if (isSFINAEContext()) return ExprError(); OpKind = tok::period; } } if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) { Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) << ObjectType << Base->getSourceRange(); return ExprError(); } // C++ [expr.pseudo]p2: // [...] The cv-unqualified versions of the object type and of the type // designated by the pseudo-destructor-name shall be the same type. if (DestructedTypeInfo) { QualType DestructedType = DestructedTypeInfo->getType(); SourceLocation DestructedTypeStart = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(); if (!DestructedType->isDependentType() && !ObjectType->isDependentType() && !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) << ObjectType << DestructedType << Base->getSourceRange() << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); // Recover by setting the destructed type to the object type. DestructedType = ObjectType; DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart); Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); } } // C++ [expr.pseudo]p2: // [...] Furthermore, the two type-names in a pseudo-destructor-name of the // form // // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name // // shall designate the same scalar type. if (ScopeTypeInfo) { QualType ScopeType = ScopeTypeInfo->getType(); if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) { Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(), diag::err_pseudo_dtor_type_mismatch) << ObjectType << ScopeType << Base->getSourceRange() << ScopeTypeInfo->getTypeLoc().getLocalSourceRange(); ScopeType = QualType(); ScopeTypeInfo = 0; } } Expr *Result = new (Context) CXXPseudoDestructorExpr(Context, Base, OpKind == tok::arrow, OpLoc, SS.getScopeRep(), SS.getRange(), ScopeTypeInfo, CCLoc, TildeLoc, Destructed); if (HasTrailingLParen) return Owned(Result); return DiagnoseDtorReference(Destructed.getLocation(), Result); } ExprResult Sema::ActOnPseudoDestructorExpr(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::err_typecheck_member_reference_suggestion) << 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 ObjectTypePtrForLookup; if (!SS.isSet()) { if (const Type *T = ObjectType->getAs<RecordType>()) ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0)); else if (ObjectType->isDependentType()) ObjectTypePtrForLookup = 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; PseudoDestructorTypeStorage Destructed; if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) { ParsedType T = getTypeName(*SecondTypeName.Identifier, SecondTypeName.StartLocation, S, &SS, true, ObjectTypePtrForLookup); 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 = PseudoDestructorTypeStorage(SecondTypeName.Identifier, SecondTypeName.StartLocation); } else if (!T) { Diag(SecondTypeName.StartLocation, diag::err_pseudo_dtor_destructor_non_type) << 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. TemplateIdAnnotation *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.getTrivialTypeSourceInfo(DestructedType, SecondTypeName.StartLocation); Destructed = PseudoDestructorTypeStorage(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, ObjectTypePtrForLookup); if (!T) { Diag(FirstTypeName.StartLocation, diag::err_pseudo_dtor_destructor_non_type) << 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. TemplateIdAnnotation *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.getTrivialTypeSourceInfo(ScopeType, FirstTypeName.StartLocation); return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, ScopeTypeInfo, CCLoc, TildeLoc, Destructed, HasTrailingLParen); } CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXMethodDecl *Method) { if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0, FoundDecl, Method)) assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?"); MemberExpr *ME = new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method, SourceLocation(), Method->getType()); QualType ResultType = Method->getCallResultType(); MarkDeclarationReferenced(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 MaybeCreateCXXExprWithTemporaries(FullExpr); }
Java
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JasperReports is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports. If not, see <http://www.gnu.org/licenses/>. */ 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 SerializationConstants.OBJECT_TYPE_FLOAT; } @Override public ReferenceType defaultReferenceType() { return ReferenceType.OBJECT; } @Override public boolean defaultStoreReference() { return true; } @Override public void write(Float value, VirtualizationOutput out) throws IOException { out.writeFloat(value); } @Override public Float read(VirtualizationInput in) throws IOException { return in.readFloat(); } }
Java
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Controller * @subpackage Zend_Controller_Action_Helper * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * @see Zend_Session */ require_once 'Zend/Session.php'; /** * @see Zend_Controller_Action_Helper_Abstract */ require_once 'Zend/Controller/Action/Helper/Abstract.php'; /** * Flash Messenger - implement session-based messages * * @uses Zend_Controller_Action_Helper_Abstract * @category Zend * @package Zend_Controller * @subpackage Zend_Controller_Action_Helper * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: FlashMessenger.php 23775 2011-03-01 17:25:24Z ralph $ */ class Zend_Controller_Action_Helper_FlashMessengerType extends Zend_Controller_Action_Helper_Abstract 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 Zend_Session_Namespace) { self::$_session = new Zend_Session_Namespace($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 Zend_Controller_Action_Helper_FlashMessenger 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 Zend_Controller_Action_Helper_FlashMessenger Provides a fluent interface */ public function setNamespace($namespace = 'default') { $this->_namespace = $namespace; return $this; } /** * resetNamespace() - reset the namespace to the default * * @return Zend_Controller_Action_Helper_FlashMessenger Provides a fluent interface */ public function resetNamespace() { $this->setNamespace(); return $this; } /** * addMessage() - Add a message to flash message * * @param string $message * @return Zend_Controller_Action_Helper_FlashMessenger 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 clearCurrentMessages() { 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); } }
Java
#exploderLightPanel{ position: absolute; width: 90%; margin-left: 5%; height: 90%; margin-top: 5%; background-color: white; z-index: 999; padding: 2em; } .level{ }
Java
<?php /* ########################################################################## # # # Version 4 / / / # # -----------__---/__---__------__----__---/---/- # # | /| / /___) / ) (_ ` / ) /___) / / # # _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ # # Free Content / Management System # # / # # # # # # Copyright 2005-2011 by webspell.org # # # # visit webSPELL.org, webspell.info to get webSPELL for free # # - Script runs under the GNU GENERAL PUBLIC LICENSE # # - It's NOT allowed to remove this copyright-tag # # -- http://www.fsf.org/licensing/licenses/gpl.html # # # # Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), # # Far Development by Development Team - webspell.org # # # # visit webspell.org # # # ########################################################################## */ $language_array = Array( /* do not edit above this line */ 'author'=>'Auteur', 'bbcode'=>'BBCode is <b><u>AAN</u></b>', 'cancel'=>'annuleren', 'comm'=>'reactie', 'comment'=>'<a href="$url">[1] reactie</a>, laatst door $lastposter - $lastdate', 'comments'=>'<a href="$url">[$anzcomments] reacties</a>, laatst door $lastposter - $lastdate', 'date'=>'Datum', 'delete'=>'verwijder', 'delete_selected'=>'verwijder geselecteerden', 'edit'=>'bewerk', 'enter_title'=>'Je moet een titel invullen!', 'enter_text'=>'Je moet tekst invullen', 'go'=>'Ga!', 'headline'=>'Titel', 'html'=>'HTML is <b><u>AAN</u></b>', 'intern'=>'intern', 'languages'=>'Talen', 'link'=>'Link', 'links'=>'Links', 'new_post'=>'Nieuw Bericht', 'new_window'=>'nieuw venster', 'news'=>'Nieuws', 'news_archive'=>'Archief', 'no'=>'nee', 'no_access'=>'geen toegang', 'no_comment'=>'<a href="$url">geen reacties</a>', 'no_comments'=>'sta commentaar niet toe', 'no_topnews'=>'geen top nieuws', 'options'=>'opties', 'post_languages'=>'Nieuws in <select name="language_count" onchange="update_textarea(this.options[this.selectedIndex].value)">$selects</select> talen', 'post_news'=>'plaats nieuws', 'preview'=>'preview', 'publish_now'=>'plaats nu', 'publish_selected'=>'plaats geselecteerden', 'really_delete'=>'Dit Nieuws echt verwijderen?', 'rubric'=>'Rubriek', 'save_news'=>'opslaan', 'select_all'=>'selecteer allen', 'self'=>'zelf venster', 'show_news'=>'bekijk nieuws', 'smilies'=>'Smileys zijn <b><u>AAN</u></b>', 'sort'=>'Sorteer:', 'title_unpublished_news'=>'<h2>ONGEPUCLICEERD NIEUWS:</h2>', 'topnews'=>'top nieuws', 'unpublish'=>'onpubliceer', 'unpublish_selected'=>'onpubliceer geselecteerden', 'unpublished_news'=>'onpubliceer nieuws', 'upload_images'=>'upload afbeeldingen', 'user_comments'=>'sta gebruikers commentaar toe', 'view_more'=>'zie meer...', 'visitor_comments'=>'sta bezoekers commentaar toe', 'written_by'=>'geschreven door', 'yes'=>'ja' ); ?>
Java
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])); } } }
Java
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.ContextHandlerCollection; 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; /** * Author: HongKee Moon (moon@mpi-cbg.de), Scientific Computing Facility * Organization: MPI-CBG Dresden * Date: December 2016 */ public class UserPageHandler extends BaseContextHandler { private static final org.eclipse.jetty.util.log.Logger LOG = Log.getLogger( UserPageHandler.class ); UserPageHandler( final Server server, final ContextHandlerCollection publicDatasetHandlers, final ContextHandlerCollection privateDatasetHandlers, final String thumbnailsDirectoryName ) throws IOException, URISyntaxException { super( server, publicDatasetHandlers, privateDatasetHandlers, thumbnailsDirectoryName ); setContextPath( "/private/user/*" ); } @Override public void doHandle( final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response ) throws IOException, ServletException { // System.out.println(target); Principal principal = request.getUserPrincipal(); // System.out.println( principal.getName() ); if ( null == request.getQueryString() ) { list( baseRequest, response, principal.getName() ); } else { // System.out.println(request.getQueryString()); updateDataSet( baseRequest, request, response, principal.getName() ); } } private void updateDataSet( Request baseRequest, HttpServletRequest request, HttpServletResponse response, String userId ) throws IOException { final String op = request.getParameter( "op" ); if ( null != op ) { if ( op.equals( "addDS" ) ) { final String dataSetName = request.getParameter( "name" ); final String tags = request.getParameter( "tags" ); final String description = request.getParameter( "description" ); final String file = request.getParameter( "file" ); final boolean isPublic = Boolean.parseBoolean( request.getParameter( "public" ) ); // System.out.println( "name: " + dataSetName ); // System.out.println( "tags: " + tags ); // System.out.println( "description: " + description ); // System.out.println( "file: " + file ); // System.out.println( "isPublic: " + isPublic ); final DataSet ds = new DataSet( dataSetName, file, tags, description, isPublic ); // Add it the database UserController.addDataSet( userId, ds ); // Add new CellHandler depending on public property addDataSet( ds, baseRequest, response ); } else if ( op.equals( "removeDS" ) ) { final long dsId = Long.parseLong( request.getParameter( "dataset" ) ); // Remove it from the database UserController.removeDataSet( userId, dsId ); // Remove the CellHandler removeDataSet( dsId, baseRequest, response ); } else if ( op.equals( "updateDS" ) ) { // UpdateDS uses x-editable // Please, refer http://vitalets.github.io/x-editable/docs.html final String field = request.getParameter( "name" ); final long dataSetId = Long.parseLong( request.getParameter( "pk" ) ); final String value = request.getParameter( "value" ); // Update the database final DataSet ds = UserController.getDataSet( userId, dataSetId ); if ( field.equals( "dataSetName" ) ) { ds.setName( value ); } else if ( field.equals( "dataSetDescription" ) ) { ds.setDescription( value ); } // Update DataBase UserController.updateDataSet( userId, ds ); // Update the CellHandler updateHandler( ds, baseRequest, response ); // System.out.println( field + ":" + value ); } else if ( op.equals( "addTag" ) || op.equals( "removeTag" ) ) { processTag( op, baseRequest, request, response ); } else if ( op.equals( "setPublic" ) ) { final long dataSetId = Long.parseLong( request.getParameter( "dataset" ) ); final boolean checked = Boolean.parseBoolean( request.getParameter( "checked" ) ); final DataSet ds = UserController.getDataSet( userId, dataSetId ); ds.setPublic( checked ); UserController.updateDataSet( userId, ds ); ds.setPublic( !checked ); updateHandlerVisibility( ds, checked, baseRequest, response ); } else if ( op.equals( "addSharedUser" ) || op.equals( "removeSharedUser" ) ) { final long dataSetId = Long.parseLong( request.getParameter( "dataset" ) ); final String sharedUserId = request.getParameter( "userId" ); if ( op.equals( "addSharedUser" ) ) { // System.out.println("Add a shared user"); UserController.addReadableSharedUser( userId, dataSetId, sharedUserId ); } else if ( op.equals( "removeSharedUser" ) ) { // System.out.println("Remove the shared user"); UserController.removeReadableSharedUser( userId, dataSetId, sharedUserId ); } response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); ow.write( "Success: " ); ow.close(); } } } private void updateHandlerVisibility( DataSet ds, boolean newVisibility, Request baseRequest, HttpServletResponse response ) throws IOException { String dsName = ds.getName(); boolean ret = removeCellHandler( ds.getIndex() ); if ( ret ) { ds.setPublic( newVisibility ); final boolean isPublic = newVisibility; final String context = "/" + ( isPublic ? Constants.PUBLIC_DATASET_CONTEXT_NAME : Constants.PRIVATE_DATASET_CONTEXT_NAME ) + "/id/" + ds.getIndex(); LOG.info( "Add new context: " + ds.getName() + " on " + context ); CellHandler ctx = getCellHandler( ds, isPublic, context ); ctx.setContextPath( context ); try { ctx.start(); } catch ( Exception e ) { LOG.warn( "Failed to start CellHandler", e ); e.printStackTrace(); ret = false; } } response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); if ( ret ) { ow.write( "Success: " + dsName + " is removed." ); } else { ow.write( "Error: " + dsName + " cannot be removed." ); } ow.close(); } private void updateHandler( DataSet ds, Request baseRequest, HttpServletResponse response ) throws IOException { boolean ret = false; String dsName = ""; for ( final Handler handler : server.getChildHandlersByClass( CellHandler.class ) ) { final CellHandler contextHandler = ( CellHandler ) handler; if ( contextHandler.getDataSet().getIndex() == ds.getIndex() ) { final DataSet dataSet = contextHandler.getDataSet(); dataSet.setName( ds.getName() ); dataSet.setDescription( ds.getDescription() ); ret = true; dsName = ds.getName(); break; } } response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); if ( ret ) { ow.write( "Success: " + dsName + " is updated." ); } else { ow.write( "Error: " + dsName + " cannot be updated." ); } ow.close(); } private void removeDataSet( long dsId, Request baseRequest, HttpServletResponse response ) throws IOException { boolean ret = removeCellHandler( dsId ); response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); if ( ret ) { ow.write( "Success: " + dsId + " is removed." ); } else { ow.write( "Error: " + dsId + " cannot be removed." ); } ow.close(); } private void addDataSet( DataSet ds, Request baseRequest, HttpServletResponse response ) throws IOException { boolean ret = false; if ( !ds.getXmlPath().isEmpty() && !ds.getName().isEmpty() ) { final boolean isPublic = ds.isPublic(); final String context = "/" + ( isPublic ? Constants.PUBLIC_DATASET_CONTEXT_NAME : Constants.PRIVATE_DATASET_CONTEXT_NAME ) + "/id/" + ds.getIndex(); LOG.info( "Add new context: " + ds.getName() + " on " + context ); CellHandler ctx = getCellHandler( ds, isPublic, context ); ctx.setContextPath( context ); try { ctx.start(); } catch ( Exception e ) { LOG.warn( "Failed to start CellHandler", e ); e.printStackTrace(); } ret = true; } response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); if ( ret ) ow.write( "Success: " + ds.getName() + " is added." ); else ow.write( "Error: " + ds.getName() + " cannot be added." ); ow.close(); } private void list( final Request baseRequest, final HttpServletResponse response, final String userId ) throws IOException { response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); getHtmlDatasetList( ow, userId ); ow.close(); } private void getHtmlDatasetList( final PrintWriter out, final String userId ) throws IOException { final List< DataSet >[] dataSets = UserController.getDataSets( userId ); final List< DataSet > myDataSetList = dataSets[ 0 ]; final List< DataSet > sharedDataSetList = dataSets[ 1 ]; final STGroup g = new STRawGroupDir( "templates", '$', '$' ); final ST userPage = g.getInstanceOf( "userPage" ); final STGroup g2 = new STRawGroupDir( "templates", '~', '~' ); final ST userPageJS = g2.getInstanceOf( "userPageJS" ); final StringBuilder dsString = new StringBuilder(); for ( DataSet ds : myDataSetList ) { StringBuilder sharedUserString = new StringBuilder(); final ST dataSetTr = g.getInstanceOf( "privateDataSetTr" ); for ( String sharedUser : ds.getSharedUsers() ) { final ST userToBeRemoved = g.getInstanceOf( "userToBeRemoved" ); userToBeRemoved.add( "dataSetId", ds.getIndex() ); userToBeRemoved.add( "sharedUserId", sharedUser ); sharedUserString.append( userToBeRemoved.render() ); } if ( ds.getDatasetUrl() == null ) { // Setup the dataset url if ( ds.isPublic() ) { ds.setDatasetUrl( "/" + Constants.PUBLIC_DATASET_CONTEXT_NAME + "/id/" + ds.getIndex() + "/" ); } else { ds.setDatasetUrl( "/" + Constants.PRIVATE_DATASET_CONTEXT_NAME + "/id/" + ds.getIndex() + "/" ); } } dataSetTr.add( "thumbnailUrl", ds.getThumbnailUrl() ); dataSetTr.add( "dataSetId", ds.getIndex() ); dataSetTr.add( "dataSetTags", ds.getTags().stream().collect( Collectors.joining( "," ) ) ); dataSetTr.add( "dataSetName", ds.getName() ); dataSetTr.add( "dataSetDescription", ds.getDescription() ); dataSetTr.add( "dataSetLocation", ds.getXmlPath() ); String url = ds.getDatasetUrl(); if ( url.endsWith( "/" ) ) url = url.substring( 0, url.lastIndexOf( "/" ) ); dataSetTr.add( "dataSetUrl", url ); dataSetTr.add( "dataSetIsPublic", ds.isPublic() ); dataSetTr.add( "sharedUsers", sharedUserString.toString() ); dsString.append( dataSetTr.render() ); } if ( sharedDataSetList != null ) { for ( DataSet ds : sharedDataSetList ) { final ST dataSetTr = g.getInstanceOf( "sharedDataSetTr" ); if ( ds.getDatasetUrl() == null ) { // Setup the dataset url if ( ds.isPublic() ) { ds.setDatasetUrl( "/" + Constants.PUBLIC_DATASET_CONTEXT_NAME + "/id/" + ds.getIndex() + "/" ); } else { ds.setDatasetUrl( "/" + Constants.PRIVATE_DATASET_CONTEXT_NAME + "/id/" + ds.getIndex() + "/" ); } } dataSetTr.add( "thumbnailUrl", ds.getThumbnailUrl() ); dataSetTr.add( "dataSetId", ds.getIndex() ); dataSetTr.add( "dataSetTags", Render.createTagsLabel( ds ) ); dataSetTr.add( "dataSetName", ds.getName() ); dataSetTr.add( "dataSetDescription", ds.getDescription() ); dataSetTr.add( "dataSetLocation", ds.getXmlPath() ); String url = ds.getDatasetUrl(); if ( url.endsWith( "/" ) ) url = url.substring( 0, url.lastIndexOf( "/" ) ); dataSetTr.add( "dataSetUrl", url ); dataSetTr.add( "dataSetIsPublic", ds.isPublic() ); dataSetTr.add( "sharedUsers", ds.getOwner() ); dsString.append( dataSetTr.render() ); } } userPage.add( "userId", userId ); userPage.add( "dataSetTr", dsString.toString() ); userPage.add( "JS", userPageJS.render() ); out.write( userPage.render() ); out.close(); } }
Java
/* * Copyright 2006, 2007 Alessandro Chiari. * * This file is part of BrewPlus. * * BrewPlus is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * BrewPlus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with BrewPlus; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ 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 getTemperaturaMaxFerm() { return temperaturaMaxFerm; } public void setTemperaturaMaxFerm(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; } }
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <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="classfasta_1_1XnuScores.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="classfasta_1_1XnuScores.html">fasta::XnuScores</a>, including all inherited members.<table> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#aee0be2c87cc3d73aa25a37ea14c27c94">Alphabet</a></td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#a05dbb507f32b777d8cf5fb258b7332e5">Blast</a></td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#aae61ad59c699d17788ebdc9f8fe0ad0f">Dayhoff</a></td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#a596b08d1891b73acfdd04fd2d2f6ebd6">Lambda120</a></td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#a9f671bdc8bb39683ddc8f3aa22e0fae3">Lambda250</a></td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#a3dce3b13d85b3d638ac4d10c24a4a65b">Lambda60</a></td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#a8034e6cbcd828e4d70b37741af985468">M</a></td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#a28615d4d2423e18aba59582e63f47ea2">Pam120</a></td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#a74d39ed5e0f4686b64f817b7fefca6bf">Pam250</a></td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#adf657d46e889bc4047e634615c4918b0">Pam60</a></td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#ad8583a13daf5fa32a64794eae87de201">XnuScores</a>()</td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#a9361babb4dd827117c55cb61dfee9553">~XnuScores</a>()</td><td><a class="el" href="classfasta_1_1XnuScores.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="MSearchResultsWindow"> <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 &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.7.6.1 </small></address> </body> </html>
Java
/* * Copyright 2016 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "cros_gralloc_helpers.h" #include <cstdlib> #include <cutils/log.h> #include <fcntl.h> #include <xf86drm.h> uint64_t cros_gralloc_convert_flags(int flags) { uint64_t usage = DRV_BO_USE_NONE; if (flags & GRALLOC_USAGE_CURSOR) usage |= DRV_BO_USE_CURSOR; if ((flags & sw_read()) == GRALLOC_USAGE_SW_READ_RARELY) usage |= DRV_BO_USE_SW_READ_RARELY; if ((flags & sw_read()) == GRALLOC_USAGE_SW_READ_OFTEN) usage |= DRV_BO_USE_SW_READ_OFTEN; if ((flags & sw_write()) == GRALLOC_USAGE_SW_WRITE_RARELY) usage |= DRV_BO_USE_SW_WRITE_RARELY; if ((flags & sw_write()) == GRALLOC_USAGE_SW_WRITE_OFTEN) usage |= DRV_BO_USE_SW_WRITE_OFTEN; if (flags & GRALLOC_USAGE_HW_TEXTURE) usage |= DRV_BO_USE_RENDERING; if (flags & GRALLOC_USAGE_HW_RENDER) usage |= DRV_BO_USE_RENDERING; if (flags & GRALLOC_USAGE_HW_2D) usage |= DRV_BO_USE_RENDERING; if (flags & GRALLOC_USAGE_HW_COMPOSER) /* HWC wants to use display hardware, but can defer to OpenGL. */ usage |= DRV_BO_USE_SCANOUT | DRV_BO_USE_RENDERING; if (flags & GRALLOC_USAGE_HW_FB) usage |= DRV_BO_USE_SCANOUT; if (flags & GRALLOC_USAGE_EXTERNAL_DISP) /* We're ignoring this flag until we decide what to with display link */ usage |= DRV_BO_USE_NONE; if (flags & GRALLOC_USAGE_PROTECTED) usage |= DRV_BO_USE_PROTECTED; if (flags & GRALLOC_USAGE_HW_VIDEO_ENCODER) /*HACK: See b/30054495 */ usage |= DRV_BO_USE_SW_READ_OFTEN; if (flags & GRALLOC_USAGE_HW_CAMERA_WRITE) usage |= DRV_BO_USE_HW_CAMERA_WRITE; if (flags & GRALLOC_USAGE_HW_CAMERA_READ) usage |= DRV_BO_USE_HW_CAMERA_READ; if (flags & GRALLOC_USAGE_HW_CAMERA_ZSL) usage |= DRV_BO_USE_HW_CAMERA_ZSL; if (flags & GRALLOC_USAGE_RENDERSCRIPT) usage |= DRV_BO_USE_RENDERSCRIPT; return usage; } drv_format_t cros_gralloc_convert_format(int format) { /* * Conversion from HAL to fourcc-based DRV formats based on * platform_android.c in mesa. */ switch (format) { case HAL_PIXEL_FORMAT_BGRA_8888: return DRV_FORMAT_ARGB8888; case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED: return DRV_FORMAT_FLEX_IMPLEMENTATION_DEFINED; case HAL_PIXEL_FORMAT_RGB_565: return DRV_FORMAT_RGB565; case HAL_PIXEL_FORMAT_RGB_888: return DRV_FORMAT_RGB888; case HAL_PIXEL_FORMAT_RGBA_8888: return DRV_FORMAT_ABGR8888; case HAL_PIXEL_FORMAT_RGBX_8888: return DRV_FORMAT_XBGR8888; case HAL_PIXEL_FORMAT_YCbCr_420_888: return DRV_FORMAT_FLEX_YCbCr_420_888; case HAL_PIXEL_FORMAT_YV12: return DRV_FORMAT_YVU420; } return DRV_FORMAT_NONE; } static int32_t cros_gralloc_query_rendernode(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 CROS_GRALLOC_ERROR_NONE; } return CROS_GRALLOC_ERROR_NO_RESOURCES; } int32_t cros_gralloc_rendernode_open(struct driver **drv) { int32_t ret; ret = cros_gralloc_query_rendernode(drv, NULL); /* Look for vgem driver if no hardware is found. */ if (ret) ret = cros_gralloc_query_rendernode(drv, "vgem"); return ret; } int32_t cros_gralloc_validate_handle(struct cros_gralloc_handle *hnd) { if (!hnd || hnd->magic != cros_gralloc_magic()) return CROS_GRALLOC_ERROR_BAD_HANDLE; return CROS_GRALLOC_ERROR_NONE; } 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); __android_log_vprint(ANDROID_LOG_ERROR, prefix, format, args); va_end(args); }
Java
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import React, { Component, PropTypes } from 'react'; import { observer } from 'mobx-react'; import { Button, GasPriceEditor } from '~/ui'; import TransactionMainDetails from '../TransactionMainDetails'; import TransactionPendingForm from '../TransactionPendingForm'; 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.getEthmFromWeiDisplay(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}` }> <TransactionMainDetails className={ styles.transactionDetails } from={ from } fromBalance={ fromBalance } gasStore={ this.gasStore } id={ id } isTest={ isTest } totalValue={ totalValue } transaction={ transaction } value={ value } /> <TransactionPendingForm 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); } }
Java
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.update_job_fetch_progress.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.open_current_job_folder) self.main_model.hotkey_model.add_hotkey(["Lcontrol", "Lmenu", "B"], self.main_view.open_current_job_basecamp) 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.show_job_already_exists_dialog() 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.show_job_fetch_progress_dialog(max) def on_job_fetch_update(self, progress): self.main_view.update_job_fetch_progress_dialog(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.google_maps_js_api_key, self.main_model.settings_model.google_maps_static_api_key, self.main_model.settings_model.google_earth_exe_path, self.main_model.settings_model.scene_exe_path) self.main_model.jobs[job.job_num] = job found = bool(job.base_folder) self.main_view.close_job_fetch_progress_dialog() if not found: open_anyway = self.main_view.show_job_not_found_dialog() 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)
Java
<?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', ), )); } }
Java
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.UnsatisfiedLinkError 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 preventDuplicateWork = 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 (preventDuplicateWork.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 { preventDuplicateWork.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.rightStateFromMarshalled(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; // } // } }
Java
// Decompiled with JetBrains decompiler // Type: System.Xml.Linq.BaseUriAnnotation // Assembly: System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // MVID: D3650A80-743D-4EFB-8926-AE790E9DB30F // 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; } } }
Java
#!/usr/bin/python # # Problem: Making Chess Boards # Language: Python # Author: KirarinSnow # 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))
Java
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 RealisticBiomeAPLAdirondackBeach extends RealisticBiomeAPLAdirondackBase { public static Biome biome = AppalachiaBiomes.adirondackBeach; public static Biome river = AppalachiaBiomes.adirondackRiver; public RealisticBiomeAPLAdirondackBeach() { super(biome, river); } @Override public void initConfig() { this.getConfig().addProperty(this.getConfig().SURFACE_MIX_BLOCK).set(""); this.getConfig().addProperty(this.getConfig().SURFACE_MIX_BLOCK_META).set(0); } @Override public TerrainBase initTerrain() { return new TerrainAPLAdirondackBeach(); } @Override public SurfaceBase initSurface() { return new SurfaceAPLAdirondackBeach(config, biome.topBlock, biome.fillerBlock, BlockUtil.getStateDirt(2), 12f, 0.27f); } public class SurfaceAPLAdirondackBeach extends SurfaceBase { protected IBlockState mixBlock; protected float width; protected float height; public SurfaceAPLAdirondackBeach(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.SURFACE_MIX_BLOCK_META.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 TerrainAPLAdirondackBeach extends TerrainBase { public TerrainAPLAdirondackBeach() { } @Override public float generateNoise(IRTGWorld rtgWorld, int x, int y, float border, float river) { return terrainBeach(x, y, rtgWorld.simplex(), river, 180f, 35f, 63f); } } }
Java
// Decompiled with JetBrains decompiler // Type: System.Boolean // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // MVID: 255ABCDF-D9D6-4E3D-BAD4-F74D4CE3D7A8 // 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)] [__DynamicallyInvokable] [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> [__DynamicallyInvokable] public static readonly string TrueString = "True"; /// <summary> /// Represents the Boolean value false as a string. This field is read-only. /// </summary> /// <filterpriority>1</filterpriority> [__DynamicallyInvokable] 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> [__DynamicallyInvokable] 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> [__DynamicallyInvokable] 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> [__DynamicallyInvokable] 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> [__DynamicallyInvokable] 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> [__DynamicallyInvokable] 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.ArgumentNullException"><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> [__DynamicallyInvokable] public static bool Parse(string value) { if (value == null) throw new ArgumentNullException("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> [__DynamicallyInvokable] 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.TrimWhiteSpaceAndNull(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 InvalidCastException(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 InvalidCastException(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 TrimWhiteSpaceAndNull(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); } } }
Java
/* * Copyright (c) 2010-2012 Matthias Klass, Johannes Leimer, * Rico Lieback, Sebastian Gabriel, Lothar Gesslein, * Alexander Rampp, Kai Weidner * * This file is part of the Physalix Enrollment System * * Foobar is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Foobar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Foobar. If not, see <http://www.gnu.org/licenses/>. */ 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 = 9180564827437598145L; /** * 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.getDetailInformation()))); 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.setEscapeModelStrings(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 = -1041971433878928045L; @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); } } }
Java
@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#org-eclipse-ui-main-toolbar { background-image: url(./win7.png); } .MPartStack.active { swt-unselected-tabs-color: #F3F9FF #D0DFEE #CEDDED #CEDDED #D2E1F0 #D2E1F0 #FFFFFF 20% 45% 60% 70% 100% 100%; swt-outer-keyline-color: #B6BCCC; } #PerspectiveSwitcher { background-color: #F5F7FC #E1E6F6 100%; } #org-eclipse-ui-editorss { swt-tab-renderer: url('bundleclass://org.eclipse.e4.ui.workbench.renderers.swt/org.eclipse.e4.ui.workbench.renderers.swt.CTabRendering'); swt-unselected-tabs-color: #F0F0F0 #F0F0F0 #F0F0F0 100% 100%; swt-outer-keyline-color: #B4B4B4; swt-inner-keyline-color: #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; }
Java
/* * AverMedia RM-KS remote controller keytable * * Copyright (C) 2010 Antti Palosaari <crope@iki.fi> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #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 }, /* 1 */ { 0x050a, KEY_2 }, /* 2 */ { 0x050b, KEY_3 }, /* 3 */ { 0x050c, KEY_4 }, /* 4 */ { 0x050d, KEY_5 }, /* 5 */ { 0x050e, KEY_6 }, /* 6 */ { 0x050f, KEY_7 }, /* 7 */ { 0x0510, KEY_8 }, /* 8 */ { 0x0511, KEY_9 }, /* 9 */ { 0x0512, KEY_0 }, /* 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 = RC_MAP_AVERMEDIA_RM_KS, } }; static int __init init_rc_map_avermedia_rm_ks(void) { return rc_map_register(&avermedia_rm_ks_map); } static void __exit exit_rc_map_avermedia_rm_ks(void) { rc_map_unregister(&avermedia_rm_ks_map); } module_init(init_rc_map_avermedia_rm_ks) module_exit(exit_rc_map_avermedia_rm_ks) MODULE_LICENSE("GPL"); MODULE_AUTHOR("Antti Palosaari <crope@iki.fi>");
Java
// Copyright (C) 2015 xaizek <xaizek@posteo.net> // // 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 // License as published by the Free Software Foundation. // // dit is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with dit. If not, see <http://www.gnu.org/licenses/>. #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 AutoRegisteredCommand<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; }
Java
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.lblLandParcelCountry = 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; // // lblLandParcelCountry // this.lblLandParcelCountry.AutoSize = true; this.lblLandParcelCountry.Location = new System.Drawing.Point(151, 17); this.lblLandParcelCountry.Name = "lblLandParcelCountry"; this.lblLandParcelCountry.Size = new System.Drawing.Size(43, 13); this.lblLandParcelCountry.TabIndex = 67; this.lblLandParcelCountry.Text = "Country"; this.lblLandParcelCountry.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.SelectedIndexChanged += new System.EventHandler(this.comboBox21_SelectedIndexChanged); // // 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 lblLandParcelCountry; 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; } }
Java
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.dialer.calllog; import android.content.Context; import android.content.res.Resources; import android.provider.CallLog.Calls; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.util.Log; import com.android.contacts.common.CallUtil; import com.android.dialer.PhoneCallDetails; import com.android.dialer.PhoneCallDetailsHelper; import com.android.dialer.R; /** * Helper class to fill in the views of a call log entry. */ /* package */class CallLogListItemHelper { private static final String TAG = "CallLogListItemHelper"; /** Helper for populating the details of a phone call. */ private final PhoneCallDetailsHelper mPhoneCallDetailsHelper; /** Helper for handling phone numbers. */ private final PhoneNumberDisplayHelper mPhoneNumberHelper; /** Resources to look up strings. */ private final Resources mResources; /** * Creates a new helper instance. * * @param phoneCallDetailsHelper used to set the details of a phone call * @param phoneNumberHelper used to process phone number */ public CallLogListItemHelper(PhoneCallDetailsHelper phoneCallDetailsHelper, PhoneNumberDisplayHelper phoneNumberHelper, Resources resources) { mPhoneCallDetailsHelper = phoneCallDetailsHelper; mPhoneNumberHelper = phoneNumberHelper; mResources = resources; } /** * Sets the name, label, and number for a contact. * * @param context The application context. * @param views the views to populate * @param details the details of a phone call needed to fill in the data */ public void setPhoneCallDetails( Context context, CallLogListItemViews views, PhoneCallDetails details) { mPhoneCallDetailsHelper.setPhoneCallDetails(views.phoneCallDetailsViews, details); // Set the accessibility text for the contact badge views.quickContactView.setContentDescription(getContactBadgeDescription(details)); // Set the primary action accessibility description views.primaryActionView.setContentDescription(getCallDescription(context, details)); // Cache name or number of caller. Used when setting the content descriptions of buttons // when the actions ViewStub is inflated. views.nameOrNumber = this.getNameOrNumber(details); } /** * Sets the accessibility descriptions for the action buttons in the action button ViewStub. * * @param views The views associated with the current call log entry. */ public void setActionContentDescriptions(CallLogListItemViews views) { if (views.nameOrNumber == null) { Log.e(TAG, "setActionContentDescriptions; name or number is null."); } // Calling expandTemplate with a null parameter will cause a NullPointerException. // Although we don't expect a null name or number, it is best to protect against it. CharSequence nameOrNumber = views.nameOrNumber == null ? "" : views.nameOrNumber; views.callBackButtonView.setContentDescription( TextUtils.expandTemplate( mResources.getString(R.string.description_call_back_action), nameOrNumber)); views.videoCallButtonView.setContentDescription( TextUtils.expandTemplate( mResources.getString(R.string.description_video_call_action), nameOrNumber)); views.voicemailButtonView.setContentDescription( TextUtils.expandTemplate( mResources.getString(R.string.description_voicemail_action), nameOrNumber)); views.detailsButtonView.setContentDescription( TextUtils.expandTemplate( mResources.getString(R.string.description_details_action), nameOrNumber)); } /** * Returns the accessibility description for the contact badge for a call log entry. * * @param details Details of call. * @return Accessibility description. */ private CharSequence getContactBadgeDescription(PhoneCallDetails details) { return mResources.getString(R.string.description_contact_details, getNameOrNumber(details)); } /** * Returns the accessibility description of the "return call/call" action for a call log * entry. * Accessibility text is a combination of: * {Voicemail Prefix}. {Number of Calls}. {Caller information} {Phone Account}. * If most recent call is a voicemail, {Voicemail Prefix} is "New Voicemail.", otherwise "". * * If more than one call for the caller, {Number of Calls} is: * "{number of calls} calls.", otherwise "". * * The {Caller Information} references the most recent call associated with the caller. * For incoming calls: * If missed call: Missed call from {Name/Number} {Call Type} {Call Time}. * If answered call: Answered call from {Name/Number} {Call Type} {Call Time}. * * For outgoing calls: * If outgoing: Call to {Name/Number] {Call Type} {Call Time}. * * Where: * {Name/Number} is the name or number of the caller (as shown in call log). * {Call type} is the contact phone number type (eg mobile) or location. * {Call Time} is the time since the last call for the contact occurred. * * The {Phone Account} refers to the account/SIM through which the call was placed or received * in multi-SIM devices. * * Examples: * 3 calls. New Voicemail. Missed call from Joe Smith mobile 2 hours ago on SIM 1. * * 2 calls. Answered call from John Doe mobile 1 hour ago. * * @param context The application context. * @param details Details of call. * @return Return call action description. */ public CharSequence getCallDescription(Context context, PhoneCallDetails details) { int lastCallType = getLastCallType(details.callTypes); boolean isVoiceMail = lastCallType == Calls.VOICEMAIL_TYPE; // Get the name or number of the caller. final CharSequence nameOrNumber = getNameOrNumber(details); // Get the call type or location of the caller; null if not applicable final CharSequence typeOrLocation = mPhoneCallDetailsHelper.getCallTypeOrLocation(details); // Get the time/date of the call final CharSequence timeOfCall = mPhoneCallDetailsHelper.getCallDate(details); SpannableStringBuilder callDescription = new SpannableStringBuilder(); // Prepend the voicemail indication. if (isVoiceMail) { callDescription.append(mResources.getString(R.string.description_new_voicemail)); } // Add number of calls if more than one. if (details.callTypes.length > 1) { callDescription.append(mResources.getString(R.string.description_num_calls, details.callTypes.length)); } // If call had video capabilities, add the "Video Call" string. if ((details.features & Calls.FEATURES_VIDEO) == Calls.FEATURES_VIDEO && CallUtil.isVideoEnabled(context)) { callDescription.append(mResources.getString(R.string.description_video_call)); } int stringID = getCallDescriptionStringID(details); String accountLabel = PhoneAccountUtils.getAccountLabel(context, details.accountHandle); // Use chosen string resource to build up the message. CharSequence onAccountLabel = accountLabel == null ? "" : TextUtils.expandTemplate( mResources.getString(R.string.description_phone_account), accountLabel); callDescription.append( TextUtils.expandTemplate( mResources.getString(stringID), nameOrNumber, // If no type or location can be determined, sub in empty string. typeOrLocation == null ? "" : typeOrLocation, timeOfCall, onAccountLabel)); return callDescription; } /** * Determine the appropriate string ID to describe a call for accessibility purposes. * * @param details Call details. * @return String resource ID to use. */ public int getCallDescriptionStringID(PhoneCallDetails details) { int lastCallType = getLastCallType(details.callTypes); int stringID; if (lastCallType == Calls.VOICEMAIL_TYPE || lastCallType == Calls.MISSED_TYPE) { //Message: Missed call from <NameOrNumber>, <TypeOrLocation>, <TimeOfCall>, //<PhoneAccount>. stringID = R.string.description_incoming_missed_call; } else if (lastCallType == Calls.INCOMING_TYPE) { //Message: Answered call from <NameOrNumber>, <TypeOrLocation>, <TimeOfCall>, //<PhoneAccount>. stringID = R.string.description_incoming_answered_call; } else { //Message: Call to <NameOrNumber>, <TypeOrLocation>, <TimeOfCall>, <PhoneAccount>. stringID = R.string.description_outgoing_call; } return stringID; } /** * Determine the call type for the most recent call. * @param callTypes Call types to check. * @return Call type. */ private int getLastCallType(int[] callTypes) { if (callTypes.length > 0) { return callTypes[0]; } else { return Calls.MISSED_TYPE; } } /** * Return the name or number of the caller specified by the details. * @param details Call details * @return the name (if known) of the caller, otherwise the formatted number. */ private CharSequence getNameOrNumber(PhoneCallDetails details) { final CharSequence recipient; if (!TextUtils.isEmpty(details.name)) { recipient = details.name; } else { recipient = mPhoneNumberHelper.getDisplayNumber(details.accountHandle, details.number, details.numberPresentation, details.formattedNumber); } return recipient; } }
Java
#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 _rb_wp_tree_node_cloor { RB_TREE_RED = 0, RB_TREE_BLACK, } wp_rb_tree_node_color_t; wp_tree_node_t *wp_tree_node_new (void); wp_tree_node_t *wp_tree_node_new_full (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 wp_tree_node_set_content (wp_tree_node_t *node, void *data); void wp_tree_node_set_parent (wp_tree_node_t *node, wp_tree_node_t *parent); void wp_tree_node_set_left (wp_tree_node_t *node, wp_tree_node_t *left); void wp_tree_node_set_right (wp_tree_node_t *node, wp_tree_node_t *right); void *wp_tree_node_get_content (const wp_tree_node_t *node); wp_tree_node_t *wp_tree_node_get_parent (const wp_tree_node_t *node); wp_tree_node_t *wp_tree_node_get_left (const wp_tree_node_t *node); wp_tree_node_t *wp_tree_node_get_right (const wp_tree_node_t *node); int wp_tree_node_is_leaf (const wp_tree_node_t *node); int wp_tree_node_is_root (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 wp_tree_node_set_red (wp_tree_node_t *node); void wp_tree_node_set_black (wp_tree_node_t *node); int wp_tree_node_is_red (const wp_tree_node_t *node); int wp_tree_node_is_black (const wp_tree_node_t *node); wp_rb_tree_node_color_t wp_tree_node_get_color (const wp_tree_node_t *node); void wp_tree_node_set_color (wp_tree_node_t *node, wp_rb_tree_node_color_t color); void wp_tree_node_copy_color (wp_tree_node_t *dest, const wp_tree_node_t *src); void rb_wp_tree_node_dump (const wp_tree_node_t *node, FILE *file, wp_write_func_t f, void *data); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* _TREENODE_H */
Java
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]; } } }
Java
/* FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd. All rights reserved VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. This file is part of the FreeRTOS distribution. FreeRTOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception. *************************************************************************** >>! NOTE: The modification to the GPL is included to allow you to !<< >>! distribute a combined work that includes FreeRTOS without being !<< >>! obliged to provide the source code for proprietary components !<< >>! outside of the FreeRTOS kernel. !<< *************************************************************************** FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Full license text is available on the following link: http://www.freertos.org/a00114.html *************************************************************************** * * * FreeRTOS provides completely free yet professionally developed, * * robust, strictly quality controlled, supported, and cross * * platform software that is more than just the market leader, it * * is the industry's de facto standard. * * * * Help yourself get started quickly while simultaneously helping * * to support the FreeRTOS project by purchasing a FreeRTOS * * tutorial book, reference manual, or both: * * http://www.FreeRTOS.org/Documentation * * * *************************************************************************** http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading the FAQ page "My application does not run, what could be wrong?". Have you defined configASSERT()? http://www.FreeRTOS.org/support - In return for receiving this top quality embedded software for free we request you assist our global community by participating in the support forum. http://www.FreeRTOS.org/training - Investing in training allows your team to be as productive as possible as early as possible. Now you can receive FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers Ltd, and the world's leading authority on the world's leading RTOS. http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, including FreeRTOS+Trace - an indispensable productivity tool, a DOS compatible FAT file system, and our tiny thread aware UDP/IP stack. http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS licenses offer ticketed support, indemnification and commercial middleware. http://www.SafeRTOS.com - High Integrity Systems also provide a safety engineered and independently SIL3 certified version for use in safety and mission critical applications that require provable dependability. 1 tab == 4 spaces! */ /* * Creates all the demo application tasks, then starts the scheduler. The WEB * documentation provides more details of the demo application tasks. * * In addition to the standard demo tasks, the follow demo specific tasks are * create: * * The "Check" task. This only executes every three seconds but has the highest * priority so is guaranteed to get processor time. Its main function is to * check that all the other tasks are still operational. Most tasks maintain * a unique count that is incremented each time the task successfully completes * its function. Should any error occur within such a task the count is * permanently halted. The check task inspects the count of each task to ensure * it has changed since the last time the check task executed. If all the count * variables have changed all the tasks are still executing error free, and the * check task toggles the onboard LED. Should any task contain an error at any time * the LED toggle rate will change from 3 seconds to 500ms. * * The "Register Check" tasks. These tasks fill the CPU registers with known * values, then check that each register still contains the expected value, the * discovery of an unexpected value being indicative of an error in the RTOS * context switch mechanism. The register check tasks operate at low priority * so are switched in and out frequently. * */ /* Scheduler includes. */ #include "FreeRTOS.h" #include "task.h" /* Xilinx library includes. */ #include "xcache_l.h" #include "xintc.h" /* Demo application includes. */ #include "flash.h" #include "integer.h" #include "comtest2.h" #include "semtest.h" #include "BlockQ.h" #include "dynamic.h" #include "GenQTest.h" #include "QPeek.h" #include "blocktim.h" #include "death.h" #include "partest.h" #include "countsem.h" #include "recmutex.h" #include "flop.h" #include "flop-reg-test.h" /* Priorities assigned to the demo tasks. */ #define mainCHECK_TASK_PRIORITY ( tskIDLE_PRIORITY + 4 ) #define mainSEM_TEST_PRIORITY ( tskIDLE_PRIORITY + 2 ) #define mainCOM_TEST_PRIORITY ( tskIDLE_PRIORITY + 1 ) #define mainQUEUE_BLOCK_PRIORITY ( tskIDLE_PRIORITY + 1 ) #define mainDEATH_PRIORITY ( tskIDLE_PRIORITY + 1 ) #define mainLED_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 ) #define mainGENERIC_QUEUE_PRIORITY ( tskIDLE_PRIORITY ) #define mainQUEUE_POLL_PRIORITY ( tskIDLE_PRIORITY + 1 ) #define mainFLOP_PRIORITY ( tskIDLE_PRIORITY ) /* The first LED used by the COM test and check tasks respectively. */ #define mainCOM_TEST_LED ( 4 ) #define mainCHECK_TEST_LED ( 3 ) /* The baud rate used by the comtest tasks is set by the hardware, so the baud rate parameters passed into the comtest initialisation has no effect. */ #define mainBAUD_SET_IN_HARDWARE ( 0 ) /* Delay periods used by the check task. If no errors have been found then the check LED will toggle every mainNO_ERROR_CHECK_DELAY milliseconds. If an error has been found at any time then the toggle rate will increase to mainERROR_CHECK_DELAY milliseconds. */ #define mainNO_ERROR_CHECK_DELAY ( ( TickType_t ) 3000 / portTICK_PERIOD_MS ) #define mainERROR_CHECK_DELAY ( ( TickType_t ) 500 / portTICK_PERIOD_MS ) /* * The tasks defined within this file - described within the comments at the * head of this page. */ static void prvRegTestTask1( void *pvParameters ); static void prvRegTestTask2( void *pvParameters ); static void prvErrorChecks( void *pvParameters ); /* * Called by the 'check' task to inspect all the standard demo tasks within * the system, as described within the comments at the head of this page. */ static portBASE_TYPE prvCheckOtherTasksAreStillRunning( void ); /* * Perform any hardware initialisation required by the demo application. */ static void prvSetupHardware( void ); /*-----------------------------------------------------------*/ /* xRegTestStatus will get set to pdFAIL by the regtest tasks if they discover an unexpected value. */ static volatile unsigned portBASE_TYPE xRegTestStatus = pdPASS; /* Counters used to ensure the regtest tasks are still running. */ static volatile unsigned long ulRegTest1Counter = 0UL, ulRegTest2Counter = 0UL; /*-----------------------------------------------------------*/ int main( void ) { /* Must be called prior to installing any interrupt handlers! */ vPortSetupInterruptController(); /* In this case prvSetupHardware() just enables the caches and and configures the IO ports for the LED outputs. */ prvSetupHardware(); /* Start the standard demo application tasks. Note that the baud rate used by the comtest tasks is set by the hardware, so the baud rate parameter passed has no effect. */ vStartLEDFlashTasks( mainLED_TASK_PRIORITY ); vStartIntegerMathTasks( tskIDLE_PRIORITY ); vAltStartComTestTasks( mainCOM_TEST_PRIORITY, mainBAUD_SET_IN_HARDWARE, mainCOM_TEST_LED ); vStartSemaphoreTasks( mainSEM_TEST_PRIORITY ); vStartBlockingQueueTasks ( mainQUEUE_BLOCK_PRIORITY ); vStartDynamicPriorityTasks(); vStartGenericQueueTasks( mainGENERIC_QUEUE_PRIORITY ); vStartQueuePeekTasks(); vCreateBlockTimeTasks(); vStartCountingSemaphoreTasks(); vStartRecursiveMutexTasks(); #if ( configUSE_FPU == 1 ) { /* A different project is provided that has configUSE_FPU set to 1 in order to demonstrate all the settings required to use the floating point unit. If you wish to use the floating point unit do not start with this project. */ vStartMathTasks( mainFLOP_PRIORITY ); vStartFlopRegTests(); } #endif /* Create the tasks defined within this file. */ xTaskCreate( prvRegTestTask1, "Regtest1", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL ); xTaskCreate( prvRegTestTask2, "Regtest2", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL ); xTaskCreate( prvErrorChecks, "Check", configMINIMAL_STACK_SIZE, NULL, mainCHECK_TASK_PRIORITY, NULL ); /* The suicide tasks must be started last as they record the number of other tasks that exist within the system. The value is then used to ensure at run time the number of tasks that exists is within expected bounds. */ vCreateSuicidalTasks( mainDEATH_PRIORITY ); /* Now start the scheduler. Following this call the created tasks should be executing. */ vTaskStartScheduler(); /* vTaskStartScheduler() will only return if an error occurs while the idle task is being created. */ for( ;; ); return 0; } /*-----------------------------------------------------------*/ static portBASE_TYPE prvCheckOtherTasksAreStillRunning( void ) { portBASE_TYPE lReturn = pdPASS; static unsigned long ulLastRegTest1Counter= 0UL, ulLastRegTest2Counter = 0UL; /* The demo tasks maintain a count that increments every cycle of the task provided that the task has never encountered an error. This function checks the counts maintained by the tasks to ensure they are still being incremented. A count remaining at the same value between calls therefore indicates that an error has been detected. */ if( xAreIntegerMathsTaskStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xAreComTestTasksStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xAreSemaphoreTasksStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xAreBlockingQueuesStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xAreDynamicPriorityTasksStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xIsCreateTaskStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xAreBlockTimeTestTasksStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xAreGenericQueueTasksStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xAreQueuePeekTasksStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xAreCountingSemaphoreTasksStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xAreRecursiveMutexTasksStillRunning() != pdTRUE ) { lReturn = pdFAIL; } #if ( configUSE_FPU == 1 ) if( xAreMathsTaskStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xAreFlopRegisterTestsStillRunning() != pdTRUE ) { lReturn = pdFAIL; } #endif /* Have the register test tasks found any errors? */ if( xRegTestStatus != pdPASS ) { lReturn = pdFAIL; } /* Are the register test tasks still looping? */ if( ulLastRegTest1Counter == ulRegTest1Counter ) { lReturn = pdFAIL; } else { ulLastRegTest1Counter = ulRegTest1Counter; } if( ulLastRegTest2Counter == ulRegTest2Counter ) { lReturn = pdFAIL; } else { ulLastRegTest2Counter = ulRegTest2Counter; } return lReturn; } /*-----------------------------------------------------------*/ static void prvErrorChecks( void *pvParameters ) { TickType_t xDelayPeriod = mainNO_ERROR_CHECK_DELAY, xLastExecutionTime; volatile unsigned portBASE_TYPE uxFreeStack; /* Just to remove compiler warning. */ ( void ) pvParameters; /* This call is just to demonstrate the use of the function - nothing is done with the value. You would expect the stack high water mark to be lower (the function to return a larger value) here at function entry than later following calls to other functions. */ uxFreeStack = uxTaskGetStackHighWaterMark( NULL ); /* Initialise xLastExecutionTime so the first call to vTaskDelayUntil() works correctly. */ xLastExecutionTime = xTaskGetTickCount(); /* Cycle for ever, delaying then checking all the other tasks are still operating without error. */ for( ;; ) { /* Again just for demo purposes - uxFreeStack should have a lower value here than following the call to uxTaskGetStackHighWaterMark() on the task entry. */ uxFreeStack = uxTaskGetStackHighWaterMark( NULL ); /* Wait until it is time to check again. The time we wait here depends on whether an error has been detected or not. When an error is detected the time is shortened resulting in a faster LED flash rate. */ vTaskDelayUntil( &xLastExecutionTime, xDelayPeriod ); /* See if the other tasks are all ok. */ if( prvCheckOtherTasksAreStillRunning() != pdPASS ) { /* An error occurred in one of the tasks so shorten the delay period - which has the effect of increasing the frequency of the LED toggle. */ xDelayPeriod = mainERROR_CHECK_DELAY; } /* Flash! */ vParTestToggleLED( mainCHECK_TEST_LED ); } } /*-----------------------------------------------------------*/ static void prvSetupHardware( void ) { XCache_EnableICache( 0x80000000 ); XCache_EnableDCache( 0x80000000 ); /* Setup the IO port for use with the LED outputs. */ vParTestInitialise(); } /*-----------------------------------------------------------*/ void prvRegTest1Pass( void ) { /* Called from the inline assembler - this cannot be static otherwise it can get optimised away. */ ulRegTest1Counter++; } /*-----------------------------------------------------------*/ void prvRegTest2Pass( void ) { /* Called from the inline assembler - this cannot be static otherwise it can get optimised away. */ ulRegTest2Counter++; } /*-----------------------------------------------------------*/ void prvRegTestFail( void ) { /* Called from the inline assembler - this cannot be static otherwise it can get optimised away. */ xRegTestStatus = pdFAIL; } /*-----------------------------------------------------------*/ static void prvRegTestTask1( void *pvParameters ) { /* Just to remove compiler warning. */ ( void ) pvParameters; /* The first register test task as described at the top of this file. The values used in the registers are different to those use in the second register test task. Also, unlike the second register test task, this task yields between setting the register values and subsequently checking the register values. */ asm volatile ( "RegTest1Start: \n\t" \ " \n\t" \ " li 0, 301 \n\t" \ " mtspr 256, 0 #USPRG0 \n\t" \ " li 0, 501 \n\t" \ " mtspr 8, 0 #LR \n\t" \ " li 0, 4 \n\t" \ " mtspr 1, 0 #XER \n\t" \ " \n\t" \ " li 0, 1 \n\t" \ " li 2, 2 \n\t" \ " li 3, 3 \n\t" \ " li 4, 4 \n\t" \ " li 5, 5 \n\t" \ " li 6, 6 \n\t" \ " li 7, 7 \n\t" \ " li 8, 8 \n\t" \ " li 9, 9 \n\t" \ " li 10, 10 \n\t" \ " li 11, 11 \n\t" \ " li 12, 12 \n\t" \ " li 13, 13 \n\t" \ " li 14, 14 \n\t" \ " li 15, 15 \n\t" \ " li 16, 16 \n\t" \ " li 17, 17 \n\t" \ " li 18, 18 \n\t" \ " li 19, 19 \n\t" \ " li 20, 20 \n\t" \ " li 21, 21 \n\t" \ " li 22, 22 \n\t" \ " li 23, 23 \n\t" \ " li 24, 24 \n\t" \ " li 25, 25 \n\t" \ " li 26, 26 \n\t" \ " li 27, 27 \n\t" \ " li 28, 28 \n\t" \ " li 29, 29 \n\t" \ " li 30, 30 \n\t" \ " li 31, 31 \n\t" \ " \n\t" \ " sc \n\t" \ " nop \n\t" \ " \n\t" \ " cmpwi 0, 1 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 2, 2 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 3, 3 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 4, 4 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 5, 5 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 6, 6 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 7, 7 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 8, 8 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 9, 9 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 10, 10 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 11, 11 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 12, 12 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 13, 13 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 14, 14 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 15, 15 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 16, 16 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 17, 17 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 18, 18 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 19, 19 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 20, 20 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 21, 21 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 22, 22 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 23, 23 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 24, 24 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 25, 25 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 26, 26 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 27, 27 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 28, 28 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 29, 29 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 30, 30 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 31, 31 \n\t" \ " bne RegTest1Fail \n\t" \ " \n\t" \ " mfspr 0, 256 #USPRG0 \n\t" \ " cmpwi 0, 301 \n\t" \ " bne RegTest1Fail \n\t" \ " mfspr 0, 8 #LR \n\t" \ " cmpwi 0, 501 \n\t" \ " bne RegTest1Fail \n\t" \ " mfspr 0, 1 #XER \n\t" \ " cmpwi 0, 4 \n\t" \ " bne RegTest1Fail \n\t" \ " \n\t" \ " bl prvRegTest1Pass \n\t" \ " b RegTest1Start \n\t" \ " \n\t" \ "RegTest1Fail: \n\t" \ " \n\t" \ " \n\t" \ " bl prvRegTestFail \n\t" \ " b RegTest1Start \n\t" \ ); } /*-----------------------------------------------------------*/ static void prvRegTestTask2( void *pvParameters ) { /* Just to remove compiler warning. */ ( void ) pvParameters; /* The second register test task as described at the top of this file. Note that this task fills the registers with different values to the first register test task. */ asm volatile ( "RegTest2Start: \n\t" \ " \n\t" \ " li 0, 300 \n\t" \ " mtspr 256, 0 #USPRG0 \n\t" \ " li 0, 500 \n\t" \ " mtspr 8, 0 #LR \n\t" \ " li 0, 4 \n\t" \ " mtspr 1, 0 #XER \n\t" \ " \n\t" \ " li 0, 11 \n\t" \ " li 2, 12 \n\t" \ " li 3, 13 \n\t" \ " li 4, 14 \n\t" \ " li 5, 15 \n\t" \ " li 6, 16 \n\t" \ " li 7, 17 \n\t" \ " li 8, 18 \n\t" \ " li 9, 19 \n\t" \ " li 10, 110 \n\t" \ " li 11, 111 \n\t" \ " li 12, 112 \n\t" \ " li 13, 113 \n\t" \ " li 14, 114 \n\t" \ " li 15, 115 \n\t" \ " li 16, 116 \n\t" \ " li 17, 117 \n\t" \ " li 18, 118 \n\t" \ " li 19, 119 \n\t" \ " li 20, 120 \n\t" \ " li 21, 121 \n\t" \ " li 22, 122 \n\t" \ " li 23, 123 \n\t" \ " li 24, 124 \n\t" \ " li 25, 125 \n\t" \ " li 26, 126 \n\t" \ " li 27, 127 \n\t" \ " li 28, 128 \n\t" \ " li 29, 129 \n\t" \ " li 30, 130 \n\t" \ " li 31, 131 \n\t" \ " \n\t" \ " cmpwi 0, 11 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 2, 12 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 3, 13 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 4, 14 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 5, 15 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 6, 16 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 7, 17 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 8, 18 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 9, 19 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 10, 110 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 11, 111 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 12, 112 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 13, 113 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 14, 114 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 15, 115 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 16, 116 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 17, 117 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 18, 118 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 19, 119 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 20, 120 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 21, 121 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 22, 122 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 23, 123 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 24, 124 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 25, 125 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 26, 126 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 27, 127 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 28, 128 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 29, 129 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 30, 130 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 31, 131 \n\t" \ " bne RegTest2Fail \n\t" \ " \n\t" \ " mfspr 0, 256 #USPRG0 \n\t" \ " cmpwi 0, 300 \n\t" \ " bne RegTest2Fail \n\t" \ " mfspr 0, 8 #LR \n\t" \ " cmpwi 0, 500 \n\t" \ " bne RegTest2Fail \n\t" \ " mfspr 0, 1 #XER \n\t" \ " cmpwi 0, 4 \n\t" \ " bne RegTest2Fail \n\t" \ " \n\t" \ " bl prvRegTest2Pass \n\t" \ " b RegTest2Start \n\t" \ " \n\t" \ "RegTest2Fail: \n\t" \ " \n\t" \ " \n\t" \ " bl prvRegTestFail \n\t" \ " b RegTest2Start \n\t" \ ); } /*-----------------------------------------------------------*/ /* This hook function will get called if there is a suspected stack overflow. An overflow can cause the task name to be corrupted, in which case the task handle needs to be used to determine the offending task. */ void vApplicationStackOverflowHook( TaskHandle_t xTask, signed char *pcTaskName ); void vApplicationStackOverflowHook( TaskHandle_t xTask, signed char *pcTaskName ) { /* To prevent the optimiser removing the variables. */ volatile TaskHandle_t xTaskIn = xTask; volatile signed char *pcTaskNameIn = pcTaskName; /* Remove compiler warnings. */ ( void ) xTaskIn; ( void ) pcTaskNameIn; /* The following three calls are simply to stop compiler warnings about the functions not being used - they are called from the inline assembly. */ prvRegTest1Pass(); prvRegTest2Pass(); prvRegTestFail(); for( ;; ); }
Java
# Pacman We are two people, trying to program a game with GODOT.
Java
# 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.
Java
-- -- 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
Java
#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::get_smallest_distance (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 = get_smallest_distance(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_->setEdgeLengthsPresent(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_; }
Java
from .gaussian_process import RandomFeatureGaussianProcess, mean_field_logits from .spectral_normalization import SpectralNormalization
Java
/* * IIIFProducer * Copyright (C) 2017 Leipzig University Library <info@ub.uni-leipzig.de> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ 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; } }
Java
/****************************************************************************** * * Copyright 2010, Dream Chip Technologies GmbH. All rights reserved. * No part of this work may be reproduced, modified, distributed, transmitted, * transcribed, or translated into any language or computer format, in any form * or by any means without written permission of: * Dream Chip Technologies GmbH, Steinriede 10, 30827 Garbsen / Berenbostel, * Germany * *****************************************************************************/ /** * @file impexinfo.h * * @brief * Image info for import/export C++ API. * *****************************************************************************/ /** * * @mainpage Module Documentation * * * Doc-Id: xx-xxx-xxx-xxx (NAME Implementation Specification)\n * Author: NAME * * DESCRIBE_HERE * * * The manual is divided into the following sections: * * -@subpage module_name_api_page \n * -@subpage module_name_page \n * * @page module_name_api_page Module Name API * This module is the API for the NAME. DESCRIBE IN DETAIL / ADD USECASES... * * for a detailed list of api functions refer to: * - @ref module_name_api * * @defgroup module_name_api Module Name API * @{ */ #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 const_category_iterator; 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; const_category_iterator begin() const ; const_category_iterator end() const ; const_tag_iterator begin( const_category_iterator iter ) const ; const_tag_iterator end( const_category_iterator 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__*/
Java
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.RESULT_TB_RESULT_ENTRY_RULE); 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.RESULT_TB_RESULT_ENTRY_RULE); 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.RESULT_TB_RESULT_ENTRY_RULE); 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(); } } } }
Java
<?php namespace MikroOdeme\Enum; /** * Mikro Odeme library in PHP. * * @package mikro-odeme * @version 0.1.0 * @author Hüseyin Emre Özdemir <h.emre.ozdemir@gmail.com> * @copyright Hüseyin Emre Özdemir <h.emre.ozdemir@gmail.com> * @license http://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0 * @link https://github.com/ozdemirr/mikro-odeme */ 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 IKI_HAFTALIK_DENEMELI = 9; CONST UC_AYLIK_DENEMELI = 10; CONST ALTI_AYLIK_DENEMELI = 11; CONST OTUZ_GUNLUK = 13; }
Java
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 'DeletePersonalDataModel' public class DeletePersonalDataModel : PageModel #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel' { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly ILogger<DeletePersonalDataModel> _logger; #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.DeletePersonalDataModel(UserManager<ApplicationUser>, SignInManager<ApplicationUser>, ILogger<DeletePersonalDataModel>)' public DeletePersonalDataModel( #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.DeletePersonalDataModel(UserManager<ApplicationUser>, SignInManager<ApplicationUser>, ILogger<DeletePersonalDataModel>)' UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ILogger<DeletePersonalDataModel> logger) { _userManager = userManager; _signInManager = signInManager; _logger = logger; } [BindProperty] #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.Input' public InputModel Input { get; set; } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.Input' #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.InputModel' public class InputModel #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.InputModel' { [Required] [DataType(DataType.Password)] #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.InputModel.Password' public string Password { get; set; } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.InputModel.Password' } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.RequirePassword' public bool RequirePassword { get; set; } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.RequirePassword' #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.OnGet()' public async Task<IActionResult> OnGet() #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.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 'DeletePersonalDataModel.OnPostAsync()' public async Task<IActionResult> OnPostAsync() #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.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 InvalidOperationException($"Unexpected error occurred deleteing user with ID '{userId}'."); } await _signInManager.SignOutAsync(); _logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId); return Redirect("~/"); } } }
Java
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 ConsiderTargetingSelf = true; public override void Process(Artifical.ActivationContext c) { var excludeSelf = ConsiderTargetingSelf ? null : c.Card; var candidates = c.Selector.GenerateCandidates(c.TriggerMessage, excludeSelf); var parameters = new TargetingRuleParameters(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(TargetingRuleParameters p); protected virtual IEnumerable<Targets> ForceSelectTargets(TargetingRuleParameters 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 CalculateAttackerScoreForThisTurn(Card attacker) { if (!attacker.CanAttack) return -1; return Combat.CouldBeBlockedByAny(attacker) ? 2 * attacker.Power.GetValueOrDefault() + attacker.Toughness.GetValueOrDefault() : 5 * attacker.CalculateCombatDamageAmount(singleDamageStep: false); } protected static int CalculateAttackingPotential(Card creature) { if (!creature.IsAbleToAttack) return 0; var damage = creature.CalculateCombatDamageAmount(singleDamageStep: false); if (creature.Has().AnyEvadingAbility) return 2 + damage; return damage; } protected int CalculateBlockerScore(Card card) { var count = Combat.CountHowManyThisCouldBlock(card); if (count > 0) { return count*10 + card.Toughness.GetValueOrDefault(); } return 0; } protected IEnumerable<Card> GetCandidatesForAttackerPowerToughnessIncrease(int? powerIncrease, int? toughnessIncrease, TargetingRuleParameters p) { return p.Candidates<Card>(ControlledBy.SpellOwner) .Where(x => x.IsAttacker) .Select( x => new { Card = x, Gain = QuickCombat.CalculateGainAttackerWouldGetIfPowerAndThoughnessWouldIncrease( 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> GetCandidatesForBlockerPowerToughnessIncrease(int? powerIncrease, int? toughnessIncrease, TargetingRuleParameters p) { return p.Candidates<Card>(ControlledBy.SpellOwner) .Where(x => x.IsBlocker) .Select( x => new { Card = x, Gain = QuickCombat.CalculateGainBlockerWouldGetIfPowerAndThougnessWouldIncrease( 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> GetCandidatesThatCanBeDestroyed(TargetingRuleParameters p, Func<TargetsCandidates, IList<TargetCandidates>> selector = null) { return p.Candidates<Card>(ControlledBy.SpellOwner, selector: selector) .Where(x => Stack.CanBeDestroyedByTopSpell(x.Card()) || Combat.CanBeDealtLeathalCombatDamage(x.Card())); } protected static IEnumerable<Card> GetBounceCandidates(TargetingRuleParameters 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); } } }
Java
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); } } }
Java
#include "buttons.c"
Java
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, HTTPDigestAuthHandler 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 test_parse_http_list(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 test_request_headers_dict(): """ The Request.headers dictionary is not a documented interface. It should stay that way, because the complete set of headers are only accessible through the .get_header(), .has_header(), .header_items() interface. However, .headers pre-dates those methods, and so real code will be using the dictionary. The introduction in 2.4 of those methods was a mistake for the same reason: code that previously saw all (urllib2 user)-provided headers in .headers now sees only a subset (and the function interface is ugly and incomplete). A better change would have been to replace .headers dict with a dict subclass (or UserDict.DictMixin instance?) that preserved the .headers interface and also provided access to the "unredirected" headers. It's probably too late to fix that, though. Check .capitalize() case normalization: >>> url = "http://example.com" >>> Request(url, headers={"Spam-eggs": "blah"}).headers["Spam-eggs"] 'blah' >>> Request(url, headers={"spam-EggS": "blah"}).headers["Spam-eggs"] 'blah' Currently, Request(url, "Spam-eggs").headers["Spam-Eggs"] raises KeyError, but that could be changed in future. """ def test_request_headers_methods(): """ Note the case normalization of header names here, to .capitalize()-case. This should be preserved for backwards-compatibility. (In the HTTP case, normalization to .title()-case is done by urllib2 before sending headers to http.client). >>> url = "http://example.com" >>> r = Request(url, headers={"Spam-eggs": "blah"}) >>> r.has_header("Spam-eggs") True >>> r.header_items() [('Spam-eggs', 'blah')] >>> r.add_header("Foo-Bar", "baz") >>> items = sorted(r.header_items()) >>> items [('Foo-bar', 'baz'), ('Spam-eggs', 'blah')] Note that e.g. r.has_header("spam-EggS") is currently False, and r.get_header("spam-EggS") returns None, but that could be changed in future. >>> r.has_header("Not-there") False >>> print(r.get_header("Not-there")) None >>> r.get_header("Not-there", "default") 'default' """ def test_password_manager(self): """ >>> mgr = urllib.request.HTTPPasswordMgr() >>> add = mgr.add_password >>> add("Some Realm", "http://example.com/", "joe", "password") >>> add("Some Realm", "http://example.com/ni", "ni", "ni") >>> add("c", "http://example.com/foo", "foo", "ni") >>> add("c", "http://example.com/bar", "bar", "nini") >>> add("b", "http://example.com/", "first", "blah") >>> add("b", "http://example.com/", "second", "spam") >>> add("a", "http://example.com", "1", "a") >>> add("Some Realm", "http://c.example.com:3128", "3", "c") >>> add("Some Realm", "d.example.com", "4", "d") >>> add("Some Realm", "e.example.com:3128", "5", "e") >>> mgr.find_user_password("Some Realm", "example.com") ('joe', 'password') >>> mgr.find_user_password("Some Realm", "http://example.com") ('joe', 'password') >>> mgr.find_user_password("Some Realm", "http://example.com/") ('joe', 'password') >>> mgr.find_user_password("Some Realm", "http://example.com/spam") ('joe', 'password') >>> mgr.find_user_password("Some Realm", "http://example.com/spam/spam") ('joe', 'password') >>> mgr.find_user_password("c", "http://example.com/foo") ('foo', 'ni') >>> mgr.find_user_password("c", "http://example.com/bar") ('bar', 'nini') Actually, this is really undefined ATM ## Currently, we use the highest-level path where more than one match: ## >>> mgr.find_user_password("Some Realm", "http://example.com/ni") ## ('joe', 'password') Use latest add_password() in case of conflict: >>> mgr.find_user_password("b", "http://example.com/") ('second', 'spam') No special relationship between a.example.com and example.com: >>> mgr.find_user_password("a", "http://example.com/") ('1', 'a') >>> mgr.find_user_password("a", "http://a.example.com/") (None, None) Ports: >>> mgr.find_user_password("Some Realm", "c.example.com") (None, None) >>> mgr.find_user_password("Some Realm", "c.example.com:3128") ('3', 'c') >>> mgr.find_user_password("Some Realm", "http://c.example.com:3128") ('3', 'c') >>> mgr.find_user_password("Some Realm", "d.example.com") ('4', 'd') >>> mgr.find_user_password("Some Realm", "e.example.com:3128") ('5', 'e') """ pass def test_password_manager_default_port(self): """ >>> mgr = urllib.request.HTTPPasswordMgr() >>> add = mgr.add_password The point to note here is that we can't guess the default port if there's no scheme. This applies to both add_password and find_user_password. >>> add("f", "http://g.example.com:80", "10", "j") >>> add("g", "http://h.example.com", "11", "k") >>> add("h", "i.example.com:80", "12", "l") >>> add("i", "j.example.com", "13", "m") >>> mgr.find_user_password("f", "g.example.com:100") (None, None) >>> mgr.find_user_password("f", "g.example.com:80") ('10', 'j') >>> mgr.find_user_password("f", "g.example.com") (None, None) >>> mgr.find_user_password("f", "http://g.example.com:100") (None, None) >>> mgr.find_user_password("f", "http://g.example.com:80") ('10', 'j') >>> mgr.find_user_password("f", "http://g.example.com") ('10', 'j') >>> mgr.find_user_password("g", "h.example.com") ('11', 'k') >>> mgr.find_user_password("g", "h.example.com:80") ('11', 'k') >>> mgr.find_user_password("g", "http://h.example.com:80") ('11', 'k') >>> mgr.find_user_password("h", "i.example.com") (None, None) >>> mgr.find_user_password("h", "i.example.com:80") ('12', 'l') >>> mgr.find_user_password("h", "http://i.example.com:80") ('12', 'l') >>> mgr.find_user_password("i", "j.example.com") ('13', 'm') >>> mgr.find_user_password("i", "j.example.com:80") (None, None) >>> mgr.find_user_password("i", "http://j.example.com") ('13', 'm') >>> mgr.find_user_password("i", "http://j.example.com:80") (None, None) """ class MockOpener: addheaders = [] def open(self, req, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): 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._GLOBAL_DEFAULT_TIMEOUT): 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 add_ordered_mock_handlers() 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 add_ordered_mock_handlers(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 test_add_non_handler(self): class NonHandler(object): pass self.assertRaises(TypeError, OpenerDirector().add_handler, NonHandler()) def test_badly_named_methods(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 = add_ordered_mock_handlers(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 = add_ordered_mock_handlers(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 = add_ordered_mock_handlers(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 = add_ordered_mock_handlers(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 = add_ordered_mock_handlers(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._GLOBAL_DEFAULT_TIMEOUT): 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.add_unredirected_header("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/x-www-form-urlencoded") # 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.add_unredirected_header("Content-length", "foo") req.add_unredirected_header("Content-type", "bar") req.add_unredirected_header("Host", "baz") req.add_unredirected_header("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 test_http_doubleslash(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 test_fixpath_in_weirdurls(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://www.python.org?getspam' 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://www.python.org' 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._GLOBAL_DEFAULT_TIMEOUT req.add_header("Nonsense", "viking=withhold") if data is not None: req.add_header("Content-Length", str(len(data))) req.add_unredirected_header("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._GLOBAL_DEFAULT_TIMEOUT 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._GLOBAL_DEFAULT_TIMEOUT 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._GLOBAL_DEFAULT_TIMEOUT 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 test_cookie_redirect(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://www.example.com/", "spam=eggs") hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n") hdeh = urllib.request.HTTPDefaultErrorHandler() hrh = urllib.request.HTTPRedirectHandler() cp = urllib.request.HTTPCookieProcessor(cj) o = build_test_opener(hh, hdeh, hrh, cp) o.open("http://www.example.com/") 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 = add_ordered_mock_handlers(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://www.perl.org/") self.assertEqual(req.get_host(), "www.perl.org") r = o.open(req) self.assertEqual(req.get_host(), "proxy.example.com") req = Request("http://www.python.org") 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 = add_ordered_mock_handlers(o, meth_spec) req = Request("https://www.example.com/") 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 test_proxy_https_proxy_authorization(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://www.example.com/") 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.HTTPBasicAuthHandler(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_auth_with_single_quoted_realm(self): self.test_basic_auth(quote_char="'") def test_proxy_basic_auth(self): opener = OpenerDirector() ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128")) opener.add_handler(ph) password_manager = MockPasswordManager() auth_handler = urllib.request.ProxyBasicAuthHandler(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 test_basic_and_digest_auth_handlers(self): # HTTPDigestAuthHandler threw an exception if it couldn't handle a 40* # response (http://python.org/sf/1479302), where it should instead # return None to allow another handler (especially # HTTPBasicAuthHandler) to handle the response. # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must # try digest first (since it's the strongest auth scheme), so we record # order of calls here to check digest comes first: class RecordingOpenerDirector(OpenerDirector): def __init__(self): OpenerDirector.__init__(self) self.recorded = [] def record(self, info): self.recorded.append(info) class TestDigestAuthHandler(urllib.request.HTTPDigestAuthHandler): def http_error_401(self, *args, **kwds): self.parent.record("digest") urllib.request.HTTPDigestAuthHandler.http_error_401(self, *args, **kwds) class TestBasicAuthHandler(urllib.request.HTTPBasicAuthHandler): def http_error_401(self, *args, **kwds): self.parent.record("basic") urllib.request.HTTPBasicAuthHandler.http_error_401(self, *args, **kwds) opener = RecordingOpenerDirector() password_manager = MockPasswordManager() digest_handler = TestDigestAuthHandler(password_manager) basic_handler = TestBasicAuthHandler(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://www.python.org/~jeremy/") self.post = Request("http://www.python.org/~jeremy/", "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://www.python.org/~jeremy/", self.get.get_full_url()) def test_selector(self): self.assertEqual("/~jeremy/", self.get.get_selector()) req = Request("http://www.python.org/") 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 test_get_host_unquote(self): req = Request("http://www.%70ython.org/") 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://www.python.org>") self.assertEqual("www.python.org", req.get_host()) def test_urlwith_fragment(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)
Java
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 2017年1月4日 * */ public class Webpage { /** * 附件id列表 */ public List<String> attachmentList; /** * 图片ID列表 */ public List<String> imageList; /** * 正文 */ private String content; /** * 标题 */ private String title; /** * 链接 */ private String url; /** * 域名 */ private String domain; /** * 爬虫id,可以认为是taskid */ private String spiderUUID; /** * 模板id */ @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(); } }
Java