blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
a5d8e840caf16dfe3670ac8cb0fd0b409e21bc56
cb53a0cff7733bc8f5c70597009580287543bb72
/AutoSave/2010/inc/dbfiler.h
872905a7349a40193f2968c58fc46185e32b394f
[ "MIT" ]
permissive
15831944/AllDemo
d23b900f15fe4b786577f60d03a7b72b8dc8bf09
fe4f56ce91afc09e034ddc80769adf9cc5daef81
refs/heads/master
2023-03-15T20:49:15.385750
2014-08-27T07:42:24
2014-08-27T07:42:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
28,410
h
// #ifndef AD_DBFILER_H #define AD_DBFILER_H // // (C) Copyright 1993-2009 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // // // DBFILER.H -- AutoCAD Database Filer Definitions // // DESCRIPTION: // // This file contains "filer" class definitions, which are passed to // AcDbObject objects by their parent AcDbDatabase object to // perform I/O operations in various contexts. // // Common Filer Contracts are: // // 1. The Database object always controls the creation of the // filers, and passing them to objects. The Database object // itself surrounds filing calls with I/O of class name/ID/DXF_name // maps, and common object information such as class IDs/DXF names, // checksums, record lengths and other common record information. // The database object also handles file section and object // sentinels for database recovery purposes. // // 2. For different I/O contexts, 3 different sets of AcDbObject // members are defined: DXF, DWG File, and Paging // While DWG File and Paging members are supplied pagers of the // same abstract class, implementations of some members, // particularly those concerned with AcDbObjectId and AcDbHandle objects, // are very different. Usage contract differs as follows, reason being // that notification chains are NOT limited to database objects: // // Paging: For Notification chains, use "void" filer method to // save/restore pointer. Do not bother to pull out // of other notification chains. // // DWG file: Pull out of other notification chains, and record // what is needed for reconstruction. // // 3. The filer methods of AcDbObject subclasses are named the same // as the parent class's methods, with "Fields" appended (as in // dwgInFields()). Each such method (with a few exceptions in // class AcDbEntity) must invoke the same method in its parent // *before* performing any of its own filing actions. #include <stdarg.h> #include "AdAChar.h" #include "acdb.h" #include "gepnt2d.h" #include "gepnt3d.h" #include "gevec3d.h" #include "gescl3d.h" #include "adsdef.h" #pragma pack (push, 8) class AcDbAuditInfo; class AcDbFilerController; class AcDbHandle; class AcDbIdRefQueue; class AcString; class ADESK_NO_VTABLE AcDbDwgFiler: public AcRxObject // // Abstract class for DWG file and paging I/O. While protocol is virtually // the same, the implementations will be different, and so will usage. DWG // filer will do byte-reversal, and convert AcDbStub and AcDbHandle values // to/from char* values // // This will also stand as an abstract class for common R14, R13, and R12 // backwards/forwards compatibility for DWG. // // The pager would presumably direct I/O, no conversions, and directly // copies"void*" values for things like pointers to reactor sets. // // Reactor sets will remain in memory when the underlying object is paged out, // while DWG I/O requires dissolution an entities presence on reactor chains // when written, and reconstruction of the same when read back in. // // For each filer data type Xxx, there is a pair of write functions // writeXxx(Xxx) and writeItem(Xxx). The writeItem() functions, defined // inline in terms of the writeXxx() functions, can be used when it is // convenient or appropriate to let the argument type determine which function // to call. The writeXxx() functions are pure-virtual, i.e., must be defined // by all concrete subclasses. // // The same applies to the read functions. // // Filers may also implement CRC accumulation. // { public: ACRX_DECLARE_MEMBERS(AcDbDwgFiler); AcDbDwgFiler(); virtual ~AcDbDwgFiler(); virtual Acad::ErrorStatus filerStatus() const = 0; virtual AcDb::FilerType filerType() const = 0; virtual void setFilerStatus(Acad::ErrorStatus) = 0; virtual void resetFilerStatus() = 0; // version of the drawing file being read or written by this filer virtual Acad::ErrorStatus dwgVersion(AcDb::AcDbDwgVersion &, AcDb::MaintenanceReleaseVersion &) const; // readXxx() and writeXxx() functions // virtual Acad::ErrorStatus readHardOwnershipId(AcDbHardOwnershipId*) = 0; virtual Acad::ErrorStatus writeHardOwnershipId( const AcDbHardOwnershipId&) = 0; virtual Acad::ErrorStatus readSoftOwnershipId(AcDbSoftOwnershipId*) = 0; virtual Acad::ErrorStatus writeSoftOwnershipId( const AcDbSoftOwnershipId&) = 0; virtual Acad::ErrorStatus readHardPointerId(AcDbHardPointerId*) = 0; virtual Acad::ErrorStatus writeHardPointerId(const AcDbHardPointerId&) = 0; virtual Acad::ErrorStatus readSoftPointerId(AcDbSoftPointerId*) = 0; virtual Acad::ErrorStatus writeSoftPointerId(const AcDbSoftPointerId&) = 0; virtual Acad::ErrorStatus readInt8(Adesk::Int8 *) = 0; virtual Acad::ErrorStatus writeInt8(Adesk::Int8 ) = 0; // These are to be removed in a future release. Please use // readInt8 or writeInt8 instead. // // Todo: decide whether a readAChar() and writeAChar() are needed... inline Acad::ErrorStatus readChar(Adesk::Int8 *p) { return this->readInt8(p); } inline Acad::ErrorStatus writeChar(Adesk::Int8 c) { return this->writeInt8(c); } // Note: use of readString(ACHAR **) is discouraged, because // caller has to free the returned string. It may be phased // out in a future release. virtual Acad::ErrorStatus readString(ACHAR **) = 0; virtual Acad::ErrorStatus writeString(const ACHAR *) = 0; virtual Acad::ErrorStatus readString(AcString &) = 0; virtual Acad::ErrorStatus writeString(const AcString &) = 0; virtual Acad::ErrorStatus readBChunk(ads_binary *) = 0; virtual Acad::ErrorStatus writeBChunk(const ads_binary&) = 0; virtual Acad::ErrorStatus readAcDbHandle(AcDbHandle*) = 0; virtual Acad::ErrorStatus writeAcDbHandle(const AcDbHandle&) = 0; virtual Acad::ErrorStatus readInt64(Adesk::Int64*) = 0; virtual Acad::ErrorStatus writeInt64(Adesk::Int64) = 0; virtual Acad::ErrorStatus readInt32(Adesk::Int32*) = 0; virtual Acad::ErrorStatus writeInt32(Adesk::Int32) = 0; virtual Acad::ErrorStatus readInt16(Adesk::Int16*) = 0; virtual Acad::ErrorStatus writeInt16(Adesk::Int16) = 0; virtual Acad::ErrorStatus readUInt64(Adesk::UInt64*) = 0; virtual Acad::ErrorStatus writeUInt64(Adesk::UInt64) = 0; virtual Acad::ErrorStatus readUInt32(Adesk::UInt32*) = 0; virtual Acad::ErrorStatus writeUInt32(Adesk::UInt32) = 0; virtual Acad::ErrorStatus readUInt16(Adesk::UInt16*) = 0; virtual Acad::ErrorStatus writeUInt16(Adesk::UInt16) = 0; virtual Acad::ErrorStatus readUInt8(Adesk::UInt8*) = 0; virtual Acad::ErrorStatus writeUInt8(Adesk::UInt8) = 0; #ifdef Adesk_Boolean_is_bool virtual Acad::ErrorStatus readInt(int*) = 0; virtual Acad::ErrorStatus writeInt(int) = 0; #endif virtual Acad::ErrorStatus readBoolean(Adesk::Boolean*) = 0; virtual Acad::ErrorStatus writeBoolean(Adesk::Boolean) = 0; virtual Acad::ErrorStatus readBool(bool*) = 0; virtual Acad::ErrorStatus writeBool(bool) = 0; virtual Acad::ErrorStatus readDouble(double*) = 0; virtual Acad::ErrorStatus writeDouble(double) = 0; virtual Acad::ErrorStatus readPoint2d(AcGePoint2d*) = 0; virtual Acad::ErrorStatus writePoint2d(const AcGePoint2d&) = 0; virtual Acad::ErrorStatus readPoint3d(AcGePoint3d*) = 0; virtual Acad::ErrorStatus writePoint3d(const AcGePoint3d&) = 0; virtual Acad::ErrorStatus readVector2d(AcGeVector2d*) = 0; virtual Acad::ErrorStatus writeVector2d(const AcGeVector2d&) = 0; virtual Acad::ErrorStatus readVector3d(AcGeVector3d*) = 0; virtual Acad::ErrorStatus writeVector3d(const AcGeVector3d&) = 0; virtual Acad::ErrorStatus readScale3d(AcGeScale3d*) = 0; virtual Acad::ErrorStatus writeScale3d(const AcGeScale3d&) = 0; virtual Acad::ErrorStatus readBytes(void *, Adesk::UIntPtr) = 0; virtual Acad::ErrorStatus writeBytes(const void *, Adesk::UIntPtr) = 0; virtual Acad::ErrorStatus readAddress(void **); virtual Acad::ErrorStatus writeAddress(const void *); // readItem() and writeItem() functions // Acad::ErrorStatus readItem(AcDbHardOwnershipId*); Acad::ErrorStatus writeItem(const AcDbHardOwnershipId&); Acad::ErrorStatus readItem(AcDbSoftOwnershipId*); Acad::ErrorStatus writeItem(const AcDbSoftOwnershipId&); Acad::ErrorStatus readItem(AcDbHardPointerId*); Acad::ErrorStatus writeItem(const AcDbHardPointerId&); Acad::ErrorStatus readItem(AcDbSoftPointerId*); Acad::ErrorStatus writeItem(const AcDbSoftPointerId&); // Note: there are no filer methods for explicitly reading or // writing a single text character. There are readChar() and // writeChar(), but these do not do any code page translation // on the data. I.e., they treat it as a signed 8-bit // integer value. Since they are thus the same as readInt8() // and writeInt8(), they are being deprecated. // Acad::ErrorStatus readItem(ACHAR **); Acad::ErrorStatus writeItem(const ACHAR *); Acad::ErrorStatus readItem(ads_binary*); Acad::ErrorStatus writeItem(const ads_binary&); Acad::ErrorStatus readItem(AcDbHandle*); Acad::ErrorStatus writeItem(const AcDbHandle&); Acad::ErrorStatus readItem(Adesk::Int32*); Acad::ErrorStatus writeItem(Adesk::Int32); Acad::ErrorStatus readItem(Adesk::Int16*); Acad::ErrorStatus writeItem(Adesk::Int16); Acad::ErrorStatus readItem(Adesk::Int8 *); Acad::ErrorStatus writeItem(Adesk::Int8); Acad::ErrorStatus readItem(Adesk::UInt32*); Acad::ErrorStatus writeItem(Adesk::UInt32); Acad::ErrorStatus readItem(Adesk::UInt16*); Acad::ErrorStatus writeItem(Adesk::UInt16); Acad::ErrorStatus readItem(Adesk::UInt8*); Acad::ErrorStatus writeItem(Adesk::UInt8); #ifdef Adesk_Boolean_is_bool Acad::ErrorStatus readItem(int*); Acad::ErrorStatus writeItem(int); #else Acad::ErrorStatus readItem(Adesk::Boolean*); Acad::ErrorStatus writeItem(Adesk::Boolean); #endif Acad::ErrorStatus readItem(bool*); Acad::ErrorStatus writeItem(bool); Acad::ErrorStatus readItem(double*); Acad::ErrorStatus writeItem(double); Acad::ErrorStatus readItem(AcGePoint2d*); Acad::ErrorStatus writeItem(const AcGePoint2d&); Acad::ErrorStatus readItem(AcGePoint3d*); Acad::ErrorStatus writeItem(const AcGePoint3d&); Acad::ErrorStatus readItem(AcGeVector2d*); Acad::ErrorStatus writeItem(const AcGeVector2d&); Acad::ErrorStatus readItem(AcGeVector3d*); Acad::ErrorStatus writeItem(const AcGeVector3d&); Acad::ErrorStatus readItem(AcGeScale3d*); Acad::ErrorStatus writeItem(const AcGeScale3d&); Acad::ErrorStatus readItem(void *, Adesk::UIntPtr); Acad::ErrorStatus writeItem(const void *, Adesk::UIntPtr); Acad::ErrorStatus readItem(void **); Acad::ErrorStatus writeItem(const void *); virtual Acad::ErrorStatus seek(Adesk::Int64 nOffset, int nMethod) = 0; virtual Adesk::Int64 tell() const = 0; virtual Acad::ErrorStatus addReferences(AcDbIdRefQueue& /*qToAbsorb*/); virtual bool usesReferences() const; virtual AcDbAuditInfo * getAuditInfo() const; virtual AcDbFilerController& controller() const; private: AcDbFilerController& mController; }; class ADESK_NO_VTABLE AcDbDxfFiler: public AcRxObject { public: ACRX_DECLARE_MEMBERS(AcDbDxfFiler); virtual int rewindFiler() = 0; virtual Acad::ErrorStatus filerStatus() const = 0; virtual void resetFilerStatus() = 0; virtual Acad::ErrorStatus setError(Acad::ErrorStatus, const ACHAR *, ...); virtual Acad::ErrorStatus setError(const ACHAR *, ...); virtual const ACHAR * errorMessage() const; virtual AcDb::FilerType filerType() const = 0; // working database being read or written by this filer virtual AcDbDatabase* database() const = 0; // version of the drawing file being read or written by this filer virtual Acad::ErrorStatus dwgVersion(AcDb::AcDbDwgVersion &, AcDb::MaintenanceReleaseVersion &) const; virtual int precision() const; virtual void setPrecision(int prec); // Number of decimal digits printed in ASCII DXF file // enum { kDfltPrec = -1, kMaxPrec = 16 }; // readXxx and writeXxx functions // virtual Acad::ErrorStatus readResBuf (resbuf*); virtual Acad::ErrorStatus writeResBuf (const resbuf&); virtual Acad::ErrorStatus writeObjectId(AcDb::DxfCode, const AcDbObjectId&) = 0; virtual Acad::ErrorStatus writeInt8 (AcDb::DxfCode, Adesk::Int8) = 0; // This is to be removed in a future release inline Acad::ErrorStatus writeChar (AcDb::DxfCode c, Adesk::Int8 n) { return this->writeInt8(c, n); } virtual Acad::ErrorStatus writeString (AcDb::DxfCode, const ACHAR *) = 0; virtual Acad::ErrorStatus writeString (AcDb::DxfCode, const AcString &) = 0; virtual Acad::ErrorStatus writeBChunk (AcDb::DxfCode, const ads_binary&) = 0; virtual Acad::ErrorStatus writeAcDbHandle(AcDb::DxfCode, const AcDbHandle&) = 0; virtual Acad::ErrorStatus writeInt64 (AcDb::DxfCode, Adesk::Int64) = 0; virtual Acad::ErrorStatus writeInt32 (AcDb::DxfCode, Adesk::Int32) = 0; virtual Acad::ErrorStatus writeInt16 (AcDb::DxfCode, Adesk::Int16) = 0; virtual Acad::ErrorStatus writeUInt64 (AcDb::DxfCode, Adesk::UInt64) = 0; virtual Acad::ErrorStatus writeUInt32 (AcDb::DxfCode, Adesk::UInt32) = 0; virtual Acad::ErrorStatus writeUInt16 (AcDb::DxfCode, Adesk::UInt16) = 0; virtual Acad::ErrorStatus writeUInt8 (AcDb::DxfCode, Adesk::UInt8) = 0; virtual Acad::ErrorStatus writeBoolean (AcDb::DxfCode, Adesk::Boolean) = 0; #ifdef Adesk_Boolean_is_bool virtual Acad::ErrorStatus writeInt (AcDb::DxfCode, int) = 0; #endif virtual Acad::ErrorStatus writeBool (AcDb::DxfCode, bool) = 0; virtual Acad::ErrorStatus writeDouble (AcDb::DxfCode, double, int = kDfltPrec) = 0; virtual Acad::ErrorStatus writePoint2d (AcDb::DxfCode, const AcGePoint2d&, int = kDfltPrec) = 0; virtual Acad::ErrorStatus writePoint3d (AcDb::DxfCode, const AcGePoint3d&, int = kDfltPrec) = 0; virtual Acad::ErrorStatus writeVector2d(AcDb::DxfCode, const AcGeVector2d&, int = kDfltPrec) = 0; virtual Acad::ErrorStatus writeVector3d(AcDb::DxfCode, const AcGeVector3d&, int = kDfltPrec) = 0; virtual Acad::ErrorStatus writeScale3d (AcDb::DxfCode, const AcGeScale3d&, int = kDfltPrec) = 0; // readItem and writeItem functions // Acad::ErrorStatus readItem (resbuf* pItem); Acad::ErrorStatus writeItem (const resbuf& pItem); Acad::ErrorStatus writeItem (AcDb::DxfCode, const AcDbObjectId&); Acad::ErrorStatus writeItem (AcDb::DxfCode, const ACHAR *); Acad::ErrorStatus writeItem (AcDb::DxfCode, const ads_binary&); Acad::ErrorStatus writeItem (AcDb::DxfCode, const AcDbHandle&); Acad::ErrorStatus writeItem (AcDb::DxfCode, Adesk::Int32); Acad::ErrorStatus writeItem (AcDb::DxfCode, Adesk::Int16); Acad::ErrorStatus writeItem (AcDb::DxfCode, Adesk::Int8); Acad::ErrorStatus writeItem (AcDb::DxfCode, Adesk::UInt32); Acad::ErrorStatus writeItem (AcDb::DxfCode, Adesk::UInt16); Acad::ErrorStatus writeItem (AcDb::DxfCode, Adesk::UInt8); #ifdef Adesk_Boolean_is_bool Acad::ErrorStatus writeItem (AcDb::DxfCode, int); #else // CAUTION: "int" parameters go to writeBoolean Acad::ErrorStatus writeItem (AcDb::DxfCode, Adesk::Boolean); #endif Acad::ErrorStatus writeItem (AcDb::DxfCode, bool); Acad::ErrorStatus writeItem (AcDb::DxfCode, double, int = kDfltPrec); Acad::ErrorStatus writeItem (AcDb::DxfCode, const AcGePoint2d&, int = kDfltPrec); Acad::ErrorStatus writeItem (AcDb::DxfCode, const AcGePoint3d&, int = kDfltPrec); Acad::ErrorStatus writeItem (AcDb::DxfCode, const AcGeVector2d&, int = kDfltPrec); Acad::ErrorStatus writeItem (AcDb::DxfCode, const AcGeVector3d&, int = kDfltPrec); Acad::ErrorStatus writeItem (AcDb::DxfCode, const AcGeScale3d&, int = kDfltPrec); virtual Acad::ErrorStatus writeXDataStart (); virtual bool includesDefaultValues() const = 0; virtual Acad::ErrorStatus pushBackItem(); virtual bool atEOF(); virtual bool atSubclassData(const ACHAR *); virtual bool atExtendedData(); virtual bool atEndOfObject(); virtual void haltAtClassBoundries(bool); virtual Acad::ErrorStatus writeEmbeddedObjectStart(); virtual bool atEmbeddedObjectStart(); virtual double elevation() const; virtual double thickness() const; virtual bool isModifyingExistingObject() const; AcDbDxfFiler(); virtual ~AcDbDxfFiler(); AcDbFilerController& controller() const; private: AcDbFilerController& mController; virtual Acad::ErrorStatus setVAError(Acad::ErrorStatus, const ACHAR *, va_list); }; inline Acad::ErrorStatus AcDbDwgFiler::readItem(AcDbHardOwnershipId* pId) { return readHardOwnershipId(pId); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(const AcDbHardOwnershipId& pId) { return writeHardOwnershipId(pId); } inline Acad::ErrorStatus AcDbDwgFiler::readItem(AcDbSoftOwnershipId* pId) { return readSoftOwnershipId(pId); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(const AcDbSoftOwnershipId& pId) { return writeSoftOwnershipId(pId); } inline Acad::ErrorStatus AcDbDwgFiler::readItem(AcDbHardPointerId* pId) { return readHardPointerId(pId); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(const AcDbHardPointerId& pId) { return writeHardPointerId(pId); } inline Acad::ErrorStatus AcDbDwgFiler::readItem(AcDbSoftPointerId* pId) { return readSoftPointerId(pId); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(const AcDbSoftPointerId& pId) { return writeSoftPointerId(pId); } inline Acad::ErrorStatus AcDbDwgFiler::readItem(ACHAR ** pVal) { return readString(pVal); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(const ACHAR * val) { return writeString(val); } inline Acad::ErrorStatus AcDbDwgFiler::readItem(ads_binary* pVal) { return readBChunk(pVal); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(const ads_binary& val) { return writeBChunk(val); } inline Acad::ErrorStatus AcDbDwgFiler::readItem(AcDbHandle* pVal) { return readAcDbHandle(pVal); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(const AcDbHandle& val) { return writeAcDbHandle(val); } inline Acad::ErrorStatus AcDbDwgFiler::readItem(Adesk::Int32* pVal) { return readInt32(pVal); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(Adesk::Int32 val) { return writeInt32(val); } inline Acad::ErrorStatus AcDbDwgFiler::readItem(Adesk::Int16* pVal) { return readInt16(pVal); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(Adesk::Int16 val) { return writeInt16(val); } inline Acad::ErrorStatus AcDbDwgFiler::readItem(Adesk::Int8 * pVal) { return this->readInt8(pVal); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(Adesk::Int8 val) { return this->writeInt8(val); } inline Acad::ErrorStatus AcDbDwgFiler::readItem(Adesk::UInt32* pVal) { return readUInt32(pVal); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(Adesk::UInt32 val) { return writeUInt32(val); } inline Acad::ErrorStatus AcDbDwgFiler::readItem(Adesk::UInt16* pVal) { return readUInt16(pVal); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(Adesk::UInt16 val) { return writeUInt16(val); } inline Acad::ErrorStatus AcDbDwgFiler::readItem(Adesk::UInt8* pVal) { return readUInt8(pVal); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(Adesk::UInt8 val) { return writeUInt8(val); } #ifdef Adesk_Boolean_is_bool inline Acad::ErrorStatus AcDbDwgFiler::readItem(int* pVal) { return readInt(pVal); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(int val) { return writeInt(val); } #else inline Acad::ErrorStatus AcDbDwgFiler::readItem(Adesk::Boolean* pVal) { return readBoolean(pVal); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(Adesk::Boolean val) { return writeBoolean(val); } #endif inline Acad::ErrorStatus AcDbDwgFiler::readItem(bool* pVal) { return readBool(pVal); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(bool val) { return writeBool(val); } inline Acad::ErrorStatus AcDbDwgFiler::readItem(double* pVal) { return readDouble(pVal); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(double val) { return writeDouble(val); } inline Acad::ErrorStatus AcDbDwgFiler::readItem(AcGePoint2d* pVal) { return readPoint2d(pVal); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(const AcGePoint2d& val) { return writePoint2d(val); } inline Acad::ErrorStatus AcDbDwgFiler::readItem(AcGePoint3d* pVal) { return readPoint3d(pVal); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(const AcGePoint3d& val) { return writePoint3d(val); } inline Acad::ErrorStatus AcDbDwgFiler::readItem(AcGeVector2d* pVal) { return readVector2d(pVal); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(const AcGeVector2d& val) { return writeVector2d(val); } inline Acad::ErrorStatus AcDbDwgFiler::readItem(AcGeVector3d* pVal) { return readVector3d(pVal); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(const AcGeVector3d& val) { return writeVector3d(val); } inline Acad::ErrorStatus AcDbDwgFiler::readItem(AcGeScale3d* pVal) { return readScale3d(pVal); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(const AcGeScale3d& val) { return writeScale3d(val); } inline Acad::ErrorStatus AcDbDwgFiler::readItem(void *buf, Adesk::UIntPtr cnt) { return readBytes(buf, cnt); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(const void *buf, Adesk::UIntPtr cnt) { return writeBytes(buf, cnt); } inline Acad::ErrorStatus AcDbDwgFiler::readItem(void **pp) { return readAddress(pp); } inline Acad::ErrorStatus AcDbDwgFiler::writeItem(const void *p) { return writeAddress(p); } inline Acad::ErrorStatus AcDbDxfFiler::readItem(resbuf* pVal) { return readResBuf(pVal); } inline Acad::ErrorStatus AcDbDxfFiler::writeItem(const resbuf& val) { return writeResBuf(val); } inline Acad::ErrorStatus AcDbDxfFiler::writeItem(AcDb::DxfCode dc, const AcDbObjectId& id) { return writeObjectId(dc, id); } inline Acad::ErrorStatus AcDbDxfFiler::writeItem(AcDb::DxfCode dc, const ACHAR * val) { return writeString(dc, val); } inline Acad::ErrorStatus AcDbDxfFiler::writeItem(AcDb::DxfCode dc, const ads_binary& val) { return writeBChunk(dc, val); } inline Acad::ErrorStatus AcDbDxfFiler::writeItem(AcDb::DxfCode dc, const AcDbHandle& val) { return writeAcDbHandle(dc, val); } inline Acad::ErrorStatus AcDbDxfFiler::writeItem(AcDb::DxfCode dc, Adesk::Int32 val) { return writeInt32(dc, val); } inline Acad::ErrorStatus AcDbDxfFiler::writeItem(AcDb::DxfCode dc, Adesk::Int16 val) { return writeInt16(dc, val); } inline Acad::ErrorStatus AcDbDxfFiler::writeItem(AcDb::DxfCode dc, Adesk::Int8 val) { return this->writeInt8(dc, val); } inline Acad::ErrorStatus AcDbDxfFiler::writeItem(AcDb::DxfCode dc, Adesk::UInt32 val) { return writeUInt32(dc, val); } inline Acad::ErrorStatus AcDbDxfFiler::writeItem(AcDb::DxfCode dc, Adesk::UInt16 val) { return writeUInt16(dc, val); } inline Acad::ErrorStatus AcDbDxfFiler::writeItem(AcDb::DxfCode dc, Adesk::UInt8 val) { return writeUInt8(dc, val); } #ifdef Adesk_Boolean_is_bool inline Acad::ErrorStatus AcDbDxfFiler::writeItem(AcDb::DxfCode dc, int val) { return writeInt(dc, val); } #else inline Acad::ErrorStatus AcDbDxfFiler::writeItem(AcDb::DxfCode dc, Adesk::Boolean val) { return writeBoolean(dc, val); } #endif inline Acad::ErrorStatus AcDbDxfFiler::writeItem(AcDb::DxfCode dc, bool val) { return writeBool(dc, val); } inline Acad::ErrorStatus AcDbDxfFiler::writeItem(AcDb::DxfCode dc, double val, int prec) { return writeDouble(dc, val, prec); } inline Acad::ErrorStatus AcDbDxfFiler::writeItem(AcDb::DxfCode dc, const AcGePoint2d& val, int prec) { return writePoint2d(dc, val, prec); } inline Acad::ErrorStatus AcDbDxfFiler::writeItem(AcDb::DxfCode dc, const AcGePoint3d& val, int prec) { return writePoint3d(dc, val, prec); } inline Acad::ErrorStatus AcDbDxfFiler::writeItem(AcDb::DxfCode dc, const AcGeVector2d& val, int prec) { return writeVector2d(dc, val, prec); } inline Acad::ErrorStatus AcDbDxfFiler::writeItem(AcDb::DxfCode dc, const AcGeVector3d& val, int prec) { return writeVector3d(dc, val, prec); } inline Acad::ErrorStatus AcDbDxfFiler::writeItem(AcDb::DxfCode dc, const AcGeScale3d& val, int prec) { return writeScale3d(dc, val, prec); } #pragma pack (pop) #endif
[ "lixiaolei2005-12@163.com" ]
lixiaolei2005-12@163.com
683fab6bf0ffd789ade813241180fc0910bf52e1
0d0e78c6262417fb1dff53901c6087b29fe260a0
/vpc/include/tencentcloud/vpc/v20170312/model/ModifyIp6AddressesBandwidthResponse.h
c6d87475a6f731e993d632743c3bc05fa9672b46
[ "Apache-2.0" ]
permissive
li5ch/tencentcloud-sdk-cpp
ae35ffb0c36773fd28e1b1a58d11755682ade2ee
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
refs/heads/master
2022-12-04T15:33:08.729850
2020-07-20T00:52:24
2020-07-20T00:52:24
281,135,686
1
0
Apache-2.0
2020-07-20T14:14:47
2020-07-20T14:14:46
null
UTF-8
C++
false
false
1,639
h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * 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. */ #ifndef TENCENTCLOUD_VPC_V20170312_MODEL_MODIFYIP6ADDRESSESBANDWIDTHRESPONSE_H_ #define TENCENTCLOUD_VPC_V20170312_MODEL_MODIFYIP6ADDRESSESBANDWIDTHRESPONSE_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Vpc { namespace V20170312 { namespace Model { /** * ModifyIp6AddressesBandwidth返回参数结构体 */ class ModifyIp6AddressesBandwidthResponse : public AbstractModel { public: ModifyIp6AddressesBandwidthResponse(); ~ModifyIp6AddressesBandwidthResponse() = default; CoreInternalOutcome Deserialize(const std::string &payload); private: }; } } } } #endif // !TENCENTCLOUD_VPC_V20170312_MODEL_MODIFYIP6ADDRESSESBANDWIDTHRESPONSE_H_
[ "zhiqiangfan@tencent.com" ]
zhiqiangfan@tencent.com
5785b2fbbdde4716000b82397604cfc5ae5233c7
e28883f9bde3f604dd9e8b265e234d7f28c7b2f9
/SJMQuant/SJMTradeInfra/Include/SJMHttpBundle/SJMHttpResponseStatus.h
b775feb20a5c149ad8e13fad6d119e340bee4459
[]
no_license
sjmohap/SJMQuant
64c097e5ba639dd0c004fce46f7fd8ca8c3c87c9
879eacf48bd2c83cbd05ab28f308ea5f740f100a
refs/heads/master
2020-03-28T08:49:38.994596
2018-11-19T04:28:08
2018-11-19T04:28:08
147,992,319
0
0
null
null
null
null
UTF-8
C++
false
false
421
h
#pragma once #include <string> #include <SJMHttpBundle/SJMHttpBundleCommonDef.h> class DLL_SJMHTTPBUNDLE SJMHttpResponseStatus { public: SJMHttpResponseStatus(unsigned response_status, const std::wstring& cs); SJMHttpResponseStatus() = default; bool wasSuccess() const; unsigned getStatusCode() const; std::wstring getResponseMsg() const; private: unsigned int _responseStatus = 0; std::wstring _responsMsg; };
[ "sjm0005@yahoo.in" ]
sjm0005@yahoo.in
6e258004e2129269b5db2587fa56869e05ed4e8f
66e6360325b781ed0791868765f1fd8a6303726f
/LQSearch/MiscellaneousPlots/7234PASFigure1SameFile/Comparison.cpp
7a9de896256cd8ccda60f0b17d6ed73ac24c3e86
[]
no_license
alintulu/FHead2011PhysicsProject
c969639b212d569198d8fce2f424ce866dcfa881
2568633d349810574354ad61b0abab24a40e510e
refs/heads/master
2022-04-28T14:19:30.534282
2020-04-23T17:17:32
2020-04-23T17:17:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,112
cpp
#include <string> #include <vector> #include <iostream> using namespace std; #include "TFile.h" #include "TTree.h" #include "TChain.h" #include "TH1D.h" #include "TH2D.h" #include "PlotHelper2.h" #include "SetStyle.h" #include "ReadLQ3Tree.h" #include "TauHelperFunctions2.h" int main(); void ReadSample(string Input, string OutputBase, double CrossSection, double Luminosity); int main() { SetStyle(); ReadSample("Samples/LM1_SUSY_sftsht_7TeV-pythia6_All.root", "LM1", 4.888, 1000); // pythia LO ReadSample("Samples/TTJets_TuneZ2_7TeV-madgraph-tauola_All.root", "TTbar", 165, 1000); // NNLL ReadSample("Samples/WJetsToLNu_TuneZ2_7TeV-madgraph-tauola_All.root", "W", 31314, 1000); // NNLO /* ReadSample("QCDSamples/CopiedFromT3SUSY_QCD_2jet_40to120.root", "QCD_2jet_40-120", 8804000 * 0.527, 1000); ReadSample("QCDSamples/CopiedFromT3SUSY_QCD_2jet_120to280.root", "QCD_2jet_120-280", 36260 * 0.296, 1000); ReadSample("QCDSamples/CopiedFromT3SUSY_QCD_2jet_280to500.root", "QCD_2jet_280-500", 377.1 * 0.240, 1000); ReadSample("QCDSamples/CopiedFromT3SUSY_QCD_2jet_500to5000.root", "QCD_2jet_500-5000", 13.14 * 0.251, 1000); ReadSample("QCDSamples/CopiedFromT3SUSY_QCD_3jet_40to120.root", "QCD_3jet_40-120", 3425000 * 0.303, 1000); ReadSample("QCDSamples/CopiedFromT3SUSY_QCD_3jet_120to280.root", "QCD_3jet_120-280", 50100 * 0.226, 1000); ReadSample("QCDSamples/CopiedFromT3SUSY_QCD_3jet_280to500.root", "QCD_3jet_280-500", 651.7 * 0.185, 1000); ReadSample("QCDSamples/CopiedFromT3SUSY_QCD_3jet_500to5000.root", "QCD_3jet_500-5000", 22.73 * 0.185, 1000); // ReadSample("QCDSamples/CopiedFromT3SUSY_QCD_4jet_40to120.root", "QCD_4jet_40-120", 467000 * 0.200, 1000); ReadSample("QCDSamples/CopiedFromT3SUSY_QCD_4jet_120to280.root", "QCD_4jet_120-280", 25680 * 0.174, 1000); ReadSample("QCDSamples/CopiedFromT3SUSY_QCD_4jet_280to500.root", "QCD_4jet_280-500", 470.8 * 0.143, 1000); ReadSample("QCDSamples/CopiedFromT3SUSY_QCD_4jet_500to5000.root", "QCD_4jet_500-5000", 17.97 * 0.142, 1000); ReadSample("QCDSamples/CopiedFromT3SUSY_QCD_5jet_40to120.root", "QCD_5jet_40-120", 64230 * 0.136, 1000); ReadSample("QCDSamples/CopiedFromT3SUSY_QCD_5jet_120to280.root", "QCD_5jet_120-280", 8187 * 0.130, 1000); ReadSample("QCDSamples/CopiedFromT3SUSY_QCD_5jet_280to500.root", "QCD_5jet_280-500", 232.9 * 0.116, 1000); ReadSample("QCDSamples/CopiedFromT3SUSY_QCD_5jet_500to5000.root", "QCD_5jet_500-5000", 9.325 * 0.110, 1000); // ReadSample("QCDSamples/CopiedFromT3SUSY_QCD_6jet_40to120.root", "QCD_6jet_40-120", 9800 * 0.118, 1000); ReadSample("QCDSamples/CopiedFromT3SUSY_QCD_6jet_120to280.root", "QCD_6jet_120-280", 2656 * 0.131, 1000); ReadSample("QCDSamples/CopiedFromT3SUSY_QCD_6jet_280to500.root", "QCD_6jet_280-500", 123.8 * 0.137, 1000); ReadSample("QCDSamples/CopiedFromT3SUSY_QCD_6jet_500to5000.root", "QCD_6jet_500-5000", 6.194 * 0.148, 1000); */ } void ReadSample(string Input, string OutputBase, double CrossSection, double Luminosity) { cout << "Start processing sample " << Input << endl; double NumberOfProcessedEvents = 0; TFile F(Input.c_str()); NumberOfProcessedEvents = ((TTree *)F.Get("LQ3Tree"))->GetEntries(); F.Close(); double Factor = CrossSection * Luminosity / NumberOfProcessedEvents; if(CrossSection < 0) // data! Factor = 1; cout << "ProcessedEvents = " << NumberOfProcessedEvents << endl; cout << "Event weight = " << Factor << endl; TChain Tree("LQ3Tree", "LQ3Tree"); Tree.AddFile(Input.c_str()); TreeRecord M; M.SetBranchAddress(&Tree); TFile OutputFile(Form("%s.root", OutputBase.c_str()), "RECREATE"); TH1D HMuon1PT("HMuon1PT", "Leading muon PT;PT (GeV/c)", 50, 0, 200); TH1D HMuon2PT("HMuon2PT", "Sub-leading muon PT;PT (GeV/c)", 50, 0, 200); TH1D HDiMuonMass("HDiMuonMass", "Di-muon mass;Mass (GeV/c^2)", 50, 0, 200); TH1D HLeadingPFJetPT("HLeadingPFJetPT", "Leading PF jet pt;PT (GeV/c)", 50, 0, 500); TH1D HSubLeadingPFJetPT("HSubLeadingPFJetPT", "Sub-leading PF jet pt;PT (GeV/c)", 50, 0, 500); TH1D HPFJetMR("HPFJetMR", "MR from PF system;MR (GeV/c^2)", 50, 0, 1000); TH1D HPFJetR("HPFJetR", "R from PF system;R", 50, 0, 1); TH1D HPFJetMRStar("HPFJetMRStar", "MRStar from PF system;MRStar (GeV/c^2)", 50, 0, 1000); TH1D HPFJetGammaMRStar("HPFJetGammaMRStar", "MR*** from PF system;MR*** (GeV/c^2)", 50, 0, 1000); TH1D HPFJetRStar("HPFJetRStar", "RStar from PF system;RStar", 50, 0, 1); TH1D HPFJetGammaMRStar_RStar05("HPFJetGammaMRStar_RStar05", "MR*** from PF system (RStar > 0.5);MR*** (GeV/c^2)", 50, 0, 1000); TH1D HPFMET("HPFMET", "PF MET distribution;MET (GeV)", 50, 0, 200); TH2D HPFJetGammaMRStarVsRStar("HPFJetGammaMRStarVsRStar", "GammaMRStar vs. RStar from PF system;GammaMRStar;RStar", 100, 0, 2000, 100, 0, 1.5); int EntryCount = Tree.GetEntries(); for(int iEntry = 0; iEntry < EntryCount; iEntry++) { if((iEntry + 1) % 250000 == 0) cout << "Processing entry " << iEntry + 1 << "/" << EntryCount << endl; Tree.GetEntry(iEntry); if(M.PFJetCount > 100) // woah.... cout << "Large number of jets!!!!" << endl; if(M.PFJetCount30 > 20) // :( continue; HMuon1PT.Fill(M.Muon1PT, Factor); HMuon2PT.Fill(M.Muon2PT, Factor); FourVector Mu1P, Mu2P; Mu1P.SetPtEtaPhi(M.Muon1PT, M.Muon1Eta, M.Muon1Phi); Mu2P.SetPtEtaPhi(M.Muon2PT, M.Muon2Eta, M.Muon2Phi); HDiMuonMass.Fill((Mu1P + Mu2P).GetMass(), Factor); if(M.PFJetCount > 0) HLeadingPFJetPT.Fill(M.PFJetPT[0], Factor); if(M.PFJetCount > 1) HSubLeadingPFJetPT.Fill(M.PFJetPT[1], Factor); vector<FourVector> GoodJets; for(int i = 0; i < M.PFJetCount && i < 100; i++) { if(M.PFJetPT[i] < 30) continue; if(M.PFJetEta[i] < -3 || M.PFJetEta[i] > 3) continue; FourVector NewJet; NewJet.SetPtEtaPhi(M.PFJetPT[i], M.PFJetEta[i], M.PFJetPhi[i]); GoodJets.push_back(NewJet); } if(GoodJets.size() > 20 || GoodJets.size() < 2) continue; vector<FourVector> Hemispheres = SplitIntoGroups(GoodJets, true); FourVector PFMET(0, M.PFMET[0], M.PFMET[1], 0); HPFMET.Fill(PFMET.GetPT(), Factor); double MR = GetMR(Hemispheres[0], Hemispheres[1]); double R = GetR(Hemispheres[0], Hemispheres[1], PFMET); double MRStar = GetMRStar(Hemispheres[0], Hemispheres[1]); double GammaRStar = GetGammaRStar(Hemispheres[0], Hemispheres[1]); double RStar = GetRStar(Hemispheres[0], Hemispheres[1], PFMET); HPFJetMR.Fill(MR, Factor); HPFJetR.Fill(R, Factor); HPFJetMRStar.Fill(MRStar, Factor); HPFJetGammaMRStar.Fill(MRStar * GammaRStar, Factor); HPFJetRStar.Fill(RStar, Factor); HPFJetGammaMRStarVsRStar.Fill(MRStar * GammaRStar, RStar * RStar, Factor); if(RStar > 0.5) HPFJetGammaMRStar_RStar05.Fill(MRStar * GammaRStar, Factor); } HMuon1PT.Write(); HMuon2PT.Write(); HDiMuonMass.Write(); HLeadingPFJetPT.Write(); HSubLeadingPFJetPT.Write(); HPFJetMR.Write(); HPFJetR.Write(); HPFJetMRStar.Write(); HPFJetGammaMRStar.Write(); HPFJetRStar.Write(); HPFJetGammaMRStarVsRStar.Write(); HPFJetGammaMRStar_RStar05.Write(); HPFMET.Write(); PsFileHelper PsFile(OutputBase + ".ps"); PsFile.AddTextPage(OutputBase); PsFile.AddPlot(HMuon1PT, "", true); PsFile.AddPlot(HMuon2PT, "", true); PsFile.AddPlot(HDiMuonMass, "", true); PsFile.AddPlot(HLeadingPFJetPT, "", true); PsFile.AddPlot(HSubLeadingPFJetPT, "", true); PsFile.AddPlot(HPFJetMR, "", true); PsFile.AddPlot(HPFJetR, "", true); PsFile.AddPlot(HPFJetMRStar, "", true); PsFile.AddPlot(HPFJetGammaMRStar, "", true); PsFile.AddPlot(HPFJetRStar, "", true); PsFile.AddPlot(HPFJetGammaMRStarVsRStar, "colz", false); PsFile.AddPlot(HPFJetGammaMRStar_RStar05, "", true); PsFile.AddPlot(HPFMET, "", true); PsFile.AddTimeStampPage(); PsFile.Close(); OutputFile.Close(); }
[ "yichen@positron01.hep.caltech.edu" ]
yichen@positron01.hep.caltech.edu
ac2cc23ebb8152390e54b13cbb3d9d12f7f29a6f
0179363e16864f8c9fa5445898c1237ef2e83901
/Sorting and Searching(Day 1)/two people meet each other.cpp
3db439d3be6935583e4a09eff2722979a9c327a3
[]
no_license
himanshu-sagar/CP_CipherSchools
4a051efe010e10a0745e6561f9268d5075a8dfaf
1c824f06d8d5d78330e5b509bf24a486c7102796
refs/heads/master
2023-03-10T21:06:35.063386
2021-02-22T17:22:17
2021-02-22T17:22:17
338,584,675
1
0
null
null
null
null
UTF-8
C++
false
false
785
cpp
#include<bits/stdc++.h> using namespace std; // time: O(n) space: O(1) bool checkMeeting(int a,int jump1,int b,int jump2) { if(a>b && jump1>=jump2) return false; if(b>a && jump2>=jump1) return false; if(a<b) { swap(a,b); swap(jump1,jump2); } while(a>=b) { if(a==b) { return true; } a=a+jump1; b=b+jump2; } return false; } // time: O(1) space: O(1) bool checkMeeting1(int a,int jump1,int b,int jump2) { if(a>b && jump1>=jump2) return false; if(b>a && jump2>=jump1) return false; if(a<b) { swap(a,b); swap(jump1,jump2); } return (a-b)%(jump2-jump1)==0; } int main() { cout<<checkMeeting1(6,6,4,9); }
[ "49094337+sagar-ML-Developer@users.noreply.github.com" ]
49094337+sagar-ML-Developer@users.noreply.github.com
cd172cedbce6b819f938c36afac04be234c328cc
57ac1261f06a461c636d6ccc7aa7881f024eb6c7
/myMotorizedPinwheel/myMotorizedPinwheel.ino
5c53b6092185e8b9b2c45148c7deba20eed91899
[]
no_license
rwbot/arduino
8c57767efcbb3795847f59c907f5cfc1f9fd5807
e9d5ad531f9acbee5551c56ab30e9908ea97a622
refs/heads/master
2020-03-07T15:30:33.252927
2018-03-31T17:53:27
2018-03-31T17:53:27
127,556,724
0
0
null
null
null
null
UTF-8
C++
false
false
369
ino
const int potPin = A0; const int motorPin = 9; int potVal; int potSpeed; void setup() { // put your setup code here, to run once: pinMode(potPin, INPUT); pinMode(motorPin, OUTPUT); } void loop() { // put your main code here, to run repeatedly: potVal = analogRead(potPin); potSpeed = map(potVal, 0, 1023, 0, 255); analogWrite(motorPin, potSpeed); }
[ "christopher.rowe@trincoll.edu" ]
christopher.rowe@trincoll.edu
7da644c9cdb5c2bb2591e8c1e20a28a62d258eb7
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/third_party/WebKit/Source/bindings/core/v8/ScriptEventListener.cpp
7680ad57152d5c7249360c3d1ae9bcddd43c7dad
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
6,196
cpp
/* * Copyright (C) 2009 Google Inc. 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. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * 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 * OWNER 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. */ #include "bindings/core/v8/ScriptEventListener.h" #include "bindings/core/v8/ScheduledAction.h" #include "bindings/core/v8/ScriptController.h" #include "bindings/core/v8/SourceLocation.h" #include "bindings/core/v8/V8AbstractEventListener.h" #include "bindings/core/v8/V8BindingForCore.h" #include "bindings/core/v8/WindowProxy.h" #include "core/dom/Document.h" #include "core/dom/DocumentParser.h" #include "core/dom/QualifiedName.h" #include "core/dom/events/EventListener.h" #include "core/frame/LocalFrame.h" #include "platform/bindings/ScriptState.h" #include "v8/include/v8.h" namespace blink { V8LazyEventListener* CreateAttributeEventListener( Node* node, const QualifiedName& name, const AtomicString& value, const AtomicString& event_parameter_name) { DCHECK(node); if (value.IsNull()) return nullptr; // FIXME: Very strange: we initialize zero-based number with '1'. TextPosition position(OrdinalNumber::FromZeroBasedInt(1), OrdinalNumber::First()); String source_url; v8::Isolate* isolate = ToIsolate(&node->GetDocument()); if (LocalFrame* frame = node->GetDocument().GetFrame()) { ScriptController& script_controller = frame->GetScriptController(); if (!node->GetDocument().CanExecuteScripts(kAboutToExecuteScript)) return nullptr; position = script_controller.EventHandlerPosition(); source_url = node->GetDocument().Url().GetString(); } return V8LazyEventListener::Create(name.LocalName(), event_parameter_name, value, source_url, position, node, isolate); } V8LazyEventListener* CreateAttributeEventListener( LocalFrame* frame, const QualifiedName& name, const AtomicString& value, const AtomicString& event_parameter_name) { if (!frame) return nullptr; if (value.IsNull()) return nullptr; if (!frame->GetDocument()->CanExecuteScripts(kAboutToExecuteScript)) return nullptr; TextPosition position = frame->GetScriptController().EventHandlerPosition(); String source_url = frame->GetDocument()->Url().GetString(); return V8LazyEventListener::Create(name.LocalName(), event_parameter_name, value, source_url, position, 0, ToIsolate(frame)); } v8::Local<v8::Object> EventListenerHandler(ExecutionContext* execution_context, EventListener* listener) { if (listener->GetType() != EventListener::kJSEventListenerType) return v8::Local<v8::Object>(); V8AbstractEventListener* v8_listener = static_cast<V8AbstractEventListener*>(listener); return v8_listener->GetListenerObject(execution_context); } v8::Local<v8::Function> EventListenerEffectiveFunction( v8::Isolate* isolate, v8::Local<v8::Object> handler) { v8::Local<v8::Function> function; if (handler->IsFunction()) { function = handler.As<v8::Function>(); } else if (handler->IsObject()) { v8::Local<v8::Value> property; // Try the "handleEvent" method (EventListener interface). if (handler ->Get(handler->CreationContext(), V8AtomicString(isolate, "handleEvent")) .ToLocal(&property) && property->IsFunction()) function = property.As<v8::Function>(); // Fall back to the "constructor" property. else if (handler ->Get(handler->CreationContext(), V8AtomicString(isolate, "constructor")) .ToLocal(&property) && property->IsFunction()) function = property.As<v8::Function>(); } if (!function.IsEmpty()) return GetBoundFunction(function); return v8::Local<v8::Function>(); } void GetFunctionLocation(v8::Local<v8::Function> function, String& script_id, int& line_number, int& column_number) { int script_id_value = function->ScriptId(); script_id = String::Number(script_id_value); line_number = function->GetScriptLineNumber(); column_number = function->GetScriptColumnNumber(); } std::unique_ptr<SourceLocation> GetFunctionLocation( ExecutionContext* execution_context, EventListener* listener) { v8::Isolate* isolate = ToIsolate(execution_context); v8::HandleScope handle_scope(isolate); v8::Local<v8::Object> handler = EventListenerHandler(execution_context, listener); if (handler.IsEmpty()) return nullptr; return SourceLocation::FromFunction( EventListenerEffectiveFunction(isolate, handler)); } } // namespace blink
[ "jacob-chen@iotwrt.com" ]
jacob-chen@iotwrt.com
b680dd808607a677da5139673dfd51b8e3c10ffb
32e910f5440c10b384bb26b5555ac7adb77540ee
/src/3rd_party/apache-log4cxx-0.10.0/src/main/include/log4cxx/helpers/socket.h
2f1636b72dc76919f8d6b16f23ce4ffcfcbfe0f1
[ "Apache-2.0" ]
permissive
smartdevicelink/sdl_core
76658282fd85b16ed6d91d8d4087d8cd1353db76
7343fc72c12edc8ac42a62556c9e4b29c9408bc3
refs/heads/master
2022-11-04T12:17:58.725371
2022-10-26T15:34:13
2022-10-26T15:34:13
24,724,170
269
306
BSD-3-Clause
2022-10-26T15:34:15
2014-10-02T15:16:26
C++
UTF-8
C++
false
false
3,477
h
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _LOG4CXX_HELPERS_SOCKET_H #define _LOG4CXX_HELPERS_SOCKET_H extern "C" { struct apr_socket_t; } #include <log4cxx/helpers/inetaddress.h> #include <log4cxx/helpers/pool.h> namespace log4cxx { namespace helpers { class ByteBuffer; /** <p>This class implements client sockets (also called just "sockets"). A socket is an endpoint for communication between two machines. <p>The actual work of the socket is performed by an instance of the SocketImpl class. An application, by changing the socket factory that creates the socket implementation, can configure itself to create sockets appropriate to the local firewall. */ class LOG4CXX_EXPORT Socket : public helpers::ObjectImpl { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(Socket) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(Socket) END_LOG4CXX_CAST_MAP() /** Creates a stream socket and connects it to the specified port number at the specified IP address. */ Socket(InetAddressPtr& address, int port); Socket(apr_socket_t* socket, apr_pool_t* pool); ~Socket(); size_t write(ByteBuffer&); /** Closes this socket. */ void close(); /** Returns the value of this socket's address field. */ InetAddressPtr getInetAddress() const; /** Returns the value of this socket's port field. */ int getPort() const; private: Socket(const Socket&); Socket& operator=(const Socket&); Pool pool; apr_socket_t* socket; /** The IP address of the remote end of this socket. */ InetAddressPtr address; /** The port number on the remote host to which this socket is connected. */ int port; }; LOG4CXX_PTR_DEF(Socket); } // namespace helpers } // namespace log4cxx #endif // _LOG4CXX_HELPERS_SOCKET_H
[ "jjdickow@gmail.com" ]
jjdickow@gmail.com
701025bac5c59cf2082c56629286cda43c115a8f
8924ecbe1c4c9c677794718622a6fd599fdc953a
/DevMng/SockProcLD.h
9a9fdc8e31c560ac2045b72126f5ac444dc18f4b
[]
no_license
pheonixsn/hcj
5ddf4d1ff363e0f1d331003d881c81fae4751ce2
440330d2483a14338ebb4f3033560e5552c84215
refs/heads/master
2021-01-14T12:30:49.213533
2016-09-16T06:31:42
2016-09-16T06:31:42
68,353,336
0
1
null
null
null
null
UTF-8
C++
false
false
317
h
#pragma once #include "stdafx.h" #include "sockproc.h" class CSockProcLD : public CSockProc { public: CSockProcLD(void); ~CSockProcLD(void); int ProcessMessage(SOCK_CMD_Frame * pFrameReq, SOCK_CMD_Frame * pFrameRsp); int VideoInfoCfgGet(SOCK_CMD_FrameDVideoInfoCfgGetRsp * cfg); int ResetData(void); };
[ "pheonixsn@gmail.com" ]
pheonixsn@gmail.com
732080fc1f5ac0eef5c86040b8a6c4a1b2285440
361e27f326afd55e2d5772dd3f3b9d6ba7623858
/service/notification/examples/tizen/NSSampleConsumerApp/inc/nsmain.h
91c99c0477f4486e5c1c7b0fb5a4022bbe3f75cd
[ "Apache-2.0", "GPL-2.0-only", "MIT", "BSD-3-Clause" ]
permissive
rzr/iotivity
2a2b2b23b855124e705d69c97a7b55be59ed533f
5d41e89f9f38d6d85fea47010729013c97410bb8
refs/heads/master
2022-05-30T19:35:55.767449
2021-08-13T15:32:19
2021-08-16T16:25:50
29,478,581
2
0
Apache-2.0
2021-08-16T16:25:51
2015-01-19T15:57:55
C++
UTF-8
C++
false
false
2,068
h
/****************************************************************** * * Copyright 2017 Samsung Electronics All Rights Reserved. * * * * 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. * ******************************************************************/ #ifndef NSMAIN_H__ #define NSMAIN_H__ #include <app.h> #include <Elementary.h> #include <system_settings.h> #include <efl_extension.h> #include <dlog.h> #include <EWebKit.h> #include "OCPlatform.h" #include "OCApi.h" #include <tizen.h> #include <app_control.h> using namespace OC; #ifdef LOG_TAG #undef LOG_TAG #endif #define LOG_TAG "nsclient" #if !defined(PACKAGE) #define PACKAGE "org.tizen.nssampleconsumer" #endif #define ELM_DEMO_EDJ "opt/usr/apps/org.tizen.nssampleconsumer/res/ui_controls.edj" typedef struct appdata { Evas_Object *win; Evas_Object *conform; Evas_Object *layout; Evas_Object *nf; Evas_Object *findButton; Evas_Object *logtext; Evas_Object *listview; Evas_Object *web_view; } appdata_s; static appdata_s ad = {0,}; static appdata_s *g_ad; static app_control_h app_handle = NULL; void clientCreateUI(void *data, Evas_Object *obj, void *event_info); void load_url(char *url); void __on_web_url_change(void *data, Evas_Object *obj, void *event_info); void __on_web_url_load_error(void *data, Evas_Object *obj, void *event_info); void __on_web_url_load_finished(void *data, Evas_Object *obj, void *event_info); void __on_web_url_load_started(void *data, Evas_Object *obj, void *event_info); void do_login(); #endif // NSMAIN_H__
[ "uzchoi@samsung.com" ]
uzchoi@samsung.com
3e41d25b00b1701ceba395a4dd8182c3851039ae
012f0800c635f23d069f0c400768bc58cc1a0574
/hhvm/hhvm-3.17/hphp/runtime/base/data-walker.cpp
20960d0a985324094256d884a53b7676268bac0a
[ "Zend-2.0", "BSD-3-Clause", "PHP-3.01" ]
permissive
chrispcx/es-hhvm
c127840387ee17789840ea788e308b711d3986a1
220fd9627b1b168271112d33747a233a91e8a268
refs/heads/master
2021-01-11T18:13:42.713724
2017-02-07T02:02:10
2017-02-07T02:02:10
79,519,670
5
0
null
null
null
null
UTF-8
C++
false
false
3,949
cpp
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2016 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/base/data-walker.h" #include "hphp/runtime/base/array-data.h" #include "hphp/runtime/base/object-data.h" #include "hphp/runtime/base/type-variant.h" #include "hphp/runtime/base/array-iterator.h" #include "hphp/runtime/base/collections.h" namespace HPHP { ////////////////////////////////////////////////////////////////////// void DataWalker::traverseData(ArrayData* data, DataFeature& features, PointerSet& visited) const { for (ArrayIter iter(data); iter; ++iter) { const Variant& var = iter.secondRef(); if (var.isReferenced()) { Variant *pvar = var.getRefData(); if (markVisited(pvar, features, visited)) { if (canStopWalk(features)) return; continue; // don't recurse forever; we already went down this path } // Right now consider it circular even if the referenced variant only // showed up in one spot. This could be revisted later. features.isCircular = true; if (canStopWalk(features)) return; } auto const type = var.getType(); // cheap enough, do it always features.hasRefCountReference = isRefcountedType(type); if (type == KindOfObject) { features.hasObjectOrResource = true; traverseData(var.getObjectData(), features, visited); } else if (isArrayLikeType(type)) { traverseData(var.getArrayData(), features, visited); } else if (type == KindOfResource) { features.hasObjectOrResource = true; } if (canStopWalk(features)) return; } } void DataWalker::traverseData( ObjectData* data, DataFeature& features, PointerSet& visited) const { objectFeature(data, features, visited); if (markVisited(data, features, visited)) { return; // avoid infinite recursion } if (!canStopWalk(features)) { traverseData(data->toArray().get(), features, visited); } } inline bool DataWalker::markVisited( void* pvar, DataFeature& features, PointerSet& visited) const { if (!visited.insert(pvar).second) { features.isCircular = true; return true; } return false; } inline void DataWalker::objectFeature( ObjectData* pobj, DataFeature& features, PointerSet& visited) const { if (pobj->isCollection()) return; if ((m_features & LookupFeature::DetectSerializable) && pobj->instanceof(SystemLib::s_SerializableClass)) { features.hasSerializable = true; } } inline bool DataWalker::canStopWalk(DataFeature& features) const { auto refCountCheck = features.hasRefCountReference || !(m_features & LookupFeature::RefCountedReference); auto objectCheck = features.hasObjectOrResource || !(m_features & LookupFeature::HasObjectOrResource); auto defaultChecks = features.isCircular || features.hasSerializable; return refCountCheck && objectCheck && defaultChecks; } ////////////////////////////////////////////////////////////////////// }
[ "peiqiang@huawei.com" ]
peiqiang@huawei.com
dc2ce9413285fc2babb0a6c7f252e1c7be4d59ab
8aa47dd44e58164a90597bebcd99e9ded6430e5e
/Phase 2 misc Files/Variables/Real.h
96130e73a6c592367aac55bfea5c45856bbc2971
[]
no_license
froyvalencia/Machine_Instruction_Simulator_VM
338d5c227f2c0608dca3d067127c329119297f6b
dfc9652d6ea049f8b2eedae12a54f85278f8c750
refs/heads/master
2021-05-01T18:46:11.387135
2016-12-12T23:22:54
2016-12-12T23:22:54
71,618,268
0
0
null
null
null
null
UTF-8
C++
false
false
1,313
h
/* @author Froylan Valencia, Brian Nguyen Real Header class Expected instrucion line input: VAR<name>,<type>,<optional:sizeincaseofstringonly>,<defaultvalue> VAR$myfloat,REAL,12.1 Real class inherits from Number which will recieve a double as the value parameter after having recognized the type in a VAR */ #pragma once #ifndef REAL_H #define REAL_H #include <iostream> #include "VAR.h" class Real : public VAR { protected: double value; public: Real(); Real(std::string n, double v); virtual ~Real(); // A method that initializes the object from a stringstream virtual void initialize (vector<string> line); VAR * clone (vector<string> line); void setValue(double v); double getValue() const; //overload operators // +, -, *, /, =, Real operator*(const Real& other); //int operator*(const Real& other,const Real& other2); Real operator/(const Real& other); Real operator-(const Real& other); Real operator+(const Real& other); Real& operator=(const Real& other); Real& operator=(const int& n); Real& operator=(const Real& other); Real& operator+=(const int& i); Real& operator+=(const double& d); Real& operator*=(const int& i); Real& operator*=(const double& d); friend std::ostream& operator<<(std::ostream& os, const Real& var); }; #endif
[ "froyvalencia@gmail.com" ]
froyvalencia@gmail.com
666444029f7880af087e1ca56c19b3488671c16a
199a69cf48121ab0643c9cafd4acd4cf879fe569
/cnt_txt_lib/cnt_txt.cpp
2fcaa64c9154e719379597d04e1af92c2de06eab
[]
no_license
Marwin34/battle_arena
8bff12ce52d1f0a99561ef45baca2f67fcb0c338
8fb6149a80c6df0b7f52b01b779319b7a99e6410
refs/heads/master
2022-04-07T23:16:32.787591
2020-02-05T15:43:56
2020-02-05T15:43:56
238,187,041
6
0
null
null
null
null
UTF-8
C++
false
false
1,517
cpp
#include "cnt_txt.hpp" Counter::Counter(int red, int green, int blue, int charSize) { font.loadFromFile("resources/font/arial.ttf"); text.setString("0"); text.setFont(font); text.setCharacterSize(charSize); color.r = red; color.g = green; color.b = blue; text.setFillColor(color); } void Counter::setCharSize(int charSize) { text.setCharacterSize(charSize); } void Counter::setFillColor(int red, int green, int blue) { color.r = red; color.g = green; color.b = blue; text.setFillColor(color); } void Counter::setPosition(int x, int y) { text.setPosition(x, y); } void Counter::setValue(int value) { std::string numberString = std::to_string(value); text.setString(numberString); } void Counter::draw(sf::RenderWindow* win) { win->draw(text); } Text::Text(int red, int green, int blue, int charSize) { font.loadFromFile("resources/font/signika.ttf"); text.setString("NONE"); text.setFont(font); text.setCharacterSize(charSize); color.r = red; color.g = green; color.b = blue; text.setFillColor(color); } void Text::setCharSize(int charSize) { text.setCharacterSize(charSize); } void Text::setFillColor(int red, int green, int blue) { color.r = red; color.g = green; color.b = blue; text.setFillColor(color); } void Text::setPositionAndValue(int x, int y, std::string textString) { text.setPosition(x, y); text.setString(textString); } void Text::draw(sf::RenderWindow* win) { win->draw(text); }
[ "marcinwojsik@wp.pl" ]
marcinwojsik@wp.pl
3d35e685f9b5ba819f173943228d8fddbad1af46
400d42521f805addafe6d240ed90b753bbaa9dc6
/main.cpp
de0503875f0cb21cf57cc677609c7a20b1166cf9
[]
no_license
codenome-trainings/locacao_de_carros_cpp
5b03d74d402435efb75b990d36da788bc3c5a072
ed4bd6f7d0ab8c0b6c1ff39c250b2fa0e7dfa1f5
refs/heads/master
2021-06-14T12:15:28.984063
2017-02-12T17:47:18
2017-02-12T17:47:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,500
cpp
#include <iostream> #include <stdio_ext.h> using namespace std; #define MAX_CLIENTES 100 #define MAX_CARROS 100 #define MAX_ALUGUEL 100 typedef struct Data { int dia; int mes; int ano; } Data; typedef struct Cliente { int id; string nome; Data dataDeNascimento; string cpf; } Cliente; int qtd_id_cliente = 20151328; typedef struct Carro { int id; string nome; string modelo; Data ano; double valor; bool status = false; //Esta Alugado? } Carro; int qtd_id_carro = 20151428; typedef struct Aluguel { int id; Cliente cliente; Carro carro; } Aluguel; int qtd_id_aluguel = 20151528; Cliente clientes[MAX_CLIENTES]; int qtd_clientes = 0; Carro carros[MAX_CARROS]; int qtd_carros = 0; Aluguel alugueis[MAX_ALUGUEL]; int qtd_alugueis = 0; Cliente *ponteiro_cliente; Carro *ponteiro_carro; void menu(); void menuCliente(); void menuAluguel(); void cadastrarCliente(); void buscarCliente(); void listarClientes(); void contaIdCliente(); void contaQtdDeClientes(); void localizaCliente(int i); void buscaPorIdCliente(); void buscaPorCpfDoCliente(); void desejaPesquisarClienteNovamente(); void menuCarro(); bool verificaSeCarroEstaDisponivel(bool status); void cadastrarCarro(); void contaIdDosCarros(); void contaQtdDosCarros(); void listaCarros(); void buscarCarro(); void localizaCarro(int i); void alugaCarro(); void armazenaClienteNoPonteiro(int i); void buscaClienteParaLocarUmCarro(); void buscaCarroParaSerAlugado(); void armazenaPonteiroDoCarro(int i); void contaIdAluguel(); void contaQtdDeAlgueis(); void relatorioDeClientesComCarrosAlugados(); void listarCarrosAlugados(); int main() { menu(); return 0; } void menu() { cout << "---------------------------------" << endl; cout << "----------MENU PRINCIPAL---------" << endl; cout << "---------------------------------" << endl; char escolha = ' '; cout << "1. Cliente" << endl; cout << "2. Carro" << endl; cout << "3. Aluguel" << endl; cout << "0. Sair" << endl; cout << "Digite uma opção: "; cin >> escolha; switch (escolha) { case '0': exit(0); case '1': menuCliente(); break; case '2': menuCarro(); break; case '3': menuAluguel(); break; default: cout << "Opção inválida! Tente novamente..." << endl; } menu(); } void menuCliente() { char escolha = ' '; cout << "---------------------------------" << endl; cout << "---------MENU DE CLIENTES--------" << endl; cout << "---------------------------------" << endl; cout << "1. Cadastrar cliente" << endl; cout << "2. Buscar cliente" << endl; cout << "3. Listar Cliente" << endl; cout << "0. Voltar" << endl; cout << "Digite uma opção: "; cin >> escolha; switch (escolha) { case '0': menu(); break; case '1': cadastrarCliente(); break; case '2': buscarCliente(); break; case '3': listarClientes(); break; default: cout << "Opção inválida! Tente novamente ..." << endl; } menuCliente(); } void listarClientes() { cout << "----------------------------------" << endl; cout << "---------LISTA DE CLIENTES--------" << endl; cout << "----------------------------------" << endl; for (int i = 0; i < qtd_clientes; i++) { cout << "ID:" << clientes[i].id << endl; cout << "NOME: " << clientes[i].nome << endl; cout << "DATA DE NASCIMENTO: " << clientes[i].dataDeNascimento.dia << "/" << clientes[i].dataDeNascimento.mes << "/" << clientes[i].dataDeNascimento.ano << endl; cout << "CPF: " << clientes[i].cpf<< endl; cout << endl; cout << "---" << endl; cout << endl; } cout << "Clientes listados com sucesso!" << endl; cout << "Pressione qualquer tecla para continuar..."; __fpurge(stdin); getchar(); menuCliente(); } void buscarCliente() { char escolha = ' '; cout << "Método de busca de um cliente: [1] ID | [0]CPF - _ "; cin >> escolha; if (escolha == '1') { buscaPorIdCliente(); } else if (escolha == '0'){ buscaPorCpfDoCliente(); } else { cout << "Opção inválida! Tente novamente ..." << endl; buscarCliente(); } } void buscaPorCpfDoCliente() { bool encontrou = false; string cpf_cliente; __fpurge(stdin); cout << "CPF do cliente: "; getline(cin, cpf_cliente); for (int i = 0; i < qtd_clientes; ++i) { if(clientes[i].cpf == cpf_cliente) { cout << endl; cout << endl; cout << "Cliente encontrado com sucesso!" << endl; localizaCliente(i); encontrou = true; break; } } if (encontrou == false) { cout << "Cliente não encontrado!" << endl; desejaPesquisarClienteNovamente(); } } void buscaPorIdCliente() { bool encontrou = false; int id_cliente = 0; cout << "ID do cliente: "; cin >> id_cliente; for (int i = 0; i < qtd_clientes; ++i) { if(id_cliente == clientes[i].id) { cout << endl; cout << endl; cout << "Cliente encontrado com sucesso!" << endl; localizaCliente(i); encontrou = true; break; } } if (encontrou == false) { cout << "Cliente não encontrado!" << endl; desejaPesquisarClienteNovamente(); } } void desejaPesquisarClienteNovamente() { cout << "Deseja pesquisar novamente?" << endl; cout << "[1] SIM" << endl; cout << "[2] NÃO (Volta ao menu de clientes)" << endl; cout << "[3] Desejo cadastrar um novo cliente" << endl; char escolha = ' '; __fpurge(stdin); cout << "Digite uma das opções: "; cin >> escolha; if (escolha == '1') { buscarCliente(); } else if (escolha == '2') { menuCliente(); } else if(escolha == '3') { cadastrarCliente(); } else { cout << "Opção inválida! Tente novamente ..." << endl; } desejaPesquisarClienteNovamente(); } void localizaCliente(int i) { cout << endl; cout << endl; cout << "ID:" << clientes[i].id << endl; cout << "NOME: " << clientes[i].nome << endl; cout << "DATA DE NASCIMENTO: " << clientes[i].dataDeNascimento.dia << "/" << clientes[i].dataDeNascimento.mes << "/" << clientes[i].dataDeNascimento.ano << endl; cout << "CPF: " << clientes[i].cpf<< endl; cout << endl; cout << "---" << endl; cout << endl; __fpurge(stdin); cout << "Consulta verificada. Pressione qualquer para continuar..."; getchar(); armazenaClienteNoPonteiro(i); } void armazenaClienteNoPonteiro(int i) { ponteiro_cliente = &clientes[i]; } void cadastrarCliente() { Cliente cliente; __fpurge(stdin); cout << "NOME: "; getline(cin, cliente.nome); __fpurge(stdin); cout << "Data de Nascimento" << endl; cout << "DIA: "; cin >> cliente.dataDeNascimento.dia; __fpurge(stdin); cout << "MÊS: "; cin >> cliente.dataDeNascimento.mes; __fpurge(stdin); cout << "ANO: "; cin >> cliente.dataDeNascimento.ano; __fpurge(stdin); cout << "CPF: "; getline(cin, cliente.cpf); cliente.id = qtd_id_cliente; contaIdCliente(); clientes[qtd_clientes] = cliente; contaQtdDeClientes(); __fpurge(stdin); cout << "Cliente cadastrado com sucesso!" << endl; cout << "Deseja cadastrar mais um cliente? [1] SIM | [0] NÃO - _ "; bool escolha; cin >> escolha; if (escolha == true) cadastrarCliente(); __fpurge(stdin); cout << "Pressione qualquer tecla para voltar ao menu de cliente."; getchar(); menuCliente(); } void contaQtdDeClientes() { qtd_clientes++; } void contaIdCliente() { qtd_id_cliente++; } void menuCarro() { char escolha = ' '; cout << "-------------------------------" << endl; cout << "---------MENU DE CARRO---------" << endl; cout << "-------------------------------" << endl; cout << "1. Cadastrar carro" << endl; cout << "2. Buscar carro" << endl; cout << "3. Listar carros" << endl; cout << "0. Voltar" << endl; cout << "Digite uma opção: "; cin >> escolha; switch (escolha) { case '0': menu(); break; case '1': cadastrarCarro(); break; case '2': buscarCarro(); break; case '3': listaCarros(); break; default: cout << "Opção inválida! Tente novamente..." << endl; } menuCarro(); } void buscarCarro() { bool encontrou = false; int id_carro = 0; cout << "ID do carro: "; cin >> id_carro; for (int i = 0; i < qtd_carros; ++i) { //Verifica se o carro existe! if(id_carro == carros[i].id) { if (verificaSeCarroEstaDisponivel(carros[i].status) != true) { break; } cout << endl; cout << endl; cout << "Carro encontrado com sucesso!" << endl; localizaCarro(i); encontrou = true; break; } } if (encontrou == false) { cout << "Carro não encontrado! Acho que você deve ter errado alguma coisa. Tente novamente ..." << endl; cout << "Deseja buscar novamente? [1] SIM | [2] NÃO - _ " << endl; char escolha = ' '; __fpurge(stdin); cout << "Digite uma opção: "; cin >> escolha; if(escolha == '1') { buscarCarro(); } else { menuCarro(); } } } bool verificaSeCarroEstaDisponivel(bool status) { if (status == true) { cout << "Este carro [NÃO] está disponível para locação." << endl; cout << "Deseja buscar outro carro? [1] SIM | [2] NÃO (Volta ao menu de carro) - "; char escolha = ' '; __fpurge(stdin); cout << "Digite uma opção: "; cin >> escolha; if (escolha == '1') { buscarCarro(); } else { menuCarro(); } } else { cout << "Carro disponivel para locação." << endl; } return true; } void localizaCarro(int i) { cout << "ID:" << carros[i].id << endl; cout << "NOME: " << carros[i].nome << endl; cout << "ANO: " << carros[i].ano.ano << endl; cout << "VALOR: R$ " << carros[i].valor << endl; if(carros[i].status == true) { cout << "STATUS: Alugado" << endl; } else { cout << "STATUS: Livre para locação" << endl; } cout << endl; cout << "---" << endl; cout << endl; __fpurge(stdin); cout << "Consulta verificada. Pressione qualquer para continuar..."; getchar(); armazenaPonteiroDoCarro(i); } void armazenaPonteiroDoCarro(int i) { ponteiro_carro = &carros[i]; } void listaCarros() { for (int i = 0; i < qtd_carros; i++) { cout << "ID:" << carros[i].id << endl; cout << "NOME: " << carros[i].nome << endl; cout << "ANO: " << carros[i].ano.ano << endl; cout << "VALOR: R$ " << carros[i].valor << endl; if(carros[i].status == true) { cout << "STATUS: Alugado" << endl; } else { cout << "STATUS: Livre para locação" << endl; } cout << endl; cout << "---" << endl; cout << endl; } cout << "Carros listados com sucesso!" << endl; cout << "Pressione qualquer tecla para continuar..."; __fpurge(stdin); getchar(); menuCarro(); } void cadastrarCarro() { Carro carro; __fpurge(stdin); cout << "NOME: "; getline(cin, carro.nome); __fpurge(stdin); cout << "MARCA: "; getline(cin, carro.modelo); cout << "ANO: "; cin >> carro.ano.ano; cout << "VALOR: "; cin >> carro.valor; carro.id = qtd_id_carro; contaIdDosCarros(); carros[qtd_carros] = carro; contaQtdDosCarros(); __fpurge(stdin); cout << "Carro cadastrado com sucesso!" << endl; cout << "Deseja cadastrar mais um Carro? [1] SIM | [0] NÃO - "; int escolha; cin >> escolha; if (escolha == 1) cadastrarCarro(); __fpurge(stdin); cout << "Pressione qualquer tecla para voltar ao menu de carro."; getchar(); menuCarro(); } void contaQtdDosCarros() { qtd_carros++; } void contaIdDosCarros() { qtd_id_carro++; } void menuAluguel() { char escolha = ' '; cout << "--------------------------------" << endl; cout << "---------MENU DE ALUGUEL--------" << endl; cout << "--------------------------------" << endl; cout << "1. Alugar um carro" << endl; cout << "2. Dar baixa em um carro" << endl; cout << "3. Ver todos os clientes com carros alugados" << endl; cout << "4. Listar todos os carros alugados" << endl; cout << "0. Voltar" << endl; cout << "Digite uma opção: "; __fpurge(stdin); cin >> escolha; switch (escolha) { case '0': menu(); break; case '1': alugaCarro(); break; case '2': // baixaEmCarro(); break; case '3': relatorioDeClientesComCarrosAlugados(); break; case '4': listarCarrosAlugados(); break; default: cout << "Opção inválida! Tente novamente ..." << endl; } menuAluguel(); } void listarCarrosAlugados() { for (int i = 0; i < qtd_carros; ++i) { if(carros[i].status == true) { cout << "ID:" << carros[i].id << endl; cout << "NOME: " << carros[i].nome << endl; cout << "ANO: " << carros[i].ano.ano << endl; cout << "VALOR: R$ " << carros[i].valor << endl; cout << "STATUS: Alugado" << endl; cout << endl; cout << "---" << endl; cout << endl; } } cout << "Carros alugados listados com sucesso!" << endl; cout << "Pressione qualquer tecla para continuar..."; __fpurge(stdin); getchar(); menuAluguel(); } void relatorioDeClientesComCarrosAlugados() { for (int i = 0; i < qtd_alugueis; ++i) { cout << "ID DO CLIENTE: " << alugueis[i].cliente.id << endl; cout << "CLIENTE: " << alugueis[i].cliente.nome << endl; cout << "ID DO CARRO: " << alugueis[i].carro.id << endl; cout << "CARRO ALUGADO: " << alugueis[i].carro.nome << endl; cout << "VALOR: " << alugueis[i].carro.valor << endl; cout << endl << "---" << endl; } cout << "Clientes que alugaram carros listados com sucesso!" << endl; cout << "Pressione qualquer tecla para continuar..."; __fpurge(stdin); getchar(); menuAluguel(); } void alugaCarro() { Aluguel aluguel; /* * Função que busca cliente e carro para serem armazenadas em um ponteiro que * armazena temporariamente os valores de carro e cliente. */ buscaClienteParaLocarUmCarro(); buscaCarroParaSerAlugado(); aluguel.id = qtd_id_aluguel; contaIdAluguel(); //Trata Cliente aluguel.cliente.id = ponteiro_cliente->id; aluguel.cliente.nome = ponteiro_cliente->nome; aluguel.cliente.cpf = ponteiro_cliente->cpf; aluguel.cliente.dataDeNascimento.dia = ponteiro_cliente->dataDeNascimento.dia; aluguel.cliente.dataDeNascimento.mes = ponteiro_cliente->dataDeNascimento.mes; aluguel.cliente.dataDeNascimento.ano = ponteiro_cliente->dataDeNascimento.ano; //Trata Alguel aluguel.carro.id = ponteiro_carro->id; aluguel.carro.nome = ponteiro_carro->nome; aluguel.carro.ano = ponteiro_carro->ano; aluguel.carro.modelo = ponteiro_carro->modelo; aluguel.carro.valor = ponteiro_carro->valor; ponteiro_carro->status = true; alugueis[qtd_alugueis] = aluguel; contaQtdDeAlgueis(); __fpurge(stdin); cout << "Aluguel cadastrado com sucesso!" << endl; cout << "Deseja cadastrar mais um Alguel? [1] SIM | [0] NÃO - _ "; bool escolha; cin >> escolha; if (escolha == true) alugaCarro(); __fpurge(stdin); cout << "Pressione qualquer tecla para voltar ao menu de aluguel."; getchar(); menuAluguel(); } void contaQtdDeAlgueis() { qtd_alugueis++; } void contaIdAluguel() { qtd_id_aluguel++; } void buscaCarroParaSerAlugado() { char done = ' '; do { bool escolha = true; buscarCarro(); __fpurge(stdin); cout << "Deseja usar este carro para ser alugado? [1] SIM | [0] NÃO (Buscar outro carro): "; cin >> escolha; if (escolha == true) { done = 'a'; } else { alugaCarro(); } } while (done == ' '); } void buscaClienteParaLocarUmCarro() { char done = ' '; do { bool escolha = true; buscarCliente(); __fpurge(stdin); cout << "Deseja usar este cliente para locar um carro? [1] SIM | [0] NÃO (Buscar outro cliente): "; cin >> escolha; if (escolha == true) { done = 'a'; } else { alugaCarro(); } } while (done == ' '); }
[ "thiagocunha.java@gmail.com" ]
thiagocunha.java@gmail.com
06601cf611a274aadfd132f6171fd815ff9d7767
6369571344b2d1c1f91a7d6561f715c633bc173a
/fileIO/read.cpp
a48393b053db6528c0c01b4495298f2093d23757
[]
no_license
pjaluka13/C-Programs
d7ce4a6acb8fffa9716d8169477378c2403b46b2
3e8e6b2cc77478804db731f283d34619120c6d52
refs/heads/master
2020-08-23T03:28:05.588135
2019-10-21T09:57:05
2019-10-21T09:57:05
216,534,073
0
0
null
2019-10-21T09:51:34
2019-10-21T09:51:34
null
UTF-8
C++
false
false
400
cpp
#include <iostream> #include <fstream> #include <cstdlib> using namespace std; int main(){ char filename[50]; ifstream ip; cin.getline(filename, 50); ip.open(filename); if(!ip.is_open()){ std::cout << "File Name does not Exists" << '\n'; exit(EXIT_FAILURE); } char word[50]; ip >> word; while(ip.good()){ std::cout << word<< ' '; ip>>word; } return 0; }
[ "tpatil2@mail.csuchico.edu" ]
tpatil2@mail.csuchico.edu
52139866928f6a79636d861e98818f6cab29d05a
ee8b61d66df872872ef4c0bb9d05f710e6740941
/include/Avl.h
069f209bf447e01e8104acb0a6a87758136d7928
[]
no_license
ahmetmgurer/AVL_tree_with_stack_structure
3735c07078e9d79cbd96f285aeca9ff4d9f265d4
9722a8a04aa6fd732890eed99d04e47cd14028bf
refs/heads/master
2022-12-31T21:08:51.561916
2020-09-24T13:44:07
2020-09-24T13:44:07
298,291,665
0
0
null
null
null
null
UTF-8
C++
false
false
499
h
#include "Kisi.h" using namespace std; class Avl { public: Kisi *root; Kisi *yeni; Avl(); void Travel(Kisi *&); Kisi* InsertNew(Kisi *&, const string&,int, const string&); void updateStack(Kisi *&); void resetStackFeatures(Kisi *&); void PostOrder(Kisi *); void StackOperations(Kisi *&); int max(int , int ); ~Avl(); private: int Height(Kisi *&); Kisi *singleLeftRotate(Kisi*&y); Kisi *singleRightRotate(Kisi*&y); Kisi *doubleLeftRotate(Kisi*&y); Kisi *doubleRightRotate(Kisi*&y); };
[ "ahmetmgurer@outlook.com" ]
ahmetmgurer@outlook.com
11166338120094078e59c97d32dd9638b816ff81
fad23560ef8e8edc1f7f8f54810a0434c449bd84
/include/cnn4/test_cnn4.hpp
4a883206c514dedd47baf8d0065c4e82c5e89c3a
[]
no_license
hyglvy/cstd
7a181d802140534cf1d3a8f3587e0fcbd6ccc233
fd30c093fd1855b18dd562e4f7f0e8cd3c6d9bd1
refs/heads/master
2020-04-12T10:06:39.923670
2018-12-18T09:58:30
2018-12-18T09:58:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
765
hpp
#pragma warning(disable: 4267) #pragma warning(disable: 4244) #include "wstd/utime.hpp" #include "wstd/string.hpp" #include <direct.h> //#include "cnn4.hpp" //#include "test/test_all.hpp" struct Net; Net* net_new(); void net_del(Net* net); int net_loadjson(Net* net, const char* fn); int net_train(Net* net); int test_cnn4() { const char* fn = NULL; //test_caffe2json(); char buf[256]; itoa_c(1234, buf, 10); if (1) { fn = "E:/caffe_train/mnist/lenet.json"; _chdir("E:/caffe_train/mnist/"); } if (0) { fn = "E:/OCR_Line/model/densenet-no-blstm/densenet-no-blstm.json"; _chdir("E:/OCR_Line/model/densenet-no-blstm/"); } Net* net = net_new(); if (net_loadjson(net, fn)) { net_train(net); } net_del(net); return 0; }
[ "31720406@qq.com" ]
31720406@qq.com
c76a9e57b4f7e2c857fcd3eee03f3ccc0ac44125
7c253960e417cdd74c5f063bc7fe4bd8c4b4686c
/tests/src/cbor/cbor_tests.cpp
994a5cfe9b890944a6a6b2303bb6a7150f2033d6
[ "BSL-1.0", "MIT" ]
permissive
jhandley/jsoncons
25f0b5d0f3be56a62098a81ad72455ee8b793324
7bdb8b9382e0acb6ad023372b3f1bd421194cf13
refs/heads/master
2022-08-31T00:25:47.071090
2020-05-15T20:53:26
2020-05-15T20:53:26
264,296,042
0
0
NOASSERTION
2020-05-15T20:50:12
2020-05-15T20:50:12
null
UTF-8
C++
false
false
6,467
cpp
// Copyright 2016 Daniel Parker // Distributed under Boost license #if defined(_MSC_VER) #include "windows.h" #endif #include <jsoncons/json.hpp> #include <jsoncons_ext/cbor/cbor.hpp> #include <sstream> #include <vector> #include <utility> #include <ctime> #include <limits> #include <catch/catch.hpp> using namespace jsoncons; TEST_CASE("cbor_test_floating_point") { json j1; j1["max double"] = (std::numeric_limits<double>::max)(); j1["max float"] = (std::numeric_limits<float>::max)(); std::vector<uint8_t> v; cbor::encode_cbor(j1, v); json j2 = cbor::decode_cbor<json>(v); CHECK(j1 == j2); } TEST_CASE("cbor_test") { json j1; j1["zero"] = 0; j1["one"] = 1; j1["two"] = 2; j1["null"] = null_type(); j1["true"] = true; j1["false"] = false; j1["max int64_t"] = (std::numeric_limits<int64_t>::max)(); j1["max uint64_t"] = (std::numeric_limits<uint64_t>::max)(); j1["min int64_t"] = (std::numeric_limits<int64_t>::lowest)(); j1["max int32_t"] = (std::numeric_limits<int32_t>::max)(); j1["max uint32_t"] = (std::numeric_limits<uint32_t>::max)(); j1["min int32_t"] = (std::numeric_limits<int32_t>::lowest)(); j1["max int16_t"] = (std::numeric_limits<int16_t>::max)(); j1["max uint16_t"] = (std::numeric_limits<uint16_t>::max)(); j1["min int16_t"] = (std::numeric_limits<int16_t>::lowest)(); j1["max int8_t"] = (std::numeric_limits<int8_t>::max)(); j1["max uint8_t"] = (std::numeric_limits<uint8_t>::max)(); j1["min int8_t"] = (std::numeric_limits<int8_t>::lowest)(); j1["max double"] = (std::numeric_limits<double>::max)(); j1["min double"] = (std::numeric_limits<double>::lowest)(); j1["max float"] = (std::numeric_limits<float>::max)(); j1["zero float"] = 0.0; j1["min float"] = (std::numeric_limits<float>::lowest)(); j1["String too long for small string optimization"] = "String too long for small string optimization"; json ja(json_array_arg); ja.push_back(0); ja.push_back(1); ja.push_back(2); ja.push_back(null_type()); ja.push_back(true); ja.push_back(false); ja.push_back((std::numeric_limits<int64_t>::max)()); ja.push_back((std::numeric_limits<uint64_t>::max)()); ja.push_back((std::numeric_limits<int64_t>::lowest)()); ja.push_back((std::numeric_limits<int32_t>::max)()); ja.push_back((std::numeric_limits<uint32_t>::max)()); ja.push_back((std::numeric_limits<int32_t>::lowest)()); ja.push_back((std::numeric_limits<int16_t>::max)()); ja.push_back((std::numeric_limits<uint16_t>::max)()); ja.push_back((std::numeric_limits<int16_t>::lowest)()); ja.push_back((std::numeric_limits<int8_t>::max)()); ja.push_back((std::numeric_limits<uint8_t>::max)()); ja.push_back((std::numeric_limits<int8_t>::lowest)()); ja.push_back((std::numeric_limits<double>::max)()); ja.push_back((std::numeric_limits<double>::lowest)()); ja.push_back((std::numeric_limits<float>::max)()); ja.push_back(0.0); ja.push_back((std::numeric_limits<float>::lowest)()); ja.push_back("String too long for small string optimization"); j1["An array"] = ja; std::vector<uint8_t> v; cbor::encode_cbor(j1, v); json j2 = cbor::decode_cbor<json>(v); CHECK(j1 == j2); } TEST_CASE("cbor_test2") { wjson j1; j1[L"zero"] = 0; j1[L"one"] = 1; j1[L"two"] = 2; j1[L"null"] = null_type(); j1[L"true"] = true; j1[L"false"] = false; j1[L"max int64_t"] = (std::numeric_limits<int64_t>::max)(); j1[L"max uint64_t"] = (std::numeric_limits<uint64_t>::max)(); j1[L"min int64_t"] = (std::numeric_limits<int64_t>::lowest)(); j1[L"max int32_t"] = (std::numeric_limits<int32_t>::max)(); j1[L"max uint32_t"] = (std::numeric_limits<uint32_t>::max)(); j1[L"min int32_t"] = (std::numeric_limits<int32_t>::lowest)(); j1[L"max int16_t"] = (std::numeric_limits<int16_t>::max)(); j1[L"max uint16_t"] = (std::numeric_limits<uint16_t>::max)(); j1[L"min int16_t"] = (std::numeric_limits<int16_t>::lowest)(); j1[L"max int8_t"] = (std::numeric_limits<int8_t>::max)(); j1[L"max uint8_t"] = (std::numeric_limits<uint8_t>::max)(); j1[L"min int8_t"] = (std::numeric_limits<int8_t>::lowest)(); j1[L"max double"] = (std::numeric_limits<double>::max)(); j1[L"min double"] = (std::numeric_limits<double>::lowest)(); j1[L"max float"] = (std::numeric_limits<float>::max)(); j1[L"zero float"] = 0.0; j1[L"min float"] = (std::numeric_limits<float>::lowest)(); j1[L"S"] = L"S"; j1[L"String too long for small string optimization"] = L"String too long for small string optimization"; wjson ja(json_array_arg); ja.push_back(0); ja.push_back(1); ja.push_back(2); ja.push_back(null_type()); ja.push_back(true); ja.push_back(false); ja.push_back((std::numeric_limits<int64_t>::max)()); ja.push_back((std::numeric_limits<uint64_t>::max)()); ja.push_back((std::numeric_limits<int64_t>::lowest)()); ja.push_back((std::numeric_limits<int32_t>::max)()); ja.push_back((std::numeric_limits<uint32_t>::max)()); ja.push_back((std::numeric_limits<int32_t>::lowest)()); ja.push_back((std::numeric_limits<int16_t>::max)()); ja.push_back((std::numeric_limits<uint16_t>::max)()); ja.push_back((std::numeric_limits<int16_t>::lowest)()); ja.push_back((std::numeric_limits<int8_t>::max)()); ja.push_back((std::numeric_limits<uint8_t>::max)()); ja.push_back((std::numeric_limits<int8_t>::lowest)()); ja.push_back((std::numeric_limits<double>::max)()); ja.push_back((std::numeric_limits<double>::lowest)()); ja.push_back((std::numeric_limits<float>::max)()); ja.push_back(0.0); ja.push_back((std::numeric_limits<float>::lowest)()); ja.push_back(L"S"); ja.push_back(L"String too long for small string optimization"); j1[L"An array"] = ja; std::vector<uint8_t> v; cbor::encode_cbor(j1, v); wjson j2 = cbor::decode_cbor<wjson>(v); CHECK(j1 == j2); } TEST_CASE("cbor_reputon_test") { ojson j1 = ojson::parse(R"( { "application": "hiking", "reputons": [ { "rater": "HikingAsylum", "assertion": "advanced", "rated": "Marilyn C", "rating": 0.90 } ] } )"); std::vector<uint8_t> v; cbor::encode_cbor(j1, v); ojson j2 = cbor::decode_cbor<ojson>(v); CHECK(j1 == j2); //std::cout << pretty_print(j2) << std::endl; }
[ "danielaparker@yahoo.com" ]
danielaparker@yahoo.com
ffed165cc8a956411226da567ff2924fc5ae4d10
e105784455826d3af3670b74b64bf2f0e4fc2f0e
/131.cpp
8057d71797b5bf36cd151592aeae25c946a96c16
[]
no_license
summylight/leetcode
076b4a1ef60c657180d2bcf9f77b05bfd5a709ad
7a6049eee5ad5e30061e05d400af536ad3418202
refs/heads/master
2020-08-25T02:22:18.817586
2019-10-23T02:13:10
2019-10-23T02:13:10
216,948,040
0
0
null
null
null
null
UTF-8
C++
false
false
136
cpp
#include<iostream> #include <vector> #include <string> using namespace std; vector<vector<string>> partition(string s) { }
[ "summylight@163.com" ]
summylight@163.com
f95813ae26b5476a402f5ab3aee3dea8d49e7f65
56fcab9393f0ec379e2abb00d2d8eda36f64e823
/uintah/kokkos_src/CCA/Components/MPM/ConstitutiveModel/Biswajit/Models/InternalVariableModel.cc
8a328b45a38b36b55c51f3aa6a59400ec7b634c4
[ "CC-BY-4.0", "MIT" ]
permissive
damu1000/hypre_ep
4a13a5545ac90b231ca9e0f29f23f041f344afb9
a6701de3d455fa4ee95ac7d79608bffa3eb115ee
refs/heads/master
2023-04-11T11:38:21.157249
2021-08-16T21:50:44
2021-08-16T21:50:44
41,874,948
2
1
null
null
null
null
UTF-8
C++
false
false
1,323
cc
/* * The MIT License * * Copyright (c) 1997-2017 The University of Utah * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "InternalVariableModel.h" using namespace UintahBB; InternalVariableModel::InternalVariableModel() { } InternalVariableModel::~InternalVariableModel() { }
[ "damodars@sci.utah.edu" ]
damodars@sci.utah.edu
961fb01fdbf35f8be0bf854f2c1430778196c0a0
b9735d8af7a081b7e39fb2ff09377dcce19f49b5
/HElib/src/Test/Test_ThinBootstrapping.cpp
db5807218ba320ab717fb5dcb389e8bcbc306170
[ "Apache-2.0" ]
permissive
MarbleHE/Marble
acdd49b06e3df5157767c709ffe0583f61fce193
691f0519cb2ea60808f93b1cdb09409ce24cdedb
refs/heads/master
2021-06-20T04:22:08.063794
2020-12-23T12:26:47
2020-12-23T12:26:47
144,953,290
13
0
null
null
null
null
UTF-8
C++
false
false
11,406
cpp
#include "../FHE.h" #include "../EncryptedArray.h" #include "../matmul.h" #include <NTL/BasicThreadPool.h> static bool noPrint = true; static long mValues[][14] = { //{ p, phi(m), m, d, m1, m2, m3, g1, g2, g3,ord1,ord2,ord3, c_m} { 2, 48, 105, 12, 3, 35, 0, 71, 76, 0, 2, 2, 0, 100}, { 2, 600, 1023, 10, 11, 93, 0, 838, 584, 0, 10, 6, 0, 100}, // m=(3)*11*{31} m/phim(m)=1.7 C=24 D=2 E=1 { 2, 1200, 1705, 20, 11, 155, 0, 156, 936, 0, 10, 6, 0, 100}, // m=(5)*11*{31} m/phim(m)=1.42 C=34 D=2 E=2 { 2, 1728, 4095, 12, 7, 5, 117, 2341, 3277, 3641, 6, 4, 6, 100}, // m=(3^2)*5*7*{13} m/phim(m)=2.36 C=26 D=3 E=2 { 2, 2304, 4641, 24, 7, 3, 221, 3979, 3095, 3760, 6, 2, -8, 100}, // m=3*7*(13)*{17} :-( m/phim(m)=2.01 C=45 D=4 E=3 { 2, 4096, 4369, 16, 17, 257, 0, 258, 4115, 0, 16,-16, 0, 100}, // m=17*(257) :-( m/phim(m)=1.06 C=61 D=3 E=4 { 2, 12800, 17425, 40, 41, 425, 0, 5951, 8078, 0, 40, -8, 0, 100}, // m=(5^2)*{17}*41 m/phim(m)=1.36 C=93 D=3 E=3 { 2, 15004, 15709, 22, 23, 683, 0, 4099, 13663, 0, 22, 31, 0, 100}, // m=23*(683) m/phim(m)=1.04 C=73 D=2 E=1 { 2, 16384, 21845, 16, 17, 5,257, 8996, 17477, 21591, 16, 4, -16,1600}, // m=5*17*(257) :-( m/phim(m)=1.33 C=65 D=4 E=4 { 2, 18000, 18631, 25, 31, 601, 0, 15627, 1334, 0, 30, 24, 0, 50}, // m=31*(601) m/phim(m)=1.03 C=77 D=2 E=0 { 2, 18816, 24295, 28, 43, 565, 0, 16386, 16427, 0, 42, 16, 0, 100}, // m=(5)*43*{113} m/phim(m)=1.29 C=84 D=2 E=2 { 2, 21168, 27305, 28, 43, 635, 0, 10796, 26059, 0, 42, 18, 0, 100}, // m=(5)*43*{127} m/phim(m)=1.28 C=86 D=2 E=2 { 2, 23040, 28679, 24, 17, 7, 241, 15184, 4098,28204, 16, 6, -10,1000}, // m=7*17*(241) m/phim(m)=1.24 C=63 D=4 E=3 { 2, 24000, 31775, 20, 41, 775, 0, 6976, 24806, 0, 40, 30, 0, 100}, // m=(5^2)*{31}*41 m/phim(m)=1.32 C=88 D=2 E=2 { 2, 26400, 27311, 55, 31, 881, 0, 21145, 1830, 0, 30, 16, 0, 100}, // m=31*(881) m/phim(m)=1.03 C=99 D=2 E=0 { 2, 27000, 32767, 15, 31, 7, 151, 11628, 28087,25824, 30, 6, -10, 150}, { 2, 31104, 35113, 36, 37, 949, 0, 16134, 8548, 0, 36, 24, 0, 400}, // m=(13)*37*{73} m/phim(m)=1.12 C=94 D=2 E=2 { 2, 34848, 45655, 44, 23, 1985, 0, 33746, 27831, 0, 22, 36, 0, 100}, // m=(5)*23*{397} m/phim(m)=1.31 C=100 D=2 E=2 { 2, 42336, 42799, 21, 127, 337, 0, 25276, 40133, 0,126, 16, 0, 20}, // m=127*(337) m/phim(m)=1.01 C=161 D=2 E=0 { 2, 45360, 46063, 45, 73, 631, 0, 35337, 20222, 0, 72, 14, 0, 100}, // m=73*(631) m/phim(m)=1.01 C=129 D=2 E=0 { 2, 46080, 53261, 24, 17, 13, 241, 43863, 28680,15913, 16, 12, -10, 100}, // m=13*17*(241) m/phim(m)=1.15 C=69 D=4 E=3 { 2, 49500, 49981, 30, 151, 331, 0, 6952, 28540, 0,150, 11, 0, 100}, // m=151*(331) m/phim(m)=1 C=189 D=2 E=1 { 2, 54000, 55831, 25, 31, 1801, 0, 19812, 50593, 0, 30, 72, 0, 100}, // m=31*(1801) m/phim(m)=1.03 C=125 D=2 E=0 { 2, 60016, 60787, 22, 89, 683, 0, 2050, 58741, 0, 88, 31, 0, 200}, // m=89*(683) m/phim(m)=1.01 C=139 D=2 E=1 { 7, 36, 57, 3, 3, 19, 0, 20, 40, 0, 2, -6, 0, 100}, // m=3*(19) :-( m/phim(m)=1.58 C=14 D=3 E=0 { 17, 48, 105, 12, 3, 35, 0, 71, 76, 0, 2, 2, 0, 100}, // m=3*(5)*{7} m/phim(m)=2.18 C=14 D=2 E=2 { 17, 576, 1365, 12, 7, 3, 65, 976, 911, 463, 6, 2, 4, 100}, // m=3*(5)*7*{13} m/phim(m)=2.36 C=22 D=3 { 17, 18000, 21917, 30, 101, 217, 0, 5860, 5455, 0, 100, 6, 0, 100}, // m=(7)*{31}*101 m/phim(m)=1.21 C=134 D=2 { 17, 30000, 34441, 30, 101, 341, 0, 2729, 31715, 0, 100, 10, 0, 100}, // m=(11)*{31}*101 m/phim(m)=1.14 C=138 D=2 { 17, 40000, 45551, 40, 101, 451, 0, 19394, 7677, 0, 100, 10, 0,2000}, // m=(11)*{41}*101 m/phim(m)=1.13 C=148 D=2 { 17, 46656, 52429, 36, 109, 481, 0, 46658, 5778, 0, 108, 12, 0, 100}, // m=(13)*{37}*109 m/phim(m)=1.12 C=154 D=2 { 17, 54208, 59363, 44, 23, 2581, 0, 25811, 5199, 0, 22, 56, 0, 100}, // m=23*(29)*{89} m/phim(m)=1.09 C=120 D=2 { 17, 70000, 78881, 10, 101, 781, 0, 67167, 58581, 0, 100, 70, 0, 100}, // m=(11)*{71}*101 m/phim(m)=1.12 C=178 D=2 {127, 576, 1365, 12, 7, 3, 65, 976, 911, 463, 6, 2, 4, 100}, // m=3*(5)*7*{13} m/phim(m)=2.36 C=22 D=3 {127, 1200, 1925, 20, 11, 175, 0, 1751, 199, 0, 10, 6, 0, 100}, // m=(5^2)*{7}*11 m/phim(m)=1.6 C=34 D=2 {127, 2160, 2821, 30, 13, 217, 0, 652, 222, 0, 12, 6, 0, 100}, // m=(7)*13*{31} m/phim(m)=1.3 C=46 D=2 {127, 18816, 24295, 28, 43, 565, 0, 16386, 16427, 0, 42, 16, 0, 100}, // m=(5)*43*{113} m/phim(m)=1.29 C=84 D=2 {127, 26112, 30277, 24, 17, 1781, 0, 14249, 10694, 0, 16, 68, 0, 100}, // m=(13)*17*{137} m/phim(m)=1.15 C=106 D=2 {127, 31752, 32551, 14, 43, 757, 0, 7571, 28768, 0, 42, 54, 0, 100}, // m=43*(757) :-( m/phim(m)=1.02 C=161 D=3 {127, 46656, 51319, 36, 37, 1387, 0, 48546, 24976, 0, 36, -36, 0, 200}, //m=(19)*37*{73}:-( m/phim(m)=1.09 C=141 D=3 {127, 49392, 61103, 28, 43, 1421, 0, 1422, 14234, 0, 42, 42, 0,4000}, // m=(7^2)*{29}*43 m/phim(m)=1.23 C=110 D=2 {127, 54400, 61787, 40, 41, 1507, 0, 30141, 46782, 0, 40, 34, 0, 100}, // m=(11)*41*{137} m/phim(m)=1.13 C=112 D=2 {127, 72000, 77531, 30, 61, 1271, 0, 7627, 34344, 0, 60, 40, 0, 100} // m=(31)*{41}*61 m/phim(m)=1.07 C=128 D=2 }; #define num_mValues (sizeof(mValues)/(14*sizeof(long))) #define OUTER_REP (1) static bool dry = false; // a dry-run flag void TestIt(long idx, long p, long r, long L, long c, long B, long skHwt, bool cons=false, int build_cache=0) { Vec<long> mvec; vector<long> gens; vector<long> ords; long phim = mValues[idx][1]; long m = mValues[idx][2]; assert(GCD(p, m) == 1); append(mvec, mValues[idx][4]); if (mValues[idx][5]>1) append(mvec, mValues[idx][5]); if (mValues[idx][6]>1) append(mvec, mValues[idx][6]); gens.push_back(mValues[idx][7]); if (mValues[idx][8]>1) gens.push_back(mValues[idx][8]); if (mValues[idx][9]>1) gens.push_back(mValues[idx][9]); ords.push_back(mValues[idx][10]); if (abs(mValues[idx][11])>1) ords.push_back(mValues[idx][11]); if (abs(mValues[idx][12])>1) ords.push_back(mValues[idx][12]); if (!noPrint) { cout << "*** TestIt"; if (isDryRun()) cout << " (dry run)"; cout << ": p=" << p << ", r=" << r << ", L=" << L << ", B=" << B << ", t=" << skHwt << ", c=" << c << ", m=" << m << " (=" << mvec << "), gens="<<gens<<", ords="<<ords << endl; cout << "Computing key-independent tables..." << std::flush; } setTimersOn(); setDryRun(false); // Need to get a "real context" to test bootstrapping double t = -GetTime(); FHEcontext context(m, p, r, gens, ords); context.bitsPerLevel = B; buildModChain(context, L, c,/*extraBits=*/7); long nPrimes = context.numPrimes(); IndexSet allPrimes(0,nPrimes-1); double bitsize = context.logOfProduct(allPrimes)/log(2.0); if (!noPrint) cout << " "<<nPrimes<<" primes in chain, total bitsize=" << ceil(bitsize) << ", secparam=" << (7.2*phim/bitsize -110) << endl; // FIXME: The extraBits is an exceedingly ugly patch, used to bypass the // issue that buildModChain must be called BEFORE the context is made // bootstrappable (else the "powerful" basis is not initialized correctly.) // This is a bug, the value 7 is sometimes the right one, but seriously?? context.makeBootstrappable(mvec, /*t=*/0, cons, build_cache); t += GetTime(); if (skHwt>0) context.trcData.skHwt = skHwt; if (!noPrint) { cout << " done in "<<t<<" seconds\n"; cout << " e=" << context.trcData.e << ", e'=" << context.trcData.ePrime << ", alpha="<< context.trcData.alpha << ", t=" << context.trcData.skHwt << "\n "; context.zMStar.printout(); } setDryRun(dry); // Now we can set the dry-run flag if desired long p2r = context.alMod.getPPowR(); context.zMStar.set_cM(mValues[idx][13]/100.0); for (long numkey=0; numkey<OUTER_REP; numkey++) { // test with 3 keys t = -GetTime(); if (!noPrint) cout << "Generating keys, " << std::flush; FHESecKey secretKey(context); FHEPubKey& publicKey = secretKey; secretKey.GenSecKey(64); // A Hamming-weight-64 secret key addSome1DMatrices(secretKey); // compute key-switching matrices that we need addFrbMatrices(secretKey); if (!noPrint) cout << "computing key-dependent tables..." << std::flush; secretKey.genRecryptData(); t += GetTime(); if (!noPrint) cout << " done in "<<t<<" seconds\n"; long d = context.zMStar.getOrdP(); long phim = context.zMStar.getPhiM(); long nslots = phim/d; // GG defines the plaintext space Z_p[X]/GG(X) ZZX GG; GG = context.alMod.getFactorsOverZZ()[0]; EncryptedArray ea(context, GG); zz_p::init(p2r); Vec<zz_p> val0(INIT_SIZE, nslots); for (auto& x: val0) random(x); vector<ZZX> val1; val1.resize(nslots); for (long i = 0; i < nslots; i++) { val1[i] = conv<ZZX>(conv<ZZ>(rep(val0[i]))); } Ctxt c1(publicKey); ea.encrypt(c1, publicKey, val1); Ctxt c2(c1); if (!noPrint) CheckCtxt(c2, "before"); publicKey.thinReCrypt(c2); if (!noPrint) CheckCtxt(c2, "after"); vector<ZZX> val2; ea.decrypt(c2, secretKey, val2); if (val1 == val2) cerr << "GOOD\n"; else cerr << "BAD\n"; //cerr << convert<Vec<ZZX>>(val1) << "\n"; } if (!noPrint) printAllTimers(); } /******************************************************************** ********************************************************************/ int main(int argc, char *argv[]) { ArgMapping amap; long p=2; long r=1; long c=3; long L=25; long B=23; long N=0; long t=0; bool cons=0; long nthreads=1; long seed=0; long useCache=1; amap.arg("p", p, "plaintext base"); amap.arg("r", r, "exponent"); amap.note("p^r is the plaintext-space modulus"); amap.arg("c", c, "number of columns in the key-switching matrices"); amap.arg("L", L, "# of levels in the modulus chain"); amap.arg("B", B, "# of bits per level"); amap.arg("N", N, "lower-bound on phi(m)"); amap.arg("t", t, "Hamming weight of recryption secret key", "heuristic"); amap.arg("dry", dry, "dry=1 for a dry-run"); amap.arg("cons", cons, "cons=1 for consevative settings (circuit deeper by 1)"); amap.arg("nthreads", nthreads, "number of threads"); amap.arg("seed", seed, "random number seed"); amap.arg("noPrint", noPrint, "suppress printouts"); amap.arg("useCache", useCache, "0: zzX cache, 1: DCRT cache"); amap.arg("force_bsgs", fhe_test_force_bsgs); amap.arg("force_hoist", fhe_test_force_hoist); amap.arg("init_level", thinRecrypt_initial_level); amap.parse(argc, argv); if (seed) SetSeed(ZZ(seed)); SetNumThreads(nthreads); if (B<=0) B=FHE_pSize; if (B>NTL_SP_NBITS/2) B = NTL_SP_NBITS/2; for (long i=0; i<(long)num_mValues; i++) if (mValues[i][0]==p && mValues[i][1]>=N) { TestIt(i,p,r,L,c,B,t,cons,useCache); break; } return 0; }
[ "alexander.viand@inf.ethz.ch" ]
alexander.viand@inf.ethz.ch
4e795a9ac65f4f42bd5ab40b91c0da0b35d58390
833a483f74e12c36ab030458ca0bfd7426254964
/include/core/ycommon.hpp
83cba5856966e9651639e3c0a16b7f0ad2140d74
[ "BSD-3-Clause", "curl", "MIT", "LicenseRef-scancode-public-domain" ]
permissive
flyinskyin2013/yLib
28a21848c88df544162b1c9f40748f9afbe21d30
0872a3b69ee80a1a46ae0fc9c9a06cb9fcc25c05
refs/heads/master
2023-06-24T06:47:00.132507
2021-12-12T10:25:51
2021-12-12T10:25:51
142,399,267
0
0
null
null
null
null
UTF-8
C++
false
false
2,919
hpp
/* Copyright (c) 2018 - 2021 flyinskyin2013 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 copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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. */ /* * @Author: Sky * @Date: 2018-10-23 11:07:58 * @LastEditors: Please set LastEditors * @LastEditTime: 2021-09-12 10:18:01 * @Description: */ #ifndef __YLIB_CORE_YCOMMON_HPP__ #define __YLIB_CORE_YCOMMON_HPP__ #include <string> #include <ctime> #include "yobject.hpp" namespace yLib{ /** * @class yCommon * @brief This is common-class in yLib. */ class __YLIB_CLASS_DECLSPEC__ yCommon: YLIB_PUBLIC_INHERIT_YOBJECT { public: /** * @fn static YLIB_STD_STRING ConvertErrnoToStr(uint64_t err_num) noexcept * @brief convert errno to str, it wrappers strerror_r() and FormatMessage().it's thread-safety. */ static YLIB_STD_STRING ConvertErrnoToStr(uint64_t err_num) noexcept; static int GetCurrentThreadId(void) noexcept; /** * @fn static void yLibGetUtcTimeAndLocalTime(struct ::timespec &time_spec, struct ::tm &tm_time) noexcept * @brief convert utc time to time_spec and tm_time, tm_time.tm_yday can't be used in windows. It's like clock_gettime() and localtime_r() on linux. */ static void GetUtcTimeAndLocalTime(struct ::timespec &time_spec, struct ::tm &tm_time) noexcept; static bool CheckFileExist(const char * full_name) noexcept; YLIB_DECLARE_CLASSINFO_CONTENT(yCommon); }; } #endif //__YLIB_CORE_YCOMMON_HPP__
[ "sky@sky-home.com" ]
sky@sky-home.com
f0cbe56f468195bf6b976e91dc1587aaeed9c241
54f352a242a8ad6ff5516703e91da61e08d9a9e6
/Source Codes/CodeJamData/13/42/4.cpp
462cee1fc813219818cbb23d7c965622389001fe
[]
no_license
Kawser-nerd/CLCDSA
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
aee32551795763b54acb26856ab239370cac4e75
refs/heads/master
2022-02-09T11:08:56.588303
2022-01-26T18:53:40
2022-01-26T18:53:40
211,783,197
23
9
null
null
null
null
UTF-8
C++
false
false
1,943
cpp
#include <cstdio> #include <numeric> #include <iostream> #include <vector> #include <set> #include <cstring> #include <string> #include <map> #include <cmath> #include <ctime> #include <algorithm> #include <bitset> #include <queue> #include <sstream> #include <deque> using namespace std; #define mp make_pair #define pb push_back #define rep(i,n) for(int i = 0; i < (n); i++) #define re return #define fi first #define se second #define sz(x) ((int) (x).size()) #define all(x) (x).begin(), (x).end() #define sqr(x) ((x) * (x)) #define sqrt(x) sqrt(abs(x)) #define y0 y3487465 #define y1 y8687969 #define fill(x,y) memset(x,y,sizeof(x)) typedef vector<int> vi; typedef long long ll; typedef long double ld; typedef double D; typedef pair<int, int> ii; typedef vector<ii> vii; typedef vector<string> vs; typedef vector<vi> vvi; template<class T> T abs(T x) { re x > 0 ? x : -x; } ll n, m, k; ll best (ll x) { ll y = k - x - 1, ans = 0; for (int i = 0; i < n; i++) if (y > 0) { ans = ans * 2; y = (y - 1) / 2; } else ans = ans * 2 + 1; re ans; } ll worst (ll x) { ll y = x, ans = 0; for (int i = 0; i < n; i++) if (y > 0) { ans = ans * 2 + 1; y = (y - 1) / 2; } else ans = ans * 2; re ans; } int main () { int tt; cin >> tt; for (int it = 1; it <= tt; it++) { cin >> n >> m; k = (ll)1 << n; ll l, r, x, y; l = 0; r = (ll)1 << n; while (r - l > 1) { ll s = (l + r) / 2; if (worst (s) < m) l = s; else r = s; } x = l; l = 0; r = (ll)1 << n; while (r - l > 1) { ll s = (l + r) / 2; if (best (s) < m) l = s; else r = s; } y = l; cout << "Case #" << it << ": " << x << " " << y; cout << endl; cerr << it << " / " << tt << endl; } return 0; }
[ "kwnafi@yahoo.com" ]
kwnafi@yahoo.com
b8cf0adac7e7747694a0a954ac437db6be647b49
819875a388d7caf6795941db8104f4bf72677b90
/chrome/browser/intents/.svn/text-base/web_intents_registry_factory.cc.svn-base
f6e75c929b9d0e67a99226e647c3a5846b12f22f
[ "BSD-3-Clause" ]
permissive
gx1997/chrome-loongson
07b763eb1d0724bf0d2e0a3c2b0eb274e9a2fb4c
1cb7e00e627422577e8b7085c2d2892eda8590ae
refs/heads/master
2020-04-28T02:04:13.872019
2012-08-16T10:09:25
2012-08-16T10:09:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,643
// Copyright (c) 2012 The Chromium 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 "chrome/browser/intents/web_intents_registry_factory.h" #include "base/memory/singleton.h" #include "chrome/browser/extensions/extension_system_factory.h" #include "chrome/browser/intents/web_intents_registry.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_dependency_manager.h" // static WebIntentsRegistry* WebIntentsRegistryFactory::GetForProfile(Profile* profile) { return static_cast<WebIntentsRegistry*>( GetInstance()->GetServiceForProfile(profile, true)); } WebIntentsRegistryFactory::WebIntentsRegistryFactory() : ProfileKeyedServiceFactory("WebIntentsRegistry", ProfileDependencyManager::GetInstance()) { // TODO(erg): For Shutdown() order, we need to: // DependsOn(WebDataServiceFactory::GetInstance()); DependsOn(ExtensionSystemFactory::GetInstance()); } WebIntentsRegistryFactory::~WebIntentsRegistryFactory() { } // static WebIntentsRegistryFactory* WebIntentsRegistryFactory::GetInstance() { return Singleton<WebIntentsRegistryFactory>::get(); } ProfileKeyedService* WebIntentsRegistryFactory::BuildServiceInstanceFor( Profile* profile) const { WebIntentsRegistry* registry = new WebIntentsRegistry; registry->Initialize(profile->GetWebDataService(Profile::EXPLICIT_ACCESS), profile->GetExtensionService()); return registry; } bool WebIntentsRegistryFactory::ServiceRedirectedInIncognito() { return false; }
[ "loongson@Loong.(none)" ]
loongson@Loong.(none)
e957e31f682348860100c0e6fdff4c5cee2961c9
cbd0828085aef90573bcc156dd2896a072a31e19
/src/qt/transactionrecord.h
9621141743b70c60d48729b9413c5019b323e845
[ "Apache-2.0", "MIT" ]
permissive
cruzezy/newbitcoin
77be346a907c4d7c73b628830c142b5be5f0e016
7767d558c5047e9f11e2e5eb9bf3f885a03adb08
refs/heads/master
2020-05-31T14:41:21.555143
2019-06-08T11:53:28
2019-06-08T11:53:28
190,334,840
0
0
null
null
null
null
UTF-8
C++
false
false
4,410
h
// Copyright (c) 2011-2013 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef NETGOLD_QT_TRANSACTIONRECORD_H #define NETGOLD_QT_TRANSACTIONRECORD_H #include "amount.h" #include "uint256.h" #include <QList> #include <QString> class CWallet; class CWalletTx; /** UI model for transaction status. The transaction status is the part of a transaction that will change over time. */ class TransactionStatus { public: TransactionStatus(): countsForBalance(false), sortKey(""), matures_in(0), status(Offline), depth(0), open_for(0), cur_num_blocks(-1) { } enum Status { Confirmed, /**< Have 6 or more confirmations (normal tx) or fully mature (mined tx) **/ /// Normal (sent/received) transactions OpenUntilDate, /**< Transaction not yet final, waiting for date */ OpenUntilBlock, /**< Transaction not yet final, waiting for block */ Offline, /**< Not sent to any other nodes **/ Unconfirmed, /**< Not yet mined into a block **/ Confirming, /**< Confirmed, but waiting for the recommended number of confirmations **/ Conflicted, /**< Conflicts with other transaction or mempool **/ /// Generated (mined) transactions Immature, /**< Mined but waiting for maturity */ MaturesWarning, /**< Transaction will likely not mature because no nodes have confirmed */ NotAccepted /**< Mined but not accepted */ }; /// Transaction counts towards available balance bool countsForBalance; /// Sorting key based on status std::string sortKey; /** @name Generated (mined) transactions @{*/ int matures_in; /**@}*/ /** @name Reported status @{*/ Status status; qint64 depth; qint64 open_for; /**< Timestamp if status==OpenUntilDate, otherwise number of additional blocks that need to be mined before finalization */ /**@}*/ /** Current number of blocks (to know whether cached status is still valid) */ int cur_num_blocks; }; /** UI model for a transaction. A core transaction can be represented by multiple UI transactions if it has multiple outputs. */ class TransactionRecord { public: enum Type { Other, Generated, SendToAddress, SendToOther, RecvWithAddress, RecvFromOther, SendToSelf }; /** Number of confirmation recommended for accepting a transaction */ static const int RecommendedNumConfirmations = 6; TransactionRecord(): hash(), time(0), type(Other), address(""), debit(0), credit(0), idx(0) { } TransactionRecord(uint256 hash, qint64 time): hash(hash), time(time), type(Other), address(""), debit(0), credit(0), idx(0) { } TransactionRecord(uint256 hash, qint64 time, Type type, const std::string &address, const CAmount& debit, const CAmount& credit): hash(hash), time(time), type(type), address(address), debit(debit), credit(credit), idx(0) { } /** Decompose CWallet transaction to model transaction records. */ static bool showTransaction(const CWalletTx &wtx); static QList<TransactionRecord> decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx); /** @name Immutable transaction attributes @{*/ uint256 hash; qint64 time; Type type; std::string address; CAmount debit; CAmount credit; /**@}*/ /** Subtransaction index, for sort key */ int idx; /** Status: can change with block chain update */ TransactionStatus status; /** Whether the transaction was sent/received with a watch-only address */ bool involvesWatchAddress; /** Return the unique identifier for this transaction (part) */ QString getTxID() const; /** Format subtransaction id */ static QString formatSubTxId(const uint256 &hash, int vout); /** Update status from core wallet tx. */ void updateStatus(const CWalletTx &wtx); /** Return whether a status update is needed. */ bool statusUpdateNeeded(); }; #endif // NETGOLD_QT_TRANSACTIONRECORD_H
[ "20241460@qq.com" ]
20241460@qq.com
2c3fa29d815031fb283f1d320fb00df102903a83
9812878facb228acb985b187e1e043c78b64a698
/2016-04-14/Empty Position/main.cpp
e5965852ec7d98ade3512b9c2a0860ba2ac60b83
[]
no_license
sparrow72/CS201R
a3a4a1bcf1f3c1fa04ec6d2d6f4a4442042fb3b2
4fca868ee340318f647b385bd583eb189bceb9bd
refs/heads/master
2020-12-29T00:56:00.617937
2016-04-14T23:42:16
2016-04-14T23:42:16
56,274,217
0
0
null
2016-04-14T22:35:42
2016-04-14T22:35:41
null
UTF-8
C++
false
false
551
cpp
#include <iostream> #include <cstdlib> #include <ctime> #include <string> using namespace std; int main() { float gpas[] = { 4.0, 3.0, -1, 2.0, 3.0, 3.5, -1, 3.2 }; float newGpa = 3.4; int emptyIndex = -1; for ( int i = 0; i < 8; i++ ) { if ( gpas[i] == -1 ) { emptyIndex = i; break; } } if ( emptyIndex != -1 ) { gpas[emptyIndex ] = newGpa; } for ( int i = 0; i < 8; i++ ) { cout << i << ": " << gpas[i] << endl; } return 0; }
[ "racheljmorris@gmail.com" ]
racheljmorris@gmail.com
4cc18eae7f2f24a5bc38e7fabebcfb79b17e70c2
62d5d3329e8649ce3b918780a609476b89358536
/Classes/GraphNode.cpp
90bf39adaad23a874cf86e4846c2876529c9a0f2
[]
no_license
JackLinMaker/PathFinder
3d2b6225e6d318435f3791efae29d3ffc2bdddd7
567bae23127e530600ff1cca3fc23a7252d4e879
refs/heads/master
2016-09-05T12:26:59.657874
2014-11-27T15:28:02
2014-11-27T15:28:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
661
cpp
// // GraphNode.cpp // PathFinder // // Created by 林光海 on 14-11-27. // // #include "GraphNode.h" GraphNode* GraphNode::create(int index) { GraphNode* node = new GraphNode(); if(node && node->init(index)) { node->autorelease(); return node; } CC_SAFE_DELETE(node); return NULL; } bool GraphNode::init(int index) { if(Node::init()) { _index = index; return true; } return false; } GraphNode::GraphNode():_index(invalid_node_index) { } GraphNode::~GraphNode() { } int GraphNode::Index() const { return _index; } void GraphNode::SetIndex(int index) { _index = index; }
[ "jacklinmaker@gmail.com" ]
jacklinmaker@gmail.com
6eed4fe53806733c16e2679435b1c1a60f726ee4
c612f9fd2fba45dfeaf2cb27884b30f520287f77
/chrome/browser/apps/app_service/app_service_test.cc
e9211ca98049740602ba9b34d8a5f67c7561e519
[ "BSD-3-Clause" ]
permissive
Turno/chromium
c498ab6d3c058d737b17439029989f69f58fe9c7
4e5eb9aba6c91df5e965f3eecd76c3ae17b0b216
refs/heads/master
2022-12-07T22:58:55.989642
2020-08-10T12:03:21
2020-08-10T12:03:21
286,471,394
1
0
BSD-3-Clause
2020-08-10T12:39:55
2020-08-10T12:39:54
null
UTF-8
C++
false
false
2,127
cc
// Copyright 2016 The Chromium 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 "chrome/browser/apps/app_service/app_service_test.h" #include "base/run_loop.h" #include "chrome/browser/apps/app_service/app_service_proxy.h" #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" #if defined(OS_CHROMEOS) #include "chrome/browser/apps/app_service/arc_apps.h" #include "chrome/browser/apps/app_service/arc_apps_factory.h" #endif // OS_CHROMEOS namespace apps { AppServiceTest::AppServiceTest() = default; AppServiceTest::~AppServiceTest() = default; void AppServiceTest::SetUp(Profile* profile) { profile_ = profile; app_service_proxy_ = apps::AppServiceProxyFactory::GetForProfile(profile); app_service_proxy_->ReInitializeForTesting(profile); // Allow async callbacks to run. WaitForAppService(); } void AppServiceTest::UninstallAllApps(Profile* profile) { AppServiceProxy* app_service_proxy_ = apps::AppServiceProxyFactory::GetForProfile(profile); std::vector<apps::mojom::AppPtr> apps; app_service_proxy_->AppRegistryCache().ForEachApp( [&apps](const apps::AppUpdate& update) { apps::mojom::AppPtr app = apps::mojom::App::New(); app->app_type = update.AppType(); app->app_id = update.AppId(); app->readiness = apps::mojom::Readiness::kUninstalledByUser; apps.push_back(app.Clone()); }); app_service_proxy_->AppRegistryCache().OnApps(std::move(apps)); // Allow async callbacks to run. WaitForAppService(); } std::string AppServiceTest::GetAppName(const std::string& app_id) const { std::string name; if (!app_service_proxy_) return name; app_service_proxy_->AppRegistryCache().ForOneApp( app_id, [&name](const apps::AppUpdate& update) { name = update.Name(); }); return name; } void AppServiceTest::WaitForAppService() { base::RunLoop().RunUntilIdle(); } void AppServiceTest::FlushMojoCalls() { if (app_service_proxy_) { app_service_proxy_->FlushMojoCallsForTesting(); } } } // namespace apps
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
ecc42ecd64cf4a14d0b1cb2abd5b9b99ea02b258
3bda6350083b34b387c31f0b9761bedb156551db
/pair_style_gauss-erfc.cpp
4fd5be7a84848ec423343dbc8a03423d7696e61b
[]
no_license
jonqdoe/mpi2
12277212efe5101ca34bbbb15ad12dcffd2ba881
6a09c9987158916e0dfd9762302b98fd0ca9f20f
refs/heads/master
2020-04-24T05:52:10.333114
2019-08-18T21:59:25
2019-08-18T21:59:25
171,744,803
0
0
null
null
null
null
UTF-8
C++
false
false
1,774
cpp
#include "globals.h" #include "pair_style_gauss-erfc.h" #include "field_component.h" void GaussianErfc::Initialize_GaussianErfc(double Ao, double sigma_squared, double Rp, double xi, int alloc_size, FieldComponent A, FieldComponent B) { Initialize_PairStyle(alloc_size, A, B) ; printf("Setting up Gaussian-Erfc pair style...") ;fflush(stdout) ; int i , j; double k2, kv[Dim], ro[Dim], rc[Dim], dr[Dim], mdr2, mdr ; for ( j=0 ; j<Dim ; j++ ) ro[j] = 0.0 ; // Define the potential and the force in k-space for ( i=0 ; i<alloc_size ; i++ ) { get_r( i, rc ) ; mdr2 = pbc_mdr2( ro, rc, dr) ; mdr = sqrt(mdr2) ; tmp[i] = Ao * V / 2.0 * ( 1.0 - erf( ( mdr - Rp ) / xi ) ) ; } fftw_fwd( tmp, ktmp ) ; for ( i=0 ; i<ML ; i++ ) { k2 = get_k(i, kv) ; ktmp[i] *= exp( -k2 * sigma_squared / 2.0 ) ; this->u_k[i] = ktmp[i] ; for ( j=0 ; j<Dim ; j++ ) this->f_k[j][i] = -I * kv[j] * this->u_k[i] ; } fftw_back( this->u_k, this->u ) ; for ( j=0 ; j<Dim ; j++ ) fftw_back( this->f_k[j], this->f[j] ) ; this->setup_virial() ; printf("done!\n"); fflush(stdout) ; } void allocate_gausserfcs() { gausserfc_prefactor = ( double* ) calloc( n_gausserfc_pairstyles, sizeof(double) ) ; gausserfc_sigma = ( double* ) calloc( n_gausserfc_pairstyles, sizeof(double) ) ; gausserfc_Rp = ( double* ) calloc( n_gausserfc_pairstyles, sizeof(double) ) ; gausserfc_xi = ( double* ) calloc( n_gausserfc_pairstyles, sizeof(double) ) ; gausserfc_types = ( int** ) calloc( n_gausserfc_pairstyles, sizeof( int* ) ) ; for (int i=0 ; i<n_gausserfc_pairstyles ; i++ ) gausserfc_types[i] = (int*) calloc( 2, sizeof(int) ) ; } GaussianErfc::GaussianErfc() { } GaussianErfc::~GaussianErfc() { }
[ "rrig@seas.upenn.edu" ]
rrig@seas.upenn.edu
bc362d04e91e2bce8bd3dc779d42a367520e7cd5
ff3c7d81878d6577a99daee0fe107bdb4a821782
/problem2.cpp
f26949472f82e16d3b3051b49e9d8e81eb6769c0
[]
no_license
tristanhanna/DataStructures
363e625d94e3b837ea368e1a5891e0e136b01a74
2f484eb7f3075daf6613393a01ea3125596a7895
refs/heads/master
2020-07-14T05:16:16.971420
2019-08-29T20:54:53
2019-08-29T20:54:53
205,247,664
0
0
null
null
null
null
UTF-8
C++
false
false
1,117
cpp
#include <iostream> #include <fstream> #include <sstream> #include <vector> using namespace std; struct User{ string username; float gpa; int age; }; void addUser(vector<User> *users, string _username, float _gpa, int _age){ User user; user.username=_username; user.gpa=_gpa; user.age=_age; users->push_back(user); } void printList(const vector<User> users){ auto size= users.size(); for(int i=0; i<size; i++){ User taco=users[i]; string theuser=taco.username; float thegpa=taco.gpa; int theage=taco.age; cout << theuser << "[" << thegpa << "] age: " << theage <<endl; } } int main(){ string filename cout << "What is the name of your file?"<<endl; getline(cin, filename); ifstream thefile(filename); string line; vector<User> thePeeps; while(thefile, line){ stringstream banana(line); string name, gpaa, aage; banana >> name >> gpaa >> aage; float gpa=stof(gpaa); int age=stoi(aage); addUser(thePeeps, name, gpa, age); } printList(thePeeps); }
[ "noreply@github.com" ]
noreply@github.com
308d134524785ee8aeb83f911906c8acc0d09595
3282ccae547452b96c4409e6b5a447f34b8fdf64
/SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimFlowMover_ReturnFan.cxx
afb779533578a303f25351dc0717ff4b9d852e5d
[ "MIT" ]
permissive
EnEff-BIM/EnEffBIM-Framework
c8bde8178bb9ed7d5e3e5cdf6d469a009bcb52de
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
refs/heads/master
2021-01-18T00:16:06.546875
2017-04-18T08:03:40
2017-04-18T08:03:40
28,960,534
3
0
null
2017-04-18T08:03:40
2015-01-08T10:19:18
C++
UTF-8
C++
false
false
14,035
cxx
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program 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. // // 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 St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // // Begin prologue. // // // End prologue. #include <xsd/cxx/pre.hxx> #include "SimFlowMover_ReturnFan.hxx" namespace schema { namespace simxml { namespace MepModel { // SimFlowMover_ReturnFan // const SimFlowMover_ReturnFan::FanPerf_NightVent_FanName_optional& SimFlowMover_ReturnFan:: FanPerf_NightVent_FanName () const { return this->FanPerf_NightVent_FanName_; } SimFlowMover_ReturnFan::FanPerf_NightVent_FanName_optional& SimFlowMover_ReturnFan:: FanPerf_NightVent_FanName () { return this->FanPerf_NightVent_FanName_; } void SimFlowMover_ReturnFan:: FanPerf_NightVent_FanName (const FanPerf_NightVent_FanName_type& x) { this->FanPerf_NightVent_FanName_.set (x); } void SimFlowMover_ReturnFan:: FanPerf_NightVent_FanName (const FanPerf_NightVent_FanName_optional& x) { this->FanPerf_NightVent_FanName_ = x; } void SimFlowMover_ReturnFan:: FanPerf_NightVent_FanName (::std::auto_ptr< FanPerf_NightVent_FanName_type > x) { this->FanPerf_NightVent_FanName_.set (x); } const SimFlowMover_ReturnFan::FanPerf_NightVent_FanTotalEff_optional& SimFlowMover_ReturnFan:: FanPerf_NightVent_FanTotalEff () const { return this->FanPerf_NightVent_FanTotalEff_; } SimFlowMover_ReturnFan::FanPerf_NightVent_FanTotalEff_optional& SimFlowMover_ReturnFan:: FanPerf_NightVent_FanTotalEff () { return this->FanPerf_NightVent_FanTotalEff_; } void SimFlowMover_ReturnFan:: FanPerf_NightVent_FanTotalEff (const FanPerf_NightVent_FanTotalEff_type& x) { this->FanPerf_NightVent_FanTotalEff_.set (x); } void SimFlowMover_ReturnFan:: FanPerf_NightVent_FanTotalEff (const FanPerf_NightVent_FanTotalEff_optional& x) { this->FanPerf_NightVent_FanTotalEff_ = x; } const SimFlowMover_ReturnFan::FanPerf_NightVent_PresRise_optional& SimFlowMover_ReturnFan:: FanPerf_NightVent_PresRise () const { return this->FanPerf_NightVent_PresRise_; } SimFlowMover_ReturnFan::FanPerf_NightVent_PresRise_optional& SimFlowMover_ReturnFan:: FanPerf_NightVent_PresRise () { return this->FanPerf_NightVent_PresRise_; } void SimFlowMover_ReturnFan:: FanPerf_NightVent_PresRise (const FanPerf_NightVent_PresRise_type& x) { this->FanPerf_NightVent_PresRise_.set (x); } void SimFlowMover_ReturnFan:: FanPerf_NightVent_PresRise (const FanPerf_NightVent_PresRise_optional& x) { this->FanPerf_NightVent_PresRise_ = x; } const SimFlowMover_ReturnFan::FanPerf_NightVent_MaxFlowRate_optional& SimFlowMover_ReturnFan:: FanPerf_NightVent_MaxFlowRate () const { return this->FanPerf_NightVent_MaxFlowRate_; } SimFlowMover_ReturnFan::FanPerf_NightVent_MaxFlowRate_optional& SimFlowMover_ReturnFan:: FanPerf_NightVent_MaxFlowRate () { return this->FanPerf_NightVent_MaxFlowRate_; } void SimFlowMover_ReturnFan:: FanPerf_NightVent_MaxFlowRate (const FanPerf_NightVent_MaxFlowRate_type& x) { this->FanPerf_NightVent_MaxFlowRate_.set (x); } void SimFlowMover_ReturnFan:: FanPerf_NightVent_MaxFlowRate (const FanPerf_NightVent_MaxFlowRate_optional& x) { this->FanPerf_NightVent_MaxFlowRate_ = x; } const SimFlowMover_ReturnFan::FanPerf_NightVent_MotorEff_optional& SimFlowMover_ReturnFan:: FanPerf_NightVent_MotorEff () const { return this->FanPerf_NightVent_MotorEff_; } SimFlowMover_ReturnFan::FanPerf_NightVent_MotorEff_optional& SimFlowMover_ReturnFan:: FanPerf_NightVent_MotorEff () { return this->FanPerf_NightVent_MotorEff_; } void SimFlowMover_ReturnFan:: FanPerf_NightVent_MotorEff (const FanPerf_NightVent_MotorEff_type& x) { this->FanPerf_NightVent_MotorEff_.set (x); } void SimFlowMover_ReturnFan:: FanPerf_NightVent_MotorEff (const FanPerf_NightVent_MotorEff_optional& x) { this->FanPerf_NightVent_MotorEff_ = x; } const SimFlowMover_ReturnFan::FanPerf_NightVent_MotorInAirstreamFrac_optional& SimFlowMover_ReturnFan:: FanPerf_NightVent_MotorInAirstreamFrac () const { return this->FanPerf_NightVent_MotorInAirstreamFrac_; } SimFlowMover_ReturnFan::FanPerf_NightVent_MotorInAirstreamFrac_optional& SimFlowMover_ReturnFan:: FanPerf_NightVent_MotorInAirstreamFrac () { return this->FanPerf_NightVent_MotorInAirstreamFrac_; } void SimFlowMover_ReturnFan:: FanPerf_NightVent_MotorInAirstreamFrac (const FanPerf_NightVent_MotorInAirstreamFrac_type& x) { this->FanPerf_NightVent_MotorInAirstreamFrac_.set (x); } void SimFlowMover_ReturnFan:: FanPerf_NightVent_MotorInAirstreamFrac (const FanPerf_NightVent_MotorInAirstreamFrac_optional& x) { this->FanPerf_NightVent_MotorInAirstreamFrac_ = x; } } } } #include <xsd/cxx/xml/dom/parsing-source.hxx> #include <xsd/cxx/tree/type-factory-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_factory_plate< 0, char > type_factory_plate_init; } namespace schema { namespace simxml { namespace MepModel { // SimFlowMover_ReturnFan // SimFlowMover_ReturnFan:: SimFlowMover_ReturnFan () : ::schema::simxml::MepModel::SimFlowMover (), FanPerf_NightVent_FanName_ (this), FanPerf_NightVent_FanTotalEff_ (this), FanPerf_NightVent_PresRise_ (this), FanPerf_NightVent_MaxFlowRate_ (this), FanPerf_NightVent_MotorEff_ (this), FanPerf_NightVent_MotorInAirstreamFrac_ (this) { } SimFlowMover_ReturnFan:: SimFlowMover_ReturnFan (const RefId_type& RefId) : ::schema::simxml::MepModel::SimFlowMover (RefId), FanPerf_NightVent_FanName_ (this), FanPerf_NightVent_FanTotalEff_ (this), FanPerf_NightVent_PresRise_ (this), FanPerf_NightVent_MaxFlowRate_ (this), FanPerf_NightVent_MotorEff_ (this), FanPerf_NightVent_MotorInAirstreamFrac_ (this) { } SimFlowMover_ReturnFan:: SimFlowMover_ReturnFan (const SimFlowMover_ReturnFan& x, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::MepModel::SimFlowMover (x, f, c), FanPerf_NightVent_FanName_ (x.FanPerf_NightVent_FanName_, f, this), FanPerf_NightVent_FanTotalEff_ (x.FanPerf_NightVent_FanTotalEff_, f, this), FanPerf_NightVent_PresRise_ (x.FanPerf_NightVent_PresRise_, f, this), FanPerf_NightVent_MaxFlowRate_ (x.FanPerf_NightVent_MaxFlowRate_, f, this), FanPerf_NightVent_MotorEff_ (x.FanPerf_NightVent_MotorEff_, f, this), FanPerf_NightVent_MotorInAirstreamFrac_ (x.FanPerf_NightVent_MotorInAirstreamFrac_, f, this) { } SimFlowMover_ReturnFan:: SimFlowMover_ReturnFan (const ::xercesc::DOMElement& e, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::MepModel::SimFlowMover (e, f | ::xml_schema::flags::base, c), FanPerf_NightVent_FanName_ (this), FanPerf_NightVent_FanTotalEff_ (this), FanPerf_NightVent_PresRise_ (this), FanPerf_NightVent_MaxFlowRate_ (this), FanPerf_NightVent_MotorEff_ (this), FanPerf_NightVent_MotorInAirstreamFrac_ (this) { if ((f & ::xml_schema::flags::base) == 0) { ::xsd::cxx::xml::dom::parser< char > p (e, true, false, true); this->parse (p, f); } } void SimFlowMover_ReturnFan:: parse (::xsd::cxx::xml::dom::parser< char >& p, ::xml_schema::flags f) { this->::schema::simxml::MepModel::SimFlowMover::parse (p, f); for (; p.more_content (); p.next_content (false)) { const ::xercesc::DOMElement& i (p.cur_element ()); const ::xsd::cxx::xml::qualified_name< char > n ( ::xsd::cxx::xml::dom::name< char > (i)); // FanPerf_NightVent_FanName // if (n.name () == "FanPerf_NightVent_FanName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< FanPerf_NightVent_FanName_type > r ( FanPerf_NightVent_FanName_traits::create (i, f, this)); if (!this->FanPerf_NightVent_FanName_) { this->FanPerf_NightVent_FanName_.set (r); continue; } } // FanPerf_NightVent_FanTotalEff // if (n.name () == "FanPerf_NightVent_FanTotalEff" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->FanPerf_NightVent_FanTotalEff_) { this->FanPerf_NightVent_FanTotalEff_.set (FanPerf_NightVent_FanTotalEff_traits::create (i, f, this)); continue; } } // FanPerf_NightVent_PresRise // if (n.name () == "FanPerf_NightVent_PresRise" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->FanPerf_NightVent_PresRise_) { this->FanPerf_NightVent_PresRise_.set (FanPerf_NightVent_PresRise_traits::create (i, f, this)); continue; } } // FanPerf_NightVent_MaxFlowRate // if (n.name () == "FanPerf_NightVent_MaxFlowRate" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->FanPerf_NightVent_MaxFlowRate_) { this->FanPerf_NightVent_MaxFlowRate_.set (FanPerf_NightVent_MaxFlowRate_traits::create (i, f, this)); continue; } } // FanPerf_NightVent_MotorEff // if (n.name () == "FanPerf_NightVent_MotorEff" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->FanPerf_NightVent_MotorEff_) { this->FanPerf_NightVent_MotorEff_.set (FanPerf_NightVent_MotorEff_traits::create (i, f, this)); continue; } } // FanPerf_NightVent_MotorInAirstreamFrac // if (n.name () == "FanPerf_NightVent_MotorInAirstreamFrac" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->FanPerf_NightVent_MotorInAirstreamFrac_) { this->FanPerf_NightVent_MotorInAirstreamFrac_.set (FanPerf_NightVent_MotorInAirstreamFrac_traits::create (i, f, this)); continue; } } break; } } SimFlowMover_ReturnFan* SimFlowMover_ReturnFan:: _clone (::xml_schema::flags f, ::xml_schema::container* c) const { return new class SimFlowMover_ReturnFan (*this, f, c); } SimFlowMover_ReturnFan& SimFlowMover_ReturnFan:: operator= (const SimFlowMover_ReturnFan& x) { if (this != &x) { static_cast< ::schema::simxml::MepModel::SimFlowMover& > (*this) = x; this->FanPerf_NightVent_FanName_ = x.FanPerf_NightVent_FanName_; this->FanPerf_NightVent_FanTotalEff_ = x.FanPerf_NightVent_FanTotalEff_; this->FanPerf_NightVent_PresRise_ = x.FanPerf_NightVent_PresRise_; this->FanPerf_NightVent_MaxFlowRate_ = x.FanPerf_NightVent_MaxFlowRate_; this->FanPerf_NightVent_MotorEff_ = x.FanPerf_NightVent_MotorEff_; this->FanPerf_NightVent_MotorInAirstreamFrac_ = x.FanPerf_NightVent_MotorInAirstreamFrac_; } return *this; } SimFlowMover_ReturnFan:: ~SimFlowMover_ReturnFan () { } } } } #include <istream> #include <xsd/cxx/xml/sax/std-input-source.hxx> #include <xsd/cxx/tree/error-handler.hxx> namespace schema { namespace simxml { namespace MepModel { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue.
[ "cao@e3d.rwth-aachen.de" ]
cao@e3d.rwth-aachen.de
1b5b8f301a7b63796aa21f718049690810966a7a
900b128f526a4d2274014dc6bfb28a163cddc971
/src/cachesim_driver.cpp
e1e10c72a1b5cd8360d00b28881d6e4c0bb24ef1
[]
no_license
ConnerBluck/Cache-Hierarchy-Simulator
63c89fb555f92f9a895a8892384571be5d35fad2
f530c197f3b05548a73adb925deefd7e3380d35a
refs/heads/main
2023-07-08T13:40:55.215490
2021-08-19T23:12:45
2021-08-19T23:12:45
398,093,244
0
0
null
null
null
null
UTF-8
C++
false
false
10,834
cpp
/** * @file cache_driver.c * @brief Trace reader and driver for the CS 4290 Summer 2021 Project 1 * * Project 1 trace reader and driver. Do not modify this file! * * @author Anirudh Jain */ #include <getopt.h> #include <unistd.h> #include <cstdarg> #include <cinttypes> #include <cstdio> #include <cstdbool> #include <cstdlib> #include <cstring> #include <string> #include "util/jsmn.h" #include "cache.hpp" // Print error usage static void print_err_usage(const char *err) { printf("%s\n", err); fprintf(stderr, "./cachesim -c <configuration file> -i <trace file>\n"); fprintf(stderr, "Look at default.conf for example configuration file\n"); exit(EXIT_FAILURE); } static inline void print_error_exit(const char *msg, ...) { va_list argptr; va_start(argptr, msg); fprintf(stderr, msg, argptr); va_end(argptr); exit(EXIT_FAILURE); } // Function to print the run configuration static void print_sim_config(struct sim_config_t *sim_conf) { fprintf(stdout, "SIMULATION CONFIGURATION\n"); fprintf(stdout, "L1 Data Cache: (C=%" PRIu64 ", B=%" PRIu64 ", S=%" PRIu64 ")\n", sim_conf->l1data.c, sim_conf->l1data.b, sim_conf->l1data.s); fprintf(stdout, "Replacement Policy: %s\n", replacement_policy_map[sim_conf->rp]); fprintf(stdout, "Victim Cache: %s; V:%" PRIu64 "\n", sim_conf->has_victim_cache ? "yes" : "no", sim_conf->V); } static void print_sim_output(struct sim_stats_t *sim_stats) { printf("\nSIMULATION OUTPUT\n"); // L1 Data Stats printf("L1 Data Accesses %" PRIu64 "\n", sim_stats->l1data_num_accesses); printf("L1 Data Load Accesses %" PRIu64 "\n", sim_stats->l1data_num_accesses_loads); printf("L1 Data Store Accesses %" PRIu64 "\n", sim_stats->l1data_num_accesses_stores); printf("L1 Data Misses %" PRIu64 "\n", sim_stats->l1data_num_misses); printf("L1 Data Load Misses %" PRIu64 "\n", sim_stats->l1data_num_misses_loads); printf("L1 Data Store Misses %" PRIu64 "\n", sim_stats->l1data_num_misses_stores); printf("L1 Data Evictions %" PRIu64 "\n", sim_stats->l1data_num_evictions); // VC stats printf("Victim Cache Accesses %" PRIu64 "\n", sim_stats->victim_cache_accesses); printf("Victim Cache Misses %" PRIu64 "\n", sim_stats->victim_cache_misses); printf("Victim Cache Hits %" PRIu64 "\n", sim_stats->victim_cache_hits); // Membus stats printf("Number of writebacks %" PRIu64 "\n", sim_stats->num_writebacks); printf("Bytes transferred from Main Memory %" PRIu64 "\n", sim_stats->bytes_transferred_from_mem); printf("Bytes transferred to Main Memory %" PRIu64 "\n", sim_stats->bytes_transferred_to_mem); // Performance stats printf("L1 Data Hit Time %.8f\n", sim_stats->l1data_hit_time); printf("L1 Data Miss Penalty %.8f\n", sim_stats->l1data_miss_penalty); printf("L1 Data Miss Rate %.8f\n", sim_stats->l1data_miss_rate); printf("Victim Cache Miss Rate %.8f\n", sim_stats->victim_cache_miss_rate); printf("Average Access Time %.8f\n", sim_stats->avg_access_time); } // Helper to compare json token strings static int jsoneq(const char *json, jsmntok_t *tok, const char *s) { if (tok->type == JSMN_STRING && (int)strlen(s) == tok->end - tok->start && strncmp(json + tok->start, s, (size_t) (tok->end - tok->start)) == 0) { return 0; } return -1; } // Helper to parse a cache configuration -- does not check for error static void parse_cache(const char *buffer, jsmntok_t *t, int index, struct cache_config_t *cache) { char *ptr; if (jsoneq(buffer, &t[index], "C") == 0 && t[index + 1].type == JSMN_PRIMITIVE) { cache->c = (uint64_t) strtol(buffer + t[index + 1].start, &ptr, 10); index += 2; } if (jsoneq(buffer, &t[index], "B") == 0 && t[index + 1].type == JSMN_PRIMITIVE) { cache->b = (uint64_t) strtol(buffer + t[index + 1].start, &ptr, 10); index += 2; } if (jsoneq(buffer, &t[index], "S") == 0 && t[index + 1].type == JSMN_PRIMITIVE) { cache->s = (uint64_t) strtol(buffer + t[index + 1].start, &ptr, 10); } } // Helper for parsing a configuration file -- tries to check for basic errors // Don't trust it with a file that is not a valid JSON. static void parse_config(FILE *fin, struct sim_config_t *sim_conf) { jsmn_parser p; jsmntok_t t[128]; // Not expecting a really large input so this should work jsmn_init(&p); char buffer[1024]; // For reading configuration file contents // Read config file contents if (fin) { size_t len = fread(buffer, sizeof(char), 1024, fin); if (ferror(fin) != 0) { print_err_usage("Error reading input configuration file"); } buffer[len++] = '\0'; fclose(fin); } // Tokenize the JSON configuration file int r = jsmn_parse(&p, buffer, strlen(buffer), t, sizeof(t) / sizeof(t[0])); if (r < 0 || (r < 1 || t[0].type != JSMN_OBJECT) ) { print_err_usage("Could not parse the configuration file"); } for (int i = 1; i < r;) { if (jsoneq(buffer, &t[i], "L1 Instruction") == 0) { if (t[i + 1].type != JSMN_OBJECT) { print_err_usage("L1 Instruction Cache configuration error"); } // parse_cache(buffer, t, i + 2, &(sim_conf->l1inst)); i += 8; } else if (jsoneq(buffer, &t[i], "L1 Data") == 0) { if (t[i + 1].type != JSMN_OBJECT) { print_err_usage("L1 Data Cache configuration error"); } parse_cache(buffer, t, i + 2, &(sim_conf->l1data)); i += 8; } else if (jsoneq(buffer, &t[i], "L2 Unified") == 0) { if (t[i + 1].type != JSMN_OBJECT) { print_err_usage("L2 Unified Cache configuration error"); } // parse_cache(buffer, t, i + 2, &(sim_conf->l2unified)); i += 8; } else if (jsoneq(buffer, &t[i], "Replacement Policy") == 0) { if (t[i + 1].type != JSMN_STRING) { print_err_usage("Replacement Policy configuration error"); } else { if (strncmp("LRU", buffer + t[i + 1].start, 3) == 0) { sim_conf->rp = LRU; } else if (strncmp("LFU", buffer + t[i + 1].start, 3) == 0) { sim_conf->rp = LFU; } else if (strncmp("FIFO", buffer + t[i + 1].start, 4) == 0) { sim_conf->rp = FIFO; } else { sim_conf->rp = LRU; // Default is LRU } } i += 2; } else if (jsoneq(buffer, &t[i], "Victim Cache") == 0) { if (t[i + 1].type != JSMN_OBJECT) { print_err_usage("Victim Cache configuration error"); } else { if (strncmp(buffer + t[i + 2].start, "V", 1) == 0) { sim_conf->has_victim_cache = true; if (t[i + 3].type == JSMN_PRIMITIVE) { sim_conf->V = (uint64_t) strtol(buffer + t[i + 3].start, NULL, 10); i += 4; } else { sim_conf->V = 4; i++; } } else { sim_conf->has_victim_cache = false; i++; } } } else { i++; // just continue on incase something cannot be read } } } // Helper to verify that the input cache configuration is valid static void verify_config(const struct sim_config_t *sim_conf) { // Ensure L1 size is within bounds if (sim_conf->l1data.c < MIN_L1_C || sim_conf->l1data.c > MAX_L1_C) { print_error_exit("L1 Data cache cannot be smaller than 512B nor larger than 32KiB\n"); } // Check VC size if (sim_conf->V > MAX_VC_SIZE) { print_error_exit("VC bigger than %d blocks won't really be effective. Choose wisely", MAX_VC_SIZE); } } // This function does no error checking and uses magic numbers static void setup_hit_times(struct sim_stats_t *sim_stats, const struct sim_config_t *sim_conf) { // L1 Data if (sim_conf->l1data.s <= MAX_S) { sim_stats->l1data_hit_time = L1_ACCESS_TIME[sim_conf->l1data.s][(sim_conf->l1data.c - MIN_L1_C)]; } else { sim_stats->l1data_hit_time = L1_ACCESS_TIME[MAX_S+1][(sim_conf->l1data.c - MIN_L1_C)]; } // Setup the L1 miss penalty, i.e. time to access main memory sim_stats->l1data_miss_penalty = 60; } // Drive the cache simulator int main(int argc, char *const argv[]) { if (argc < 5) { print_err_usage("Input configuration file not provided"); } FILE *fin = stdin; // config file FILE *trace = NULL; // trace file struct sim_config_t sim_conf; memset(&sim_conf, 0, sizeof(sim_conf)); struct sim_stats_t sim_stats; memset(&sim_stats, 0, sizeof(sim_stats)); int opt; while (-1 != (opt = getopt(argc, argv, "c:C:i:I:h"))) { switch (opt) { case 'c': case 'C': fin = fopen(optarg, "r"); if (fin == NULL) { print_err_usage("Could not open input configuration file"); } parse_config(fin, &sim_conf); // read the json config file verify_config(&sim_conf); // verify that the configuration is legal setup_hit_times(&sim_stats, &sim_conf); // setup hit times from the hit times table break; case 'i': case 'I': trace = fopen(optarg, "r"); if (trace == NULL) { print_err_usage("Could not open the input trace file"); } break; case 'h': print_err_usage(""); break; default: print_err_usage("Invalid argument to program"); break; } } // Print sim configuration print_sim_config(&sim_conf); // setup the cache structures sim_init(&sim_conf); printf("SETUP COMPLETE - STARTING SIMULATION\n"); // Run the simulator -- one access at a time char type; uint64_t addr; while (!feof(trace)) { int ret = fscanf(trace, "%c %" PRIx64 "\n", &type, &addr); if (ret == 2) { cache_access(addr, type, &sim_stats, &sim_conf); } } fclose(trace); sim_cleanup(&sim_stats, &sim_conf); print_sim_output(&sim_stats); return 0; }
[ "noreply@github.com" ]
noreply@github.com
a0fac577f17a26f6815db79f3e3719d708f85792
48a5a1240fe963919e41ddbadbc0a6f0006d1f32
/Códigos/I_O_P1.ino
8044515456d481690bedd3996a8ae2121962a032
[]
no_license
itam-sdi-11561-spring-2019/practica-2-los-lupitos-y-diego
4b686a23d4d186839c7c47b76b893d5b8c73b5cf
6789f6f1283da58ab011bc8095fa3783be97fa93
refs/heads/master
2020-04-24T14:11:04.702120
2019-02-26T04:28:05
2019-02-26T04:28:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
347
ino
void setup() { // put your setup code here, to run once: DDRB = B00100000; } void loop() { // put your main code here, to run repeatedly: asm volatile( "cbi %0, %1 \n" \ "sbis %2, %3 \n" \ "sbi %0, %1 \n" \ : : "I" (_SFR_IO_ADDR(PORTB)), "I" (PORTB5), "I" (_SFR_IO_ADDR(PINB)), "I" (PINB5) : ); delay(300); }
[ "noreply@github.com" ]
noreply@github.com
56baff9d6911c506639ea019cfbf3a247e836599
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/Trigger/TrigHypothesis/TrigLongLivedParticlesHypo/src/TrigCaloRatioHypo.cxx
7eaac563567e21fe4158fbffb4f4dbcc855df1fb
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
8,268
cxx
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ // ************************************************************ // // NAME: TrigCaloRatioHypo.cxx // PACKAGE: Trigger/TrigHypothesis/TrigLongLivedParticlesHypo // // AUTHOR: Andrea Coccaro // EMAIL: Andrea.Coccaro AT cern.ch // // ************************************************************ #include "TrigLongLivedParticlesHypo/TrigCaloRatioHypo.h" #include "TrigSteeringEvent/PhiHelper.h" #include "xAODJet/JetContainer.h" #include "xAODJet/Jet.h" #include "xAODTracking/TrackParticleContainer.h" #include "CxxUtils/fpcompare.h" //** ----------------------------------------------------------------------------------------------------------------- **// TrigCaloRatioHypo::TrigCaloRatioHypo(const std::string& name, ISvcLocator* pSvcLocator): HLT::HypoAlgo(name, pSvcLocator) { declareProperty("EtCut", m_etCut = 30*CLHEP::GeV, "cut value forthe jet et"); declareProperty("LogRatioCut", m_logRatioCut = 1.2, "cut value for the jet energy ratio"); declareProperty("PtMinID", m_ptCut = 2000.0, "minimum track Pt in MeV for the isolation requirement"); declareProperty("TrackCut", m_trackCut = 0, "minimum number of tracks for the isolation requirement"); declareProperty("DeltaR", m_deltaR=0.2, "radius for the track isolation requirement"); declareProperty("EtaCut", m_etaCut = 2.5, "cut value for Eta of the Jet"); declareProperty("Reversed", m_reversedCut = false, "reversed cut for collimated photons"); declareProperty("DoTrackIso", m_doTrackIso = true, "switch on/off the track isolation requirement"); declareProperty("AcceptAll", m_acceptAll=false); declareMonitoredStdContainer("JetEt", m_jetEt); declareMonitoredStdContainer("JetEta", m_jetEta); declareMonitoredStdContainer("JetPhi", m_jetPhi); declareMonitoredVariable("CutCounter", m_cutCounter); declareMonitoredVariable("logRatio", m_logRatio); } //** ----------------------------------------------------------------------------------------------------------------- **// TrigCaloRatioHypo::~TrigCaloRatioHypo() {} //** ----------------------------------------------------------------------------------------------------------------- **// HLT::ErrorCode TrigCaloRatioHypo::hltInitialize() { msg() << MSG::INFO << "in initialize()" << endreq; m_accepted=0; m_rejected=0; m_errors=0; //* declareProperty overview *// if (msgLvl() <= MSG::DEBUG) { msg() << MSG::DEBUG << "declareProperty review:" << endreq; msg() << MSG::DEBUG << " EtCut = " << m_etCut << endreq; msg() << MSG::DEBUG << " LogRatioCut = " << m_logRatioCut << endreq; msg() << MSG::DEBUG << " PtMinID = " << m_ptCut << endreq; msg() << MSG::DEBUG << " TrackCut = " << m_trackCut << endreq; msg() << MSG::DEBUG << " DeltaR = " << m_deltaR << endreq; msg() << MSG::DEBUG << " EtaCut = " << m_etaCut << endreq; msg() << MSG::DEBUG << " Reversed = " << m_reversedCut << endreq; msg() << MSG::DEBUG << " DoTrackIso = " << m_doTrackIso << endreq; msg() << MSG::DEBUG << " AcceptAll = " << m_acceptAll << endreq; } return HLT::OK; } //** ----------------------------------------------------------------------------------------------------------------- **// HLT::ErrorCode TrigCaloRatioHypo::hltFinalize() { msg() << MSG::INFO << "in finalize()" << endreq; msg() << MSG::INFO << "Events accepted/rejected/errors: "<< m_accepted <<" / "<<m_rejected <<" / "<< m_errors << endreq; return HLT::OK; } //** ----------------------------------------------------------------------------------------------------------------- **// HLT::ErrorCode TrigCaloRatioHypo::hltExecute(const HLT::TriggerElement* outputTE, bool& pass) { m_cutCounter = -1; bool passCutJet = false; bool passCutTrk = true; //default to true, changes false if m_trackCut tracks are within m_deltaR of the jet axis pass=false; double jetRatio = -1.; m_logRatio = -1.; //clear monitoring vectors m_jetEt.clear(); m_jetPhi.clear(); m_jetEta.clear(); const xAOD::JetContainer* vectorOfJets = 0; HLT::ErrorCode status = getFeature(outputTE, vectorOfJets); m_cutCounter = 0; if (status != HLT::OK) { msg() << MSG::ERROR << "Failed to get the xAOD jet container" << endreq; m_errors++; return HLT::ERROR; } else if (msgLvl() <= MSG::DEBUG) msg() << MSG::DEBUG << "Got the xAOD jet container" << endreq; if (vectorOfJets->size() == 0) { if (msgLvl() <= MSG::DEBUG) msg() << MSG::DEBUG << "The xAOD jet container is empty" << endreq; m_errors++; return HLT::OK; } else if (vectorOfJets->size() != 1) { msg() << MSG::ERROR << "More than one xAOD jet, not expected!" << endreq; m_errors++; return HLT::ERROR; } else { if (msgLvl() <= MSG::DEBUG) msg() << MSG::DEBUG << vectorOfJets->size() << " jet is found" << endreq; } const xAOD::Jet *jet = vectorOfJets->front(); double jetEta = jet->eta(); double jetPhi = jet->phi(); double jetEt = jet->p4().Et(); double jetEMF = jet->getAttribute<float>("EMFrac"); double zero = 0.; double one = 1.; if (CxxUtils::fpcompare::greater(jetEMF,zero)){ if(CxxUtils::fpcompare::greater_equal(jetEMF,one)) jetRatio = -999.; else jetRatio = log10(double(1./jetEMF - 1.)); } else { jetRatio = 999; } if(msgLvl() <= MSG::DEBUG) msg() << MSG::DEBUG << " jet with et=" << jetEt << ", eta=" << jetEta << ", phi=" << jetPhi << ", log-ratio=" << jetRatio << endreq; if(!m_reversedCut) { if (jetEt > m_etCut && std::fabs(jetEta) <= m_etaCut) { m_jetEt.push_back(jetEt/CLHEP::GeV); m_jetEta.push_back(jetEta); m_jetPhi.push_back(jetPhi); m_logRatio = jetRatio; passCutJet = true; } } else { if (jetEt > m_etCut && std::fabs(jetEta) <= m_etaCut && jetRatio <= m_logRatioCut) { m_jetEt.push_back(jetEt/CLHEP::GeV); m_jetEta.push_back(jetEta); m_jetPhi.push_back(jetPhi); m_logRatio = jetRatio; passCutJet = true; } } if(m_doTrackIso) { bool countTracks=0; const xAOD::TrackParticleContainer* vectorOfTracks; status = getFeature(outputTE, vectorOfTracks, "InDetTrigTrackingxAODCnv_Tau_IDTrig"); if(status != HLT::OK) { msg() << MSG::ERROR << "Failed to get the xAOD track container" << endreq; m_errors++; return HLT::ERROR; } else if (msgLvl() <= MSG::DEBUG) msg() << MSG::DEBUG << "Got the xAOD track container" << endreq; if(vectorOfTracks->size() == 0) { if (msgLvl() <= MSG::DEBUG) msg() << MSG::DEBUG << "The xAOD track container is empty" << endreq; passCutTrk = true; //default is true, but just for clarity } else { if (msgLvl() <= MSG::DEBUG) msg() << MSG::DEBUG << vectorOfTracks->size() << " tracks are found" << endreq; xAOD::TrackParticleContainer::const_iterator track = vectorOfTracks->begin(), lasttrack = vectorOfTracks->end(); for(; track !=lasttrack; track++ ) { float theta = (*track)->theta(); float qOverPt = (*track)->qOverP()/TMath::Sin(theta); float pT = (1/qOverPt); if (fabs(pT) <= m_ptCut) continue; double phi = (*track)->phi0(); double eta = (*track)->eta(); if(msgLvl() <= MSG::DEBUG) msg() << MSG::DEBUG << " track with " << "pt=" << pT << ", eta=" << eta << ", phi=" << phi << endreq; double deta = fabs(eta-jetEta); double dphi = fabs(HLT::wrapPhi(phi-jetPhi)); double dR = sqrt((deta*deta)+(dphi*dphi)); if (dR<m_deltaR) { countTracks++; } } } if(countTracks>m_trackCut){ passCutTrk = false; } else{ if(msgLvl() <= MSG::DEBUG) msg() << MSG::DEBUG << "Jet passed tracking isolation" << endreq; } } if((passCutJet&&passCutTrk) || m_acceptAll) { pass = true; m_cutCounter = 1; if(msgLvl() <= MSG::DEBUG) msg() << MSG::DEBUG << "Jet passing calo-ratio requirements" << endreq; } else { if(msgLvl() <= MSG::DEBUG) msg() << MSG::DEBUG << "Jet not passing calo-ratio requirements" << endreq; } return HLT::OK; }
[ "rushioda@lxplus754.cern.ch" ]
rushioda@lxplus754.cern.ch
9a9da6752eae7cbfecb4b081364943720ec6cc55
867748c43510579840e061f2fa23ce46f6d7c87c
/code/timer/heaptimer.hh
2fa032ba43f403eee3dfa6eebcce4f3e67ad5849
[]
no_license
IceCream-jy/HTTPWebServer
22c45689deab9b2517e0bae345ef6df3f8517cdb
9b845b0958b3ade170f20ea6d729ad45c1d1a2ef
refs/heads/main
2023-05-29T09:39:19.996463
2021-06-04T01:27:28
2021-06-04T01:27:28
346,352,459
0
0
null
null
null
null
UTF-8
C++
false
false
1,416
hh
#ifndef _HEAP_TIMER_H_ #define _HEAP_TIMER_H_ #include <queue> #include <unordered_map> #include <time.h> #include <algorithm> #include <arpa/inet.h> #include <functional> #include <assert.h> #include <chrono> #include "../log/log.hh" typedef std::function<void()> TimeoutCallBack; typedef std::chrono::high_resolution_clock Clock; typedef std::chrono::milliseconds MS; typedef Clock::time_point TimeStamp; struct TimerNode { int id; TimeStamp expires; TimeoutCallBack cb; bool operator<(const TimerNode& t) { return expires < t.expires; } }; class HeapTimer { public: HeapTimer() { heap_.reserve(64); } ~HeapTimer() { clear(); } // 调整指定 id 的结点,expires = now() + newExpires void adjust(int id, int newExpires); void add(int id, int timeOut, const TimeoutCallBack& cb); // 删除指定 id 节点,并触发回调函数 void doWork(int id); void clear(); // 清除超时节点 void tick(); void pop(); // tick,并返回下一节点 expire 的时间距离 int GetNextTick(); private: // 删除指定位置节点 void del_(size_t i); // 对第 i 个节点执行 sift_up void siftup_(size_t i); bool siftdown_(size_t index, size_t n); void SwapNode_(size_t i, size_t j); std::vector<TimerNode> heap_; // 保存 id 的个数 std::unordered_map<int, size_t> ref_; }; #endif
[ "304754843@qq.com" ]
304754843@qq.com
8f36ef220d6677d3ccd35f04037c55d3d75ccb84
7f867a8769ee44363ea5b7d2b71be6f8e54474b0
/Crawler/LinkRepository/LinkStatus.hpp
a20f71b27453378ee047400a202918de637a5865
[]
no_license
zakariannn/searchengine
ce3b5d50eddcf8634f4388b4668b1f15f4d89b2b
e2a59015d0f817220b8b89c6d30a0832e4973a66
refs/heads/main
2023-05-01T14:52:05.316941
2021-05-26T09:10:43
2021-05-26T09:10:43
341,845,666
0
0
null
null
null
null
UTF-8
C++
false
false
123
hpp
#ifndef LINK_STATUS #define LINK_STATUS enum class LinkStatus { WAITING = 0, SUCCESS = 1, ERROR = 2 }; #endif
[ "marina.zakaryan.5@gmail.com" ]
marina.zakaryan.5@gmail.com
9240ecb5fee333367ec0475b54060f3933b10d67
9cb84563351e742501af429dbb17198dd7aaa345
/huobi_futures/linear_swap/restful/response/account/GetAccountInfoResponse.hpp
85cd200dfa2b1e2e8c7ac2690ed4b1ee78bb5510
[]
no_license
hbdmapi/huobi_futures_Cpp
c22ebeaac4ae32d371e4ef3ce925dceefc28b605
66e59178c20b58c28ebf3c06c0f0f9b209da9c69
refs/heads/master
2023-04-19T05:07:15.712360
2021-05-06T03:36:22
2021-05-06T03:36:22
324,038,739
3
2
null
null
null
null
UTF-8
C++
false
false
3,011
hpp
#pragma once #include <string> using std::string; #include "huobi_futures/json_struct/json_struct.h" #include <vector> #include <optional> namespace huobi_futures { namespace linear_swap { namespace restful { namespace response_account { struct GetAccountInfoResponse { string status; std::optional<int32_t> err_code; std::optional<string> err_msg; struct Data { std::optional<string> symbol; std::optional<string> contract_code; string margin_asset; float margin_balance; float margin_static; float margin_position; float margin_frozen; std::optional<float> margin_available; float profit_real; float profit_unreal; float withdraw_available; JS::Nullable<float> risk_rate; std::optional<JS::Nullable<float>>liquidation_price; std::optional<float> lever_rate; std::optional<float> adjust_factor; string margin_mode; string margin_account; struct ContractDetail { string symbol; string contract_code; float margin_position; float margin_frozen; float margin_available; float profit_unreal; JS::Nullable<float> liquidation_price; int32_t lever_rate; float adjust_factor; JS_OBJ(symbol, contract_code, margin_position, margin_frozen, margin_available, profit_unreal, liquidation_price, lever_rate, adjust_factor); }; std::optional<std::vector<ContractDetail>> contract_detail; JS_OBJ(symbol, contract_code, margin_asset, margin_balance, margin_static, margin_position, margin_frozen, margin_available, profit_real, profit_unreal, withdraw_available, risk_rate, liquidation_price, lever_rate, adjust_factor, margin_mode, margin_account, contract_detail); }; std::optional<std::vector<Data>> data; int64_t ts; JS_OBJ(status, err_code, err_msg, data, ts); }; } // namespace response_account } // namespace restful } // namespace linear_swap } // namespace huobi_futures
[ "3140618@163.com" ]
3140618@163.com
d5d0950fd6bceb0582698180937d14ee2acdabb2
ad2e78e30d89780412546cbd9ca7e63bf317899b
/Semester 2/Exercise2/Exercise2/Polynomial.cpp
bdd56fd265ff70d61477186fa389f7c95d7854d1
[]
no_license
RocketSkates/SchoolNew
a6eb619b3fef221c9c92c599250f9d5ee8f4ad4f
a695cdafcaa69ede2092980ee47cdcb5fd5e68b4
refs/heads/master
2020-05-27T23:05:02.409991
2017-11-01T12:48:22
2017-11-01T12:48:22
82,576,659
0
0
null
null
null
null
UTF-8
C++
false
false
1,559
cpp
#include "Polynomial.h" Polynomial::Polynomial() :numMonoms(0) { for (int i = 0; i < MAX_Monoms; i++) poly[i] = NULL; } Polynomial::~Polynomial() { for (int i = 0; i < MAX_Monoms; i++) delete poly[i]; } Polynomial::Polynomial(const Polynomial & poly1) { numMonoms = poly1.GetNum(); for (int i = 0; i < numMonoms; i++) poly[i] = poly1.poly[i]; } Polynomial& Polynomial::operator= (const Polynomial& p) { numMonoms = p.GetNum(); for (int i = 0; i < numMonoms; i++) poly[i] = p.poly[i]; } Polynomial& Polynomial::operator >> (const char* str) { //TODO Polynomial p1; char* temp; } Polynomial& Polynomial::operator+= (const Polynomial& p) { for (int i = 0; i < numMonoms; i++){ for (int j = 0; j < p.numMonoms; j++){ if (poly[i]->GetExp() == p.poly[j]->GetExp()) { poly[i]->SetCoeff(poly[i]->GetCoeff() + p.poly[j]->GetCoeff()); } } } } Polynomial& Polynomial::operator+= (const Monomial& m) { for (int i = 0; i < numMonoms; i++) { if (poly[i]->GetExp == m.GetExp()) { poly[i]->SetCoeff(poly[i]->GetCoeff() + m.GetCoeff()); } } } Polynomial& Polynomial::operator-= (const Polynomial& p) { for (int i = 0; i < numMonoms; i++) { for (int j = 0; j < p.numMonoms; j++) { if (poly[i]->GetExp() == p.poly[j]->GetExp()) { poly[i]->SetCoeff(poly[i]->GetCoeff() - p.poly[j]->GetCoeff()); } } } } Polynomial& Polynomial::operator-= (const Monomial& m) { for (int i = 0; i < numMonoms; i++) { if (poly[i]->GetExp == m.GetExp()) { poly[i]->SetCoeff(poly[i]->GetCoeff() - m.GetCoeff()); } } }
[ "sigal.gurman@gmail.com" ]
sigal.gurman@gmail.com
3172404bf8524300b46692f07c4fa497b06dc6f6
bc9ab0fa7a51d03e194d2ab573f9bfdb00f0267c
/OpenGL/src/GameObject/GameObjectManager.cpp
6bf8cec0591a40da86bde0e3b0c677404cf31d9a
[]
no_license
shashagit/BocksEngine
24a92a90ee01e2aa1f06a72fd2ce9c865035a2a5
e0efcea6788b14af01c2040e871303fec86661e6
refs/heads/master
2022-04-08T15:30:24.676470
2019-11-18T17:24:20
2019-11-18T17:24:20
211,177,732
1
0
null
null
null
null
UTF-8
C++
false
false
2,521
cpp
/* Start Header ------------------------------------------------------- Copyright (C) 20xx DigiPen Institute of Technology. Reproduction or disclosure of this file or its contents without the prior written consent of DigiPen Institute of Technology is prohibited. File Name: <put file name here> Purpose: <explain the contents of this file> Language: <specify language and compiler> Platform: <specify compiler version, hardware requirements, operating systems> Project: <specify student login, class, and assignment. For example: if foo.boo is in class CS 529 and this file is a part of assignment 2, then write: CS529_fooboo_2> Author: <provide your name, student login, and student id> Creation date: <date on which you created this file> - End Header --------------------------------------------------------*/ #include "GameObjectManager.h" #include "GameObject.h" #include "ObjectFactory.h" #include "../Components/Transform.h" #include "../Components/Component.h" #include "../Components/Mesh.h" #include "../Components/Body.h" #include "../Components/Collider.h" #include "../Components/DebugVector.h" #include "../Components/Shape.h" #include <cstdlib> #include <ctime> extern ObjectFactory* gpObjectFactory; GameObjectManager::GameObjectManager() { // creating map of components componentMap[TRANSFORM] = new Transform(); componentMap[BODY] = new Body(); componentMap[MESH] = new Mesh(); componentMap[COLLIDER] = new Collider(); componentMap[DEBUGVEC] = new DebugVector(); // setting Color array Colors[Color::Red] = glm::vec4(1.0f, 0.0f, 0.0f, 1.0f); Colors[Color::Green] = glm::vec4(0.0f, 1.0f, 0.0f, 1.0f); Colors[Color::Blue] = glm::vec4(0.0f, 0.0f, 1.0f, 1.0f); Colors[Color::White] = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f); } GameObjectManager::~GameObjectManager() { for(auto go: mGameObjects) { delete go; } } void GameObjectManager::DeleteGameObject(GameObject* go) { std::vector<GameObject*>::iterator position = std::find(mGameObjects.begin(), mGameObjects.end(), go); if (position != mGameObjects.end()) { mGameObjects.erase(position); } } void GameObjectManager::Update() { for (auto go : mGameObjects) go->Update(); } Transform* GameObjectManager::CreateDebugObject() { GameObject* go = new GameObject(); Transform* pTr = static_cast<Transform*>(go->AddComponent(TRANSFORM)); pTr->mScale = glm::vec3(0.1f, 0.1f, 0.1f); pTr->Update(); mDebugObjects.push_back(go); return pTr; }
[ "devshashwatpandey@gmail.com" ]
devshashwatpandey@gmail.com
2bef4cd6c8d18652def114b1396c69e869ae9f0c
e9f54dc20a1a1f52ed846d0f108824f0886d97fc
/aeda1920_fp09/Tests/jogador.h
b9a7317b4fc3e3d7b6bb0715f52a4e5bb32ca0f4
[]
no_license
marianaramos37/AEDA_feup
68dbd5fa3738e5257727a4e3cad1dca53ae57a1a
2324c50751a5a4820cf35a43cd1203edfb352319
refs/heads/main
2022-12-27T20:31:04.043433
2020-10-07T18:07:28
2020-10-07T18:07:28
302,119,480
0
0
null
null
null
null
UTF-8
C++
false
false
898
h
#ifndef JOGADOR_H_ #define JOGADOR_H_ #include "aposta.h" #include <string> using namespace std; //a alterar struct apostaHash { int operator() (const Aposta & ap) const { return ap.getNumeros().size(); } bool operator() (const Aposta & ap1, const Aposta & ap2) const { tabHInt::const_iterator it; for (it=ap1.getNumeros().begin(); it!=ap1.getNumeros().end(); it++) if (!ap2.contem(*it)) return false; return true; } }; typedef unordered_set<Aposta, apostaHash, apostaHash> tabHAposta; class Jogador { tabHAposta apostas; string nome; public: Jogador(string nm="anonimo") { nome=nm; } void adicionaAposta(const Aposta & ap); unsigned apostasNoNumero(unsigned num) const; tabHAposta apostasPremiadas(const tabHInt & sorteio) const; unsigned getNumApostas() const { return apostas.size(); } }; #endif /*JOGADOR1_H_*/
[ "7marianaramos@gmail.com" ]
7marianaramos@gmail.com
3dc40cad43e270129dc12419ea86261e9a100529
a575bb4ba5b842dcc4b00148a3fb17ef575a0fc3
/urm.h
811ec2401629baa76b2929a57451714e6db98971
[]
no_license
Jakjm/URM
8f1d1682e788fd5f6a240dba7b0390adae5a0da0
a15449ac58e0f3a2a58a50d95053247ca9b16ccd
refs/heads/master
2022-07-14T13:25:57.248071
2020-05-14T07:05:12
2020-05-14T07:05:12
260,367,935
2
0
null
null
null
null
UTF-8
C++
false
false
309
h
#include <vector> #include <map> using namespace std; class V_Instruction; class URM{ public: vector<int> *variables; vector<V_Instruction*> *instructions; map<string,int> varMap; int programCounter; URM(vector <V_Instruction*> *instructions,vector <int> *vars,map <string,int> varMap); void run(); };
[ "jakj3m@gmail.com" ]
jakj3m@gmail.com
b398a470cf7d3de9bf06450b6af28f6ee05a3e2e
5fed51550227689ab197910b1b3a3b55fdcdec85
/include/bakkesmod/wrappers/GameObject/RumbleComponent/VelcroPickup.h
42c0fef505edf15953c63d0dcf317ffaa6e05803
[ "MIT" ]
permissive
GodGamer029/SuperSonicML
6f57dc58804d9189706540b4a7b4d281dde6e501
2b0a446d6f206dd365661806ab29f8672c9b7adb
refs/heads/master
2022-12-23T04:05:22.158352
2020-10-03T15:36:22
2020-10-03T15:36:22
262,556,810
8
2
null
null
null
null
UTF-8
C++
false
false
1,764
h
#pragma once template<class T> class ArrayWrapper; template<typename T> class StructArrayWrapper; #include "../../WrapperStructs.h" #include "../.././GameObject/RumbleComponent/RumblePickupComponentWrapper.h" class BallWrapper; class CarWrapper; class RBActorWrapper; class BAKKESMOD_PLUGIN_IMPORT VelcroPickup : public RumblePickupComponentWrapper { public: CONSTRUCTORS(VelcroPickup) //AUTO-GENERATED FROM FIELDS Vector GetBallOffset(); void SetBallOffset(Vector newBallOffset); unsigned long GetbUseRealOffset(); void SetbUseRealOffset(unsigned long newbUseRealOffset); unsigned long GetbHit(); void SetbHit(unsigned long newbHit); unsigned long GetbBroken(); void SetbBroken(unsigned long newbBroken); float GetAfterHitDuration(); void SetAfterHitDuration(float newAfterHitDuration); float GetPostBreakDuration(); void SetPostBreakDuration(float newPostBreakDuration); float GetMinBreakForce(); void SetMinBreakForce(float newMinBreakForce); float GetMinBreakTime(); void SetMinBreakTime(float newMinBreakTime); float GetCheckLastTouchRate(); void SetCheckLastTouchRate(float newCheckLastTouchRate); BallWrapper GetWeldedBall(); void SetWeldedBall(BallWrapper newWeldedBall); float GetOldBallMass(); void SetOldBallMass(float newOldBallMass); float GetAttachTime(); void SetAttachTime(float newAttachTime); float GetLastTouchCheckTime(); void SetLastTouchCheckTime(float newLastTouchCheckTime); float GetBreakTime(); void SetBreakTime(float newBreakTime); //AUTO-GENERATED FUNCTION PROXIES void DoBreak(); void HandleCarTouch(BallWrapper InBall, CarWrapper InCar, unsigned char HitType); void PickupEnd(); void OnBallHit(); void HandleHitBall(CarWrapper InCar, BallWrapper InBall); void PickupStart(); private: PIMPL };
[ "godgamer029@gmail.com" ]
godgamer029@gmail.com
63c3fe43baece3a463802ced384d03ecfbbb57c3
97e9f7e62763e88b6b3af7d0441d916232cabc0e
/poly3.cpp
3e79f097f35c02c61c4082ac027aea06cf6e3858
[]
no_license
prabhhav/cpluspluscpp
afddb1d2fc8b025cd8f85c4947ef7a32f9732dee
3d6e524185e4d5481111c88495737f590c6f62a8
refs/heads/master
2020-12-30T04:06:46.431122
2020-06-01T11:38:13
2020-06-01T11:38:13
238,854,791
0
0
null
null
null
null
UTF-8
C++
false
false
359
cpp
#include <iostream> using namespace std; class Animal { // base class declaration. public: string color = "Black"; }; class Dog: public Animal // inheriting Animal class. { public: string color = "Grey"; }; int main(void) { Animal d= Dog(); cout<<d.color; }
[ "noreply@github.com" ]
noreply@github.com
73972699c56d2996edcb53afc79f9b628fd2c97a
58f46a28fc1b58f9cd4904c591b415c29ab2842f
/chromium-courgette-redacted-29.0.1547.57/chrome/browser/chromeos/login/user_manager_impl.cc
049b604c503c0e56a240067958467344718f0767
[ "BSD-3-Clause" ]
permissive
bbmjja8123/chromium-1
e739ef69d176c636d461e44d54ec66d11ed48f96
2a46d8855c48acd51dafc475be7a56420a716477
refs/heads/master
2021-01-16T17:50:45.184775
2015-03-20T18:38:11
2015-03-20T18:42:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
66,458
cc
// Copyright (c) 2013 The Chromium 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 "chrome/browser/chromeos/login/user_manager_impl.h" #include <cstddef> #include <set> #include "ash/shell.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/chromeos/chromeos_version.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/prefs/pref_registry_simple.h" #include "base/prefs/pref_service.h" #include "base/rand_util.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/app_mode/app_mode_utils.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/cros/cert_library.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/login/default_pinned_apps_field_trial.h" #include "chrome/browser/chromeos/login/login_display.h" #include "chrome/browser/chromeos/login/login_utils.h" #include "chrome/browser/chromeos/login/remove_user_delegate.h" #include "chrome/browser/chromeos/login/user_image_manager_impl.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/chromeos/policy/device_local_account.h" #include "chrome/browser/chromeos/session_length_limiter.h" #include "chrome/browser/chromeos/settings/cros_settings_names.h" #include "chrome/browser/managed_mode/managed_user_service.h" #include "chrome/browser/policy/browser_policy_connector.h" #include "chrome/browser/prefs/scoped_user_pref_update.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chromeos/chromeos_switches.h" #include "chromeos/cryptohome/async_method_caller.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/ime/input_method_manager.h" #include "chromeos/login/login_state.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "google_apis/gaia/gaia_auth_util.h" #include "google_apis/gaia/google_service_auth_error.h" #include "policy/policy_constants.h" #include "ui/views/corewm/corewm_switches.h" using content::BrowserThread; namespace chromeos { namespace { // A vector pref of the the regular users known on this device, arranged in LRU // order. const char kRegularUsers[] = "LoggedInUsers"; // A vector pref of the public accounts defined on this device. const char kPublicAccounts[] = "PublicAccounts"; // A map from locally managed user id to manager user id. const char kManagedUserManagers[] = "ManagedUserManagers"; // A map from locally managed user id to manager display name. const char kManagedUserManagerNames[] = "ManagedUserManagerNames"; // A map from locally managed user id to manager display e-mail. const char kManagedUserManagerDisplayEmails[] = "ManagedUserManagerDisplayEmails"; // A vector pref of the locally managed accounts defined on this device, that // had not logged in yet. const char kLocallyManagedUsersFirstRun[] = "LocallyManagedUsersFirstRun"; // A pref of the next id for locally managed users generation. const char kLocallyManagedUsersNextId[] = "LocallyManagedUsersNextId"; // A pref of the next id for locally managed users generation. const char kLocallyManagedUserCreationTransactionDisplayName[] = "LocallyManagedUserCreationTransactionDisplayName"; // A pref of the next id for locally managed users generation. const char kLocallyManagedUserCreationTransactionUserId[] = "LocallyManagedUserCreationTransactionUserId"; // A string pref that gets set when a public account is removed but a user is // currently logged into that account, requiring the account's data to be // removed after logout. const char kPublicAccountPendingDataRemoval[] = "PublicAccountPendingDataRemoval"; // A dictionary that maps usernames to the displayed name. const char kUserDisplayName[] = "UserDisplayName"; // A dictionary that maps usernames to the displayed (non-canonical) emails. const char kUserDisplayEmail[] = "UserDisplayEmail"; // A dictionary that maps usernames to OAuth token presence flag. const char kUserOAuthTokenStatus[] = "OAuthTokenStatus"; // Callback that is called after user removal is complete. void OnRemoveUserComplete(const std::string& user_email, bool success, cryptohome::MountError return_code) { // Log the error, but there's not much we can do. if (!success) { LOG(ERROR) << "Removal of cryptohome for " << user_email << " failed, return code: " << return_code; } } // This method is used to implement UserManager::RemoveUser. void RemoveUserInternal(const std::string& user_email, chromeos::RemoveUserDelegate* delegate) { CrosSettings* cros_settings = CrosSettings::Get(); // Ensure the value of owner email has been fetched. if (CrosSettingsProvider::TRUSTED != cros_settings->PrepareTrustedValues( base::Bind(&RemoveUserInternal, user_email, delegate))) { // Value of owner email is not fetched yet. RemoveUserInternal will be // called again after fetch completion. return; } std::string owner; cros_settings->GetString(kDeviceOwner, &owner); if (user_email == owner) { // Owner is not allowed to be removed from the device. return; } if (delegate) delegate->OnBeforeUserRemoved(user_email); chromeos::UserManager::Get()->RemoveUserFromList(user_email); cryptohome::AsyncMethodCaller::GetInstance()->AsyncRemove( user_email, base::Bind(&OnRemoveUserComplete, user_email)); if (delegate) delegate->OnUserRemoved(user_email); } // Helper function that copies users from |users_list| to |users_vector| and // |users_set|. Duplicates and users already present in |existing_users| are // skipped. void ParseUserList(const ListValue& users_list, const std::set<std::string>& existing_users, std::vector<std::string>* users_vector, std::set<std::string>* users_set) { users_vector->clear(); users_set->clear(); for (size_t i = 0; i < users_list.GetSize(); ++i) { std::string email; if (!users_list.GetString(i, &email) || email.empty()) { LOG(ERROR) << "Corrupt entry in user list at index " << i << "."; continue; } if (existing_users.find(email) != existing_users.end() || !users_set->insert(email).second) { LOG(ERROR) << "Duplicate user: " << email; continue; } users_vector->push_back(email); } } } // namespace // static void UserManager::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterListPref(kRegularUsers); registry->RegisterListPref(kPublicAccounts); registry->RegisterListPref(kLocallyManagedUsersFirstRun); registry->RegisterIntegerPref(kLocallyManagedUsersNextId, 0); registry->RegisterStringPref(kPublicAccountPendingDataRemoval, ""); registry->RegisterStringPref( kLocallyManagedUserCreationTransactionDisplayName, ""); registry->RegisterStringPref( kLocallyManagedUserCreationTransactionUserId, ""); registry->RegisterDictionaryPref(kUserOAuthTokenStatus); registry->RegisterDictionaryPref(kUserDisplayName); registry->RegisterDictionaryPref(kUserDisplayEmail); registry->RegisterDictionaryPref(kManagedUserManagers); registry->RegisterDictionaryPref(kManagedUserManagerNames); registry->RegisterDictionaryPref(kManagedUserManagerDisplayEmails); SessionLengthLimiter::RegisterPrefs(registry); } UserManagerImpl::UserManagerImpl() : cros_settings_(CrosSettings::Get()), device_local_account_policy_service_(NULL), users_loaded_(false), active_user_(NULL), session_started_(false), user_sessions_restored_(false), is_current_user_owner_(false), is_current_user_new_(false), is_current_user_ephemeral_regular_user_(false), ephemeral_users_enabled_(false), locally_managed_users_enabled_by_policy_(false), merge_session_state_(MERGE_STATUS_NOT_STARTED), observed_sync_service_(NULL), user_image_manager_(new UserImageManagerImpl) { // UserManager instance should be used only on UI thread. DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); registrar_.Add(this, chrome::NOTIFICATION_OWNERSHIP_STATUS_CHANGED, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED, content::NotificationService::AllSources()); RetrieveTrustedDevicePolicies(); cros_settings_->AddSettingsObserver(kAccountsPrefDeviceLocalAccounts, this); cros_settings_->AddSettingsObserver(kAccountsPrefSupervisedUsersEnabled, this); UpdateLoginState(); } UserManagerImpl::~UserManagerImpl() { // Can't use STLDeleteElements because of the private destructor of User. for (UserList::iterator it = users_.begin(); it != users_.end(); it = users_.erase(it)) { if (active_user_ == *it) active_user_ = NULL; delete *it; } // These are pointers to the same User instances that were in users_ list. logged_in_users_.clear(); lru_logged_in_users_.clear(); delete active_user_; } void UserManagerImpl::Shutdown() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); cros_settings_->RemoveSettingsObserver(kAccountsPrefDeviceLocalAccounts, this); cros_settings_->RemoveSettingsObserver( kAccountsPrefSupervisedUsersEnabled, this); // Stop the session length limiter. session_length_limiter_.reset(); if (device_local_account_policy_service_) device_local_account_policy_service_->RemoveObserver(this); if (observed_sync_service_) observed_sync_service_->RemoveObserver(this); } UserImageManager* UserManagerImpl::GetUserImageManager() { return user_image_manager_.get(); } const UserList& UserManagerImpl::GetUsers() const { const_cast<UserManagerImpl*>(this)->EnsureUsersLoaded(); return users_; } UserList UserManagerImpl::GetUsersAdmittedForMultiProfile() const { UserList result; const UserList& users = GetUsers(); for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) { if ((*it)->GetType() == User::USER_TYPE_REGULAR && !(*it)->is_logged_in()) result.push_back(*it); } return result; } const UserList& UserManagerImpl::GetLoggedInUsers() const { return logged_in_users_; } const UserList& UserManagerImpl::GetLRULoggedInUsers() { // If there is no user logged in, we return the active user as the only one. if (lru_logged_in_users_.empty() && active_user_) { temp_single_logged_in_users_.clear(); temp_single_logged_in_users_.insert(temp_single_logged_in_users_.begin(), active_user_); return temp_single_logged_in_users_; } return lru_logged_in_users_; } void UserManagerImpl::UserLoggedIn(const std::string& email, const std::string& username_hash, bool browser_restart) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!CommandLine::ForCurrentProcess()->HasSwitch(::switches::kMultiProfiles)) DCHECK(!IsUserLoggedIn()); if (active_user_) active_user_->set_is_active(false); if (email == UserManager::kGuestUserName) { GuestUserLoggedIn(); } else if (email == UserManager::kRetailModeUserName) { RetailModeUserLoggedIn(); } else if (policy::IsKioskAppUser(email)) { KioskAppLoggedIn(email); } else { EnsureUsersLoaded(); User* user = FindUserInListAndModify(email); if (user && user->GetType() == User::USER_TYPE_PUBLIC_ACCOUNT) { PublicAccountUserLoggedIn(user); } else if ((user && user->GetType() == User::USER_TYPE_LOCALLY_MANAGED) || (!user && gaia::ExtractDomainName(email) == UserManager::kLocallyManagedUserDomain)) { LocallyManagedUserLoggedIn(email); } else if (browser_restart && email == g_browser_process->local_state()-> GetString(kPublicAccountPendingDataRemoval)) { PublicAccountUserLoggedIn(User::CreatePublicAccountUser(email)); } else if (email != owner_email_ && !user && (AreEphemeralUsersEnabled() || browser_restart)) { RegularUserLoggedInAsEphemeral(email); } else { RegularUserLoggedIn(email, browser_restart); } // Initialize the session length limiter and start it only if // session limit is defined by the policy. session_length_limiter_.reset(new SessionLengthLimiter(NULL, browser_restart)); } DCHECK(active_user_); active_user_->set_is_logged_in(true); active_user_->set_is_active(true); active_user_->set_username_hash(username_hash); // Place user who just signed in to the top of the logged in users. logged_in_users_.insert(logged_in_users_.begin(), active_user_); SetLRUUser(active_user_); NotifyOnLogin(); } void UserManagerImpl::SwitchActiveUser(const std::string& email) { if (!CommandLine::ForCurrentProcess()->HasSwitch(::switches::kMultiProfiles)) return; User* user = FindUserAndModify(email); if (!user) { NOTREACHED() << "Switching to a non-existing user"; return; } if (user == active_user_) { NOTREACHED() << "Switching to a user who is already active"; return; } if (!user->is_logged_in()) { NOTREACHED() << "Switching to a user that is not logged in"; return; } if (user->GetType() != User::USER_TYPE_REGULAR) { NOTREACHED() << "Switching to a non-regular user"; return; } if (user->username_hash().empty()) { NOTREACHED() << "Switching to a user that doesn't have username_hash set"; return; } DCHECK(active_user_); active_user_->set_is_active(false); user->set_is_active(true); active_user_ = user; // Move the user to the front. SetLRUUser(active_user_); NotifyActiveUserHashChanged(active_user_->username_hash()); NotifyActiveUserChanged(active_user_); } void UserManagerImpl::RestoreActiveSessions() { DBusThreadManager::Get()->GetSessionManagerClient()->RetrieveActiveSessions( base::Bind(&UserManagerImpl::OnRestoreActiveSessions, base::Unretained(this))); } void UserManagerImpl::SessionStarted() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); session_started_ = true; UpdateLoginState(); content::NotificationService::current()->Notify( chrome::NOTIFICATION_SESSION_STARTED, content::Source<UserManager>(this), content::Details<const User>(active_user_)); if (is_current_user_new_) { // Make sure that the new user's data is persisted to Local State. g_browser_process->local_state()->CommitPendingWrite(); } } std::string UserManagerImpl::GenerateUniqueLocallyManagedUserId() { int counter = g_browser_process->local_state()-> GetInteger(kLocallyManagedUsersNextId); std::string id; bool user_exists; do { id = base::StringPrintf("%d@%s", counter, kLocallyManagedUserDomain); counter++; user_exists = (NULL != FindUser(id)); DCHECK(!user_exists); if (user_exists) { LOG(ERROR) << "Locally managed user with id " << id << " already exists."; } } while (user_exists); g_browser_process->local_state()-> SetInteger(kLocallyManagedUsersNextId, counter); g_browser_process->local_state()->CommitPendingWrite(); return id; } const User* UserManagerImpl::CreateLocallyManagedUserRecord( const std::string& manager_id, const std::string& e_mail, const string16& display_name) { const User* user = FindLocallyManagedUser(display_name); DCHECK(!user); if (user) return user; PrefService* local_state = g_browser_process->local_state(); User* new_user = User::CreateLocallyManagedUser(e_mail); ListPrefUpdate prefs_users_update(local_state, kRegularUsers); prefs_users_update->Insert(0, new base::StringValue(e_mail)); ListPrefUpdate prefs_new_users_update(local_state, kLocallyManagedUsersFirstRun); prefs_new_users_update->Insert(0, new base::StringValue(e_mail)); users_.insert(users_.begin(), new_user); const User* manager = FindUser(manager_id); CHECK(manager); DictionaryPrefUpdate manager_update(local_state, kManagedUserManagers); DictionaryPrefUpdate manager_name_update(local_state, kManagedUserManagerNames); DictionaryPrefUpdate manager_email_update(local_state, kManagedUserManagerDisplayEmails); manager_update->SetWithoutPathExpansion(e_mail, new base::StringValue(manager->email())); manager_name_update->SetWithoutPathExpansion(e_mail, new base::StringValue(manager->GetDisplayName())); manager_email_update->SetWithoutPathExpansion(e_mail, new base::StringValue(manager->display_email())); SaveUserDisplayName(e_mail, display_name); g_browser_process->local_state()->CommitPendingWrite(); return new_user; } string16 UserManagerImpl::GetManagerDisplayNameForManagedUser( const std::string& managed_user_id) const { PrefService* local_state = g_browser_process->local_state(); const DictionaryValue* manager_names = local_state->GetDictionary(kManagedUserManagerNames); string16 result; if (manager_names->GetStringWithoutPathExpansion(managed_user_id, &result) && !result.empty()) return result; return UTF8ToUTF16(GetManagerDisplayEmailForManagedUser(managed_user_id)); } std::string UserManagerImpl::GetManagerUserIdForManagedUser( const std::string& managed_user_id) const { PrefService* local_state = g_browser_process->local_state(); const DictionaryValue* manager_ids = local_state->GetDictionary(kManagedUserManagers); std::string result; manager_ids->GetStringWithoutPathExpansion(managed_user_id, &result); return result; } std::string UserManagerImpl::GetManagerDisplayEmailForManagedUser( const std::string& managed_user_id) const { PrefService* local_state = g_browser_process->local_state(); const DictionaryValue* manager_mails = local_state->GetDictionary(kManagedUserManagerDisplayEmails); std::string result; if (manager_mails->GetStringWithoutPathExpansion(managed_user_id, &result) && !result.empty()) { return result; } return GetManagerUserIdForManagedUser(managed_user_id); } void UserManagerImpl::RemoveUser(const std::string& email, RemoveUserDelegate* delegate) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); const User* user = FindUser(email); if (!user || (user->GetType() != User::USER_TYPE_REGULAR && user->GetType() != User::USER_TYPE_LOCALLY_MANAGED)) return; // Sanity check: we must not remove single user. This check may seem // redundant at a first sight because this single user must be an owner and // we perform special check later in order not to remove an owner. However // due to non-instant nature of ownership assignment this later check may // sometimes fail. See http://crosbug.com/12723 if (users_.size() < 2) return; // Sanity check: do not allow any of the the logged in users to be removed. for (UserList::const_iterator it = logged_in_users_.begin(); it != logged_in_users_.end(); ++it) { if ((*it)->email() == email) return; } RemoveUserInternal(email, delegate); } void UserManagerImpl::RemoveUserFromList(const std::string& email) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); EnsureUsersLoaded(); RemoveNonCryptohomeData(email); delete RemoveRegularOrLocallyManagedUserFromList(email); // Make sure that new data is persisted to Local State. g_browser_process->local_state()->CommitPendingWrite(); } bool UserManagerImpl::IsKnownUser(const std::string& email) const { return FindUser(email) != NULL; } const User* UserManagerImpl::FindUser(const std::string& email) const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (active_user_ && active_user_->email() == email) return active_user_; return FindUserInList(email); } const User* UserManagerImpl::FindLocallyManagedUser( const string16& display_name) const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); const UserList& users = GetUsers(); for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) { if (((*it)->GetType() == User::USER_TYPE_LOCALLY_MANAGED) && ((*it)->display_name() == display_name)) { return *it; } } return NULL; } const User* UserManagerImpl::GetLoggedInUser() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return active_user_; } User* UserManagerImpl::GetLoggedInUser() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return active_user_; } const User* UserManagerImpl::GetActiveUser() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return active_user_; } User* UserManagerImpl::GetActiveUser() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return active_user_; } void UserManagerImpl::SaveUserOAuthStatus( const std::string& username, User::OAuthTokenStatus oauth_token_status) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DVLOG(1) << "Saving user OAuth token status in Local State"; User* user = FindUserAndModify(username); if (user) user->set_oauth_token_status(oauth_token_status); GetUserFlow(username)->HandleOAuthTokenStatusChange(oauth_token_status); // Do not update local store if data stored or cached outside the user's // cryptohome is to be treated as ephemeral. if (IsUserNonCryptohomeDataEphemeral(username)) return; PrefService* local_state = g_browser_process->local_state(); DictionaryPrefUpdate oauth_status_update(local_state, kUserOAuthTokenStatus); oauth_status_update->SetWithoutPathExpansion(username, new base::FundamentalValue(static_cast<int>(oauth_token_status))); } User::OAuthTokenStatus UserManagerImpl::LoadUserOAuthStatus( const std::string& username) const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); PrefService* local_state = g_browser_process->local_state(); const DictionaryValue* prefs_oauth_status = local_state->GetDictionary(kUserOAuthTokenStatus); int oauth_token_status = User::OAUTH_TOKEN_STATUS_UNKNOWN; if (prefs_oauth_status && prefs_oauth_status->GetIntegerWithoutPathExpansion( username, &oauth_token_status)) { User::OAuthTokenStatus result = static_cast<User::OAuthTokenStatus>(oauth_token_status); if (result == User::OAUTH2_TOKEN_STATUS_INVALID) GetUserFlow(username)->HandleOAuthTokenStatusChange(result); return result; } return User::OAUTH_TOKEN_STATUS_UNKNOWN; } void UserManagerImpl::SaveUserDisplayName(const std::string& username, const string16& display_name) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); User* user = FindUserAndModify(username); if (!user) return; // Ignore if there is no such user. user->set_display_name(display_name); // Do not update local store if data stored or cached outside the user's // cryptohome is to be treated as ephemeral. if (IsUserNonCryptohomeDataEphemeral(username)) return; PrefService* local_state = g_browser_process->local_state(); DictionaryPrefUpdate display_name_update(local_state, kUserDisplayName); display_name_update->SetWithoutPathExpansion( username, new base::StringValue(display_name)); // Update name if this user is manager of some managed users. const DictionaryValue* manager_ids = local_state->GetDictionary(kManagedUserManagers); DictionaryPrefUpdate manager_name_update(local_state, kManagedUserManagerNames); for (DictionaryValue::Iterator it(*manager_ids); !it.IsAtEnd(); it.Advance()) { std::string manager_id; bool has_manager_id = it.value().GetAsString(&manager_id); DCHECK(has_manager_id); if (manager_id == username) { manager_name_update->SetWithoutPathExpansion( it.key(), new base::StringValue(display_name)); } } } string16 UserManagerImpl::GetUserDisplayName( const std::string& username) const { const User* user = FindUser(username); return user ? user->display_name() : string16(); } void UserManagerImpl::SaveUserDisplayEmail(const std::string& username, const std::string& display_email) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); User* user = FindUserAndModify(username); if (!user) return; // Ignore if there is no such user. user->set_display_email(display_email); // Do not update local store if data stored or cached outside the user's // cryptohome is to be treated as ephemeral. if (IsUserNonCryptohomeDataEphemeral(username)) return; PrefService* local_state = g_browser_process->local_state(); DictionaryPrefUpdate display_email_update(local_state, kUserDisplayEmail); display_email_update->SetWithoutPathExpansion( username, new base::StringValue(display_email)); } std::string UserManagerImpl::GetUserDisplayEmail( const std::string& username) const { const User* user = FindUser(username); return user ? user->display_email() : username; } void UserManagerImpl::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_OWNERSHIP_STATUS_CHANGED: if (!device_local_account_policy_service_) { device_local_account_policy_service_ = g_browser_process->browser_policy_connector()-> GetDeviceLocalAccountPolicyService(); if (device_local_account_policy_service_) device_local_account_policy_service_->AddObserver(this); } CheckOwnership(); RetrieveTrustedDevicePolicies(); break; case chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED: if (IsUserLoggedIn() && !IsLoggedInAsGuest() && !IsLoggedInAsLocallyManagedUser() && !IsLoggedInAsKioskApp()) { Profile* profile = content::Details<Profile>(details).ptr(); if (!profile->IsOffTheRecord() && profile == ProfileManager::GetDefaultProfile()) { // TODO(nkostylev): We should observe all logged in user's profiles. // http://crbug.com/230860 if (!CommandLine::ForCurrentProcess()-> HasSwitch(::switches::kMultiProfiles)) { DCHECK(NULL == observed_sync_service_); observed_sync_service_ = ProfileSyncServiceFactory::GetForProfile(profile); if (observed_sync_service_) observed_sync_service_->AddObserver(this); } } } break; case chrome::NOTIFICATION_SYSTEM_SETTING_CHANGED: { std::string changed_setting = *content::Details<const std::string>(details).ptr(); DCHECK(changed_setting == kAccountsPrefDeviceLocalAccounts || changed_setting == kAccountsPrefSupervisedUsersEnabled); RetrieveTrustedDevicePolicies(); break; } default: NOTREACHED(); } } void UserManagerImpl::OnStateChanged() { DCHECK(IsLoggedInAsRegularUser()); GoogleServiceAuthError::State state = observed_sync_service_->GetAuthError().state(); if (state != GoogleServiceAuthError::NONE && state != GoogleServiceAuthError::CONNECTION_FAILED && state != GoogleServiceAuthError::SERVICE_UNAVAILABLE && state != GoogleServiceAuthError::REQUEST_CANCELED) { // Invalidate OAuth token to force Gaia sign-in flow. This is needed // because sign-out/sign-in solution is suggested to the user. // TODO(altimofeev): this code isn't needed after crosbug.com/25978 is // implemented. DVLOG(1) << "Invalidate OAuth token because of a sync error."; // http://crbug.com/230860 // TODO(nkostylev): Figure out whether we want to have observers // for each logged in user. // TODO(nkostyelv): Change observer after active user has changed. SaveUserOAuthStatus( active_user_->email(), User::OAUTH2_TOKEN_STATUS_INVALID); } } void UserManagerImpl::OnPolicyUpdated(const std::string& user_id) { UpdatePublicAccountDisplayName(user_id); NotifyUserListChanged(); } void UserManagerImpl::OnDeviceLocalAccountsChanged() { // No action needed here, changes to the list of device-local accounts get // handled via the kAccountsPrefDeviceLocalAccounts device setting observer. } bool UserManagerImpl::IsCurrentUserOwner() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); base::AutoLock lk(is_current_user_owner_lock_); return is_current_user_owner_; } void UserManagerImpl::SetCurrentUserIsOwner(bool is_current_user_owner) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); base::AutoLock lk(is_current_user_owner_lock_); is_current_user_owner_ = is_current_user_owner; UpdateLoginState(); } bool UserManagerImpl::IsCurrentUserNew() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return is_current_user_new_; } bool UserManagerImpl::IsCurrentUserNonCryptohomeDataEphemeral() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return IsUserLoggedIn() && IsUserNonCryptohomeDataEphemeral(GetLoggedInUser()->email()); } bool UserManagerImpl::CanCurrentUserLock() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return IsUserLoggedIn() && active_user_->can_lock(); } bool UserManagerImpl::IsUserLoggedIn() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return active_user_; } bool UserManagerImpl::IsLoggedInAsRegularUser() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return IsUserLoggedIn() && active_user_->GetType() == User::USER_TYPE_REGULAR; } bool UserManagerImpl::IsLoggedInAsDemoUser() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return IsUserLoggedIn() && active_user_->GetType() == User::USER_TYPE_RETAIL_MODE; } bool UserManagerImpl::IsLoggedInAsPublicAccount() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return IsUserLoggedIn() && active_user_->GetType() == User::USER_TYPE_PUBLIC_ACCOUNT; } bool UserManagerImpl::IsLoggedInAsGuest() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return IsUserLoggedIn() && active_user_->GetType() == User::USER_TYPE_GUEST; } bool UserManagerImpl::IsLoggedInAsLocallyManagedUser() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return IsUserLoggedIn() && active_user_->GetType() == User::USER_TYPE_LOCALLY_MANAGED; } bool UserManagerImpl::IsLoggedInAsKioskApp() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return IsUserLoggedIn() && active_user_->GetType() == User::USER_TYPE_KIOSK_APP; } bool UserManagerImpl::IsLoggedInAsStub() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return IsUserLoggedIn() && active_user_->email() == kStubUser; } bool UserManagerImpl::IsSessionStarted() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return session_started_; } bool UserManagerImpl::UserSessionsRestored() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return user_sessions_restored_; } UserManager::MergeSessionState UserManagerImpl::GetMergeSessionState() const { return merge_session_state_; } void UserManagerImpl::SetMergeSessionState( UserManager::MergeSessionState state) { if (merge_session_state_ == state) return; merge_session_state_ = state; NotifyMergeSessionStateChanged(); } bool UserManagerImpl::HasBrowserRestarted() const { CommandLine* command_line = CommandLine::ForCurrentProcess(); return base::chromeos::IsRunningOnChromeOS() && command_line->HasSwitch(switches::kLoginUser) && !command_line->HasSwitch(switches::kLoginPassword); } bool UserManagerImpl::IsUserNonCryptohomeDataEphemeral( const std::string& email) const { // Data belonging to the guest, retail mode and stub users is always // ephemeral. if (email == UserManager::kGuestUserName || email == UserManager::kRetailModeUserName || email == kStubUser) { return true; } // Data belonging to the owner, anyone found on the user list and obsolete // public accounts whose data has not been removed yet is not ephemeral. if (email == owner_email_ || FindUserInList(email) || email == g_browser_process->local_state()-> GetString(kPublicAccountPendingDataRemoval)) { return false; } // Data belonging to the currently logged-in user is ephemeral when: // a) The user logged into a regular account while the ephemeral users policy // was enabled. // - or - // b) The user logged into any other account type. if (IsUserLoggedIn() && (email == GetLoggedInUser()->email()) && (is_current_user_ephemeral_regular_user_ || !IsLoggedInAsRegularUser())) { return true; } // Data belonging to any other user is ephemeral when: // a) Going through the regular login flow and the ephemeral users policy is // enabled. // - or - // b) The browser is restarting after a crash. return AreEphemeralUsersEnabled() || HasBrowserRestarted(); } void UserManagerImpl::AddObserver(UserManager::Observer* obs) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); observer_list_.AddObserver(obs); } void UserManagerImpl::RemoveObserver(UserManager::Observer* obs) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); observer_list_.RemoveObserver(obs); } void UserManagerImpl::AddSessionStateObserver( UserManager::UserSessionStateObserver* obs) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); session_state_observer_list_.AddObserver(obs); } void UserManagerImpl::RemoveSessionStateObserver( UserManager::UserSessionStateObserver* obs) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); session_state_observer_list_.RemoveObserver(obs); } void UserManagerImpl::NotifyLocalStateChanged() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FOR_EACH_OBSERVER(UserManager::Observer, observer_list_, LocalStateChanged(this)); } void UserManagerImpl::OnProfilePrepared(Profile* profile) { LoginUtils::Get()->DoBrowserLaunch(profile, NULL); // host_, not needed here if (!CommandLine::ForCurrentProcess()->HasSwitch(::switches::kTestName)) { // Did not log in (we crashed or are debugging), need to restore Sync. // TODO(nkostylev): Make sure that OAuth state is restored correctly for all // users once it is fully multi-profile aware. http://crbug.com/238987 // For now if we have other user pending sessions they'll override OAuth // session restore for previous users. LoginUtils::Get()->RestoreAuthenticationSession(profile); } // Restore other user sessions if any. RestorePendingUserSessions(); } void UserManagerImpl::EnsureUsersLoaded() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!g_browser_process || !g_browser_process->local_state()) return; if (users_loaded_) return; users_loaded_ = true; // Clean up user list first. if (HasFailedLocallyManagedUserCreationTransaction()) RollbackLocallyManagedUserCreationTransaction(); PrefService* local_state = g_browser_process->local_state(); const ListValue* prefs_regular_users = local_state->GetList(kRegularUsers); const ListValue* prefs_public_accounts = local_state->GetList(kPublicAccounts); const DictionaryValue* prefs_display_names = local_state->GetDictionary(kUserDisplayName); const DictionaryValue* prefs_display_emails = local_state->GetDictionary(kUserDisplayEmail); // Load regular users and locally managed users. std::vector<std::string> regular_users; std::set<std::string> regular_users_set; ParseUserList(*prefs_regular_users, std::set<std::string>(), &regular_users, &regular_users_set); for (std::vector<std::string>::const_iterator it = regular_users.begin(); it != regular_users.end(); ++it) { User* user = NULL; const std::string domain = gaia::ExtractDomainName(*it); if (domain == UserManager::kLocallyManagedUserDomain) { user = User::CreateLocallyManagedUser(*it); } else { user = User::CreateRegularUser(*it); user->set_oauth_token_status(LoadUserOAuthStatus(*it)); } users_.push_back(user); string16 display_name; if (prefs_display_names->GetStringWithoutPathExpansion(*it, &display_name)) { user->set_display_name(display_name); } std::string display_email; if (prefs_display_emails->GetStringWithoutPathExpansion(*it, &display_email)) { user->set_display_email(display_email); } } // Load public accounts. std::vector<std::string> public_accounts; std::set<std::string> public_accounts_set; ParseUserList(*prefs_public_accounts, regular_users_set, &public_accounts, &public_accounts_set); for (std::vector<std::string>::const_iterator it = public_accounts.begin(); it != public_accounts.end(); ++it) { users_.push_back(User::CreatePublicAccountUser(*it)); UpdatePublicAccountDisplayName(*it); } user_image_manager_->LoadUserImages(users_); } void UserManagerImpl::RetrieveTrustedDevicePolicies() { ephemeral_users_enabled_ = false; locally_managed_users_enabled_by_policy_ = false; owner_email_ = ""; // Schedule a callback if device policy has not yet been verified. if (CrosSettingsProvider::TRUSTED != cros_settings_->PrepareTrustedValues( base::Bind(&UserManagerImpl::RetrieveTrustedDevicePolicies, base::Unretained(this)))) { return; } cros_settings_->GetBoolean(kAccountsPrefEphemeralUsersEnabled, &ephemeral_users_enabled_); cros_settings_->GetBoolean(kAccountsPrefSupervisedUsersEnabled, &locally_managed_users_enabled_by_policy_); cros_settings_->GetString(kDeviceOwner, &owner_email_); EnsureUsersLoaded(); bool changed = UpdateAndCleanUpPublicAccounts( policy::GetDeviceLocalAccounts(cros_settings_)); // If ephemeral users are enabled and we are on the login screen, take this // opportunity to clean up by removing all regular users except the owner. if (ephemeral_users_enabled_ && !IsUserLoggedIn()) { ListPrefUpdate prefs_users_update(g_browser_process->local_state(), kRegularUsers); prefs_users_update->Clear(); for (UserList::iterator it = users_.begin(); it != users_.end(); ) { const std::string user_email = (*it)->email(); if ((*it)->GetType() == User::USER_TYPE_REGULAR && user_email != owner_email_) { RemoveNonCryptohomeData(user_email); delete *it; it = users_.erase(it); changed = true; } else { if ((*it)->GetType() != User::USER_TYPE_PUBLIC_ACCOUNT) prefs_users_update->Append(new base::StringValue(user_email)); ++it; } } } if (changed) NotifyUserListChanged(); } bool UserManagerImpl::AreEphemeralUsersEnabled() const { return ephemeral_users_enabled_ && (g_browser_process->browser_policy_connector()->IsEnterpriseManaged() || !owner_email_.empty()); } UserList& UserManagerImpl::GetUsersAndModify() { EnsureUsersLoaded(); return users_; } User* UserManagerImpl::FindUserAndModify(const std::string& email) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (active_user_ && active_user_->email() == email) return active_user_; return FindUserInListAndModify(email); } const User* UserManagerImpl::FindUserInList(const std::string& email) const { const UserList& users = GetUsers(); for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) { if ((*it)->email() == email) return *it; } return NULL; } User* UserManagerImpl::FindUserInListAndModify(const std::string& email) { UserList& users = GetUsersAndModify(); for (UserList::iterator it = users.begin(); it != users.end(); ++it) { if ((*it)->email() == email) return *it; } return NULL; } void UserManagerImpl::GuestUserLoggedIn() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); WallpaperManager::Get()->SetInitialUserWallpaper(UserManager::kGuestUserName, false); active_user_ = User::CreateGuestUser(); // TODO(nkostylev): Add support for passing guest session cryptohome // mount point. Legacy (--login-profile) value will be used for now. // http://crosbug.com/230859 active_user_->SetStubImage(User::kInvalidImageIndex, false); } void UserManagerImpl::RegularUserLoggedIn(const std::string& email, bool browser_restart) { // Remove the user from the user list. active_user_ = RemoveRegularOrLocallyManagedUserFromList(email); // If the user was not found on the user list, create a new user. is_current_user_new_ = !active_user_; if (!active_user_) { active_user_ = User::CreateRegularUser(email); active_user_->set_oauth_token_status(LoadUserOAuthStatus(email)); SaveUserDisplayName(active_user_->email(), UTF8ToUTF16(active_user_->GetAccountName(true))); WallpaperManager::Get()->SetInitialUserWallpaper(email, true); } // Add the user to the front of the user list. ListPrefUpdate prefs_users_update(g_browser_process->local_state(), kRegularUsers); prefs_users_update->Insert(0, new base::StringValue(email)); users_.insert(users_.begin(), active_user_); user_image_manager_->UserLoggedIn(email, is_current_user_new_, false); if (!browser_restart) { // For GAIA login flow, logged in user wallpaper may not be loaded. WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded(); } default_pinned_apps_field_trial::SetupForUser(email, is_current_user_new_); // Make sure that new data is persisted to Local State. g_browser_process->local_state()->CommitPendingWrite(); } void UserManagerImpl::RegularUserLoggedInAsEphemeral(const std::string& email) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); is_current_user_new_ = true; is_current_user_ephemeral_regular_user_ = true; active_user_ = User::CreateRegularUser(email); user_image_manager_->UserLoggedIn(email, is_current_user_new_, false); WallpaperManager::Get()->SetInitialUserWallpaper(email, false); } void UserManagerImpl::LocallyManagedUserLoggedIn( const std::string& username) { // TODO(nkostylev): Refactor, share code with RegularUserLoggedIn(). // Remove the user from the user list. active_user_ = RemoveRegularOrLocallyManagedUserFromList(username); // If the user was not found on the user list, create a new user. if (!active_user_) { is_current_user_new_ = true; active_user_ = User::CreateLocallyManagedUser(username); // Leaving OAuth token status at the default state = unknown. WallpaperManager::Get()->SetInitialUserWallpaper(username, true); } else { ListPrefUpdate prefs_new_users_update(g_browser_process->local_state(), kLocallyManagedUsersFirstRun); if (prefs_new_users_update->Remove(base::StringValue(username), NULL)) { is_current_user_new_ = true; WallpaperManager::Get()->SetInitialUserWallpaper(username, true); } else { is_current_user_new_ = false; } } // Add the user to the front of the user list. ListPrefUpdate prefs_users_update(g_browser_process->local_state(), kRegularUsers); prefs_users_update->Insert(0, new base::StringValue(username)); users_.insert(users_.begin(), active_user_); // Now that user is in the list, save display name. if (is_current_user_new_) { SaveUserDisplayName(active_user_->email(), active_user_->GetDisplayName()); } user_image_manager_->UserLoggedIn(username, is_current_user_new_, true); WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded(); // Make sure that new data is persisted to Local State. g_browser_process->local_state()->CommitPendingWrite(); } void UserManagerImpl::PublicAccountUserLoggedIn(User* user) { is_current_user_new_ = true; active_user_ = user; // The UserImageManager chooses a random avatar picture when a user logs in // for the first time. Tell the UserImageManager that this user is not new to // prevent the avatar from getting changed. user_image_manager_->UserLoggedIn(user->email(), false, true); WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded(); } void UserManagerImpl::KioskAppLoggedIn(const std::string& username) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(policy::IsKioskAppUser(username)); WallpaperManager::Get()->SetInitialUserWallpaper(username, false); active_user_ = User::CreateKioskAppUser(username); active_user_->SetStubImage(User::kInvalidImageIndex, false); // TODO(bartfab): Add KioskAppUsers to the users_ list and keep metadata like // the kiosk_app_id in these objects, removing the need to re-parse the // device-local account list here to extract the kiosk_app_id. const std::vector<policy::DeviceLocalAccount> device_local_accounts = policy::GetDeviceLocalAccounts(cros_settings_); const policy::DeviceLocalAccount* account = NULL; for (std::vector<policy::DeviceLocalAccount>::const_iterator it = device_local_accounts.begin(); it != device_local_accounts.end(); ++it) { if (it->user_id == username) { account = &*it; break; } } std::string kiosk_app_id; if (account) { kiosk_app_id = account->kiosk_app_id; } else { LOG(ERROR) << "Logged into nonexistent kiosk-app account: " << username; NOTREACHED(); } CommandLine* command_line = CommandLine::ForCurrentProcess(); command_line->AppendSwitch(::switches::kForceAppMode); command_line->AppendSwitchASCII(::switches::kAppId, kiosk_app_id); // Disable window animation since kiosk app runs in a single full screen // window and window animation causes start-up janks. command_line->AppendSwitch( views::corewm::switches::kWindowAnimationsDisabled); } void UserManagerImpl::RetailModeUserLoggedIn() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); is_current_user_new_ = true; active_user_ = User::CreateRetailModeUser(); user_image_manager_->UserLoggedIn(UserManager::kRetailModeUserName, is_current_user_new_, true); WallpaperManager::Get()->SetInitialUserWallpaper( UserManager::kRetailModeUserName, false); } void UserManagerImpl::NotifyOnLogin() { CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); NotifyActiveUserHashChanged(active_user_->username_hash()); NotifyActiveUserChanged(active_user_); UpdateLoginState(); // TODO(nkostylev): Deprecate this notification in favor of // ActiveUserChanged() observer call. content::NotificationService::current()->Notify( chrome::NOTIFICATION_LOGIN_USER_CHANGED, content::Source<UserManager>(this), content::Details<const User>(active_user_)); // Indicate to DeviceSettingsService that the owner key may have become // available. DeviceSettingsService::Get()->SetUsername(active_user_->email()); } void UserManagerImpl::UpdateOwnership( DeviceSettingsService::OwnershipStatus status, bool is_owner) { VLOG(1) << "Current user " << (is_owner ? "is owner" : "is not owner"); SetCurrentUserIsOwner(is_owner); } void UserManagerImpl::CheckOwnership() { DeviceSettingsService::Get()->GetOwnershipStatusAsync( base::Bind(&UserManagerImpl::UpdateOwnership, base::Unretained(this))); } void UserManagerImpl::RemoveNonCryptohomeData(const std::string& email) { WallpaperManager::Get()->RemoveUserWallpaperInfo(email); user_image_manager_->DeleteUserImage(email); PrefService* prefs = g_browser_process->local_state(); DictionaryPrefUpdate prefs_oauth_update(prefs, kUserOAuthTokenStatus); int oauth_status; prefs_oauth_update->GetIntegerWithoutPathExpansion(email, &oauth_status); prefs_oauth_update->RemoveWithoutPathExpansion(email, NULL); DictionaryPrefUpdate prefs_display_name_update(prefs, kUserDisplayName); prefs_display_name_update->RemoveWithoutPathExpansion(email, NULL); DictionaryPrefUpdate prefs_display_email_update(prefs, kUserDisplayEmail); prefs_display_email_update->RemoveWithoutPathExpansion(email, NULL); ListPrefUpdate prefs_new_users_update(prefs, kLocallyManagedUsersFirstRun); prefs_new_users_update->Remove(base::StringValue(email), NULL); DictionaryPrefUpdate managers_update(prefs, kManagedUserManagers); managers_update->RemoveWithoutPathExpansion(email, NULL); DictionaryPrefUpdate manager_names_update(prefs, kManagedUserManagerNames); manager_names_update->RemoveWithoutPathExpansion(email, NULL); DictionaryPrefUpdate manager_emails_update(prefs, kManagedUserManagerDisplayEmails); manager_emails_update->RemoveWithoutPathExpansion(email, NULL); } User* UserManagerImpl::RemoveRegularOrLocallyManagedUserFromList( const std::string& username) { ListPrefUpdate prefs_users_update(g_browser_process->local_state(), kRegularUsers); prefs_users_update->Clear(); User* user = NULL; for (UserList::iterator it = users_.begin(); it != users_.end(); ) { const std::string user_email = (*it)->email(); if (user_email == username) { user = *it; it = users_.erase(it); } else { if ((*it)->GetType() == User::USER_TYPE_REGULAR || (*it)->GetType() == User::USER_TYPE_LOCALLY_MANAGED) { prefs_users_update->Append(new base::StringValue(user_email)); } ++it; } } return user; } void UserManagerImpl::CleanUpPublicAccountNonCryptohomeDataPendingRemoval() { PrefService* local_state = g_browser_process->local_state(); const std::string public_account_pending_data_removal = local_state->GetString(kPublicAccountPendingDataRemoval); if (public_account_pending_data_removal.empty() || (IsUserLoggedIn() && public_account_pending_data_removal == GetActiveUser()->email())) { return; } RemoveNonCryptohomeData(public_account_pending_data_removal); local_state->ClearPref(kPublicAccountPendingDataRemoval); } void UserManagerImpl::CleanUpPublicAccountNonCryptohomeData( const std::vector<std::string>& old_public_accounts) { std::set<std::string> users; for (UserList::const_iterator it = users_.begin(); it != users_.end(); ++it) users.insert((*it)->email()); // If the user is logged into a public account that has been removed from the // user list, mark the account's data as pending removal after logout. if (IsLoggedInAsPublicAccount()) { const std::string active_user_id = GetActiveUser()->email(); if (users.find(active_user_id) == users.end()) { g_browser_process->local_state()->SetString( kPublicAccountPendingDataRemoval, active_user_id); users.insert(active_user_id); } } // Remove the data belonging to any other public accounts that are no longer // found on the user list. for (std::vector<std::string>::const_iterator it = old_public_accounts.begin(); it != old_public_accounts.end(); ++it) { if (users.find(*it) == users.end()) RemoveNonCryptohomeData(*it); } } bool UserManagerImpl::UpdateAndCleanUpPublicAccounts( const std::vector<policy::DeviceLocalAccount>& device_local_accounts) { // Try to remove any public account data marked as pending removal. CleanUpPublicAccountNonCryptohomeDataPendingRemoval(); // Get the current list of public accounts. std::vector<std::string> old_public_accounts; for (UserList::const_iterator it = users_.begin(); it != users_.end(); ++it) { if ((*it)->GetType() == User::USER_TYPE_PUBLIC_ACCOUNT) old_public_accounts.push_back((*it)->email()); } // Get the new list of public accounts from policy. std::vector<std::string> new_public_accounts; for (std::vector<policy::DeviceLocalAccount>::const_iterator it = device_local_accounts.begin(); it != device_local_accounts.end(); ++it) { // TODO(mnissler, nkostylev, bartfab): Process Kiosk Apps within the // standard login framework: http://crbug.com/234694 if (it->type == policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION) new_public_accounts.push_back(it->user_id); } // If the list of public accounts has not changed, return. if (new_public_accounts.size() == old_public_accounts.size()) { bool changed = false; for (size_t i = 0; i < new_public_accounts.size(); ++i) { if (new_public_accounts[i] != old_public_accounts[i]) { changed = true; break; } } if (!changed) return false; } // Persist the new list of public accounts in a pref. ListPrefUpdate prefs_public_accounts_update(g_browser_process->local_state(), kPublicAccounts); prefs_public_accounts_update->Clear(); for (std::vector<std::string>::const_iterator it = new_public_accounts.begin(); it != new_public_accounts.end(); ++it) { prefs_public_accounts_update->AppendString(*it); } // Remove the old public accounts from the user list. for (UserList::iterator it = users_.begin(); it != users_.end(); ) { if ((*it)->GetType() == User::USER_TYPE_PUBLIC_ACCOUNT) { if (*it != GetLoggedInUser()) delete *it; it = users_.erase(it); } else { ++it; } } // Add the new public accounts to the front of the user list. for (std::vector<std::string>::const_reverse_iterator it = new_public_accounts.rbegin(); it != new_public_accounts.rend(); ++it) { if (IsLoggedInAsPublicAccount() && *it == GetActiveUser()->email()) users_.insert(users_.begin(), GetLoggedInUser()); else users_.insert(users_.begin(), User::CreatePublicAccountUser(*it)); UpdatePublicAccountDisplayName(*it); } user_image_manager_->LoadUserImages( UserList(users_.begin(), users_.begin() + new_public_accounts.size())); // Remove data belonging to public accounts that are no longer found on the // user list. CleanUpPublicAccountNonCryptohomeData(old_public_accounts); return true; } void UserManagerImpl::UpdatePublicAccountDisplayName( const std::string& username) { std::string display_name; if (device_local_account_policy_service_) { policy::DeviceLocalAccountPolicyBroker* broker = device_local_account_policy_service_->GetBrokerForUser(username); if (broker) display_name = broker->GetDisplayName(); } // Set or clear the display name. SaveUserDisplayName(username, UTF8ToUTF16(display_name)); } void UserManagerImpl::StartLocallyManagedUserCreationTransaction( const string16& display_name) { g_browser_process->local_state()-> SetString(kLocallyManagedUserCreationTransactionDisplayName, UTF16ToASCII(display_name)); g_browser_process->local_state()->CommitPendingWrite(); } void UserManagerImpl::SetLocallyManagedUserCreationTransactionUserId( const std::string& email) { g_browser_process->local_state()-> SetString(kLocallyManagedUserCreationTransactionUserId, email); g_browser_process->local_state()->CommitPendingWrite(); } void UserManagerImpl::CommitLocallyManagedUserCreationTransaction() { g_browser_process->local_state()-> ClearPref(kLocallyManagedUserCreationTransactionDisplayName); g_browser_process->local_state()-> ClearPref(kLocallyManagedUserCreationTransactionUserId); g_browser_process->local_state()->CommitPendingWrite(); } bool UserManagerImpl::HasFailedLocallyManagedUserCreationTransaction() { return !(g_browser_process->local_state()-> GetString(kLocallyManagedUserCreationTransactionDisplayName). empty()); } void UserManagerImpl::RollbackLocallyManagedUserCreationTransaction() { PrefService* prefs = g_browser_process->local_state(); std::string display_name = prefs-> GetString(kLocallyManagedUserCreationTransactionDisplayName); std::string user_id = prefs-> GetString(kLocallyManagedUserCreationTransactionUserId); LOG(WARNING) << "Cleaning up transaction for " << display_name << "/" << user_id; if (user_id.empty()) { // Not much to do - just remove transaction. prefs->ClearPref(kLocallyManagedUserCreationTransactionDisplayName); return; } if (gaia::ExtractDomainName(user_id) != kLocallyManagedUserDomain) { LOG(WARNING) << "Clean up transaction for non-locally managed user found :" << user_id << ", will not remove data"; prefs->ClearPref(kLocallyManagedUserCreationTransactionDisplayName); prefs->ClearPref(kLocallyManagedUserCreationTransactionUserId); return; } ListPrefUpdate prefs_users_update(prefs, kRegularUsers); prefs_users_update->Remove(base::StringValue(user_id), NULL); RemoveNonCryptohomeData(user_id); cryptohome::AsyncMethodCaller::GetInstance()->AsyncRemove( user_id, base::Bind(&OnRemoveUserComplete, user_id)); prefs->ClearPref(kLocallyManagedUserCreationTransactionDisplayName); prefs->ClearPref(kLocallyManagedUserCreationTransactionUserId); prefs->CommitPendingWrite(); } UserFlow* UserManagerImpl::GetCurrentUserFlow() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!IsUserLoggedIn()) return GetDefaultUserFlow(); return GetUserFlow(GetLoggedInUser()->email()); } UserFlow* UserManagerImpl::GetUserFlow(const std::string& email) const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FlowMap::const_iterator it = specific_flows_.find(email); if (it != specific_flows_.end()) return it->second; return GetDefaultUserFlow(); } void UserManagerImpl::SetUserFlow(const std::string& email, UserFlow* flow) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ResetUserFlow(email); specific_flows_[email] = flow; } void UserManagerImpl::ResetUserFlow(const std::string& email) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FlowMap::iterator it = specific_flows_.find(email); if (it != specific_flows_.end()) { delete it->second; specific_flows_.erase(it); } } bool UserManagerImpl::GetAppModeChromeClientOAuthInfo( std::string* chrome_client_id, std::string* chrome_client_secret) { if (!chrome::IsRunningInForcedAppMode() || chrome_client_id_.empty() || chrome_client_secret_.empty()) { return false; } *chrome_client_id = chrome_client_id_; *chrome_client_secret = chrome_client_secret_; return true; } void UserManagerImpl::SetAppModeChromeClientOAuthInfo( const std::string& chrome_client_id, const std::string& chrome_client_secret) { if (!chrome::IsRunningInForcedAppMode()) return; chrome_client_id_ = chrome_client_id; chrome_client_secret_ = chrome_client_secret; } bool UserManagerImpl::AreLocallyManagedUsersAllowed() const { return ManagedUserService::AreManagedUsersEnabled() && (locally_managed_users_enabled_by_policy_ || !g_browser_process->browser_policy_connector()->IsEnterpriseManaged()); } UserFlow* UserManagerImpl::GetDefaultUserFlow() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!default_flow_.get()) default_flow_.reset(new DefaultUserFlow()); return default_flow_.get(); } void UserManagerImpl::NotifyUserListChanged() { content::NotificationService::current()->Notify( chrome::NOTIFICATION_USER_LIST_CHANGED, content::Source<UserManager>(this), content::NotificationService::NoDetails()); } void UserManagerImpl::NotifyMergeSessionStateChanged() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FOR_EACH_OBSERVER(UserManager::Observer, observer_list_, MergeSessionStateChanged(merge_session_state_)); } void UserManagerImpl::NotifyActiveUserChanged(const User* active_user) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver, session_state_observer_list_, ActiveUserChanged(active_user)); } void UserManagerImpl::NotifyActiveUserHashChanged(const std::string& hash) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver, session_state_observer_list_, ActiveUserHashChanged(hash)); } void UserManagerImpl::NotifyPendingUserSessionsRestoreFinished() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); user_sessions_restored_ = true; FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver, session_state_observer_list_, PendingUserSessionsRestoreFinished()); } void UserManagerImpl::UpdateLoginState() { if (!LoginState::IsInitialized()) return; // LoginState may not be intialized in tests. LoginState::LoggedInState logged_in_state; logged_in_state = active_user_ ? LoginState::LOGGED_IN_ACTIVE : LoginState::LOGGED_IN_NONE; LoginState::LoggedInUserType login_user_type; if (logged_in_state == LoginState::LOGGED_IN_NONE) login_user_type = LoginState::LOGGED_IN_USER_NONE; else if (is_current_user_owner_) login_user_type = LoginState::LOGGED_IN_USER_OWNER; else if (active_user_->GetType() == User::USER_TYPE_GUEST) login_user_type = LoginState::LOGGED_IN_USER_GUEST; else if (active_user_->GetType() == User::USER_TYPE_RETAIL_MODE) login_user_type = LoginState::LOGGED_IN_USER_RETAIL_MODE; else if (active_user_->GetType() == User::USER_TYPE_PUBLIC_ACCOUNT) login_user_type = LoginState::LOGGED_IN_USER_PUBLIC_ACCOUNT; else if (active_user_->GetType() == User::USER_TYPE_LOCALLY_MANAGED) login_user_type = LoginState::LOGGED_IN_USER_LOCALLY_MANAGED; else if (active_user_->GetType() == User::USER_TYPE_KIOSK_APP) login_user_type = LoginState::LOGGED_IN_USER_KIOSK_APP; else login_user_type = LoginState::LOGGED_IN_USER_REGULAR; LoginState::Get()->SetLoggedInState(logged_in_state, login_user_type); } void UserManagerImpl::SetLRUUser(User* user) { UserList::iterator it = std::find(lru_logged_in_users_.begin(), lru_logged_in_users_.end(), user); if (it != lru_logged_in_users_.end()) lru_logged_in_users_.erase(it); lru_logged_in_users_.insert(lru_logged_in_users_.begin(), user); } void UserManagerImpl::OnRestoreActiveSessions( const SessionManagerClient::ActiveSessionsMap& sessions, bool success) { if (!success) { LOG(ERROR) << "Could not get list of active user sessions after crash."; // If we could not get list of active user sessions it is safer to just // sign out so that we don't get in the inconsistent state. DBusThreadManager::Get()->GetSessionManagerClient()->StopSession(); return; } // One profile has been already loaded on browser start. DCHECK(GetLoggedInUsers().size() == 1); DCHECK(GetActiveUser()); std::string active_user_id = GetActiveUser()->email(); SessionManagerClient::ActiveSessionsMap::const_iterator it; for (it = sessions.begin(); it != sessions.end(); ++it) { if (active_user_id == it->first) continue; pending_user_sessions_[it->first] = it->second; } RestorePendingUserSessions(); } void UserManagerImpl::RestorePendingUserSessions() { if (pending_user_sessions_.empty()) { NotifyPendingUserSessionsRestoreFinished(); return; } // Get next user to restore sessions and delete it from list. SessionManagerClient::ActiveSessionsMap::const_iterator it = pending_user_sessions_.begin(); std::string user_id = it->first; std::string user_id_hash = it->second; DCHECK(!user_id.empty()); DCHECK(!user_id_hash.empty()); pending_user_sessions_.erase(user_id); // Check that this user is not logged in yet. UserList logged_in_users = GetLoggedInUsers(); bool user_already_logged_in = false; for (UserList::const_iterator it = logged_in_users.begin(); it != logged_in_users.end(); ++it) { const User* user = (*it); if (user->email() == user_id) { user_already_logged_in = true; break; } } DCHECK(!user_already_logged_in); if (!user_already_logged_in) { // Will call OnProfilePrepared() once profile has been loaded. LoginUtils::Get()->PrepareProfile(UserContext(user_id, std::string(), // password std::string(), // auth_code user_id_hash), std::string(), // display_email false, // using_oauth false, // has_cookies true, // has_active_session this); } else { RestorePendingUserSessions(); } } } // namespace chromeos
[ "Khilan.Gudka@cl.cam.ac.uk" ]
Khilan.Gudka@cl.cam.ac.uk
d5dd77dac3097956250cf5c64cb41e2f7df306b2
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE121_Stack_Based_Buffer_Overflow/s06/CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_ncat_82.h
2f09730a8a540e1ebb6d7d149a16420790531ef9
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
1,361
h
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_ncat_82.h Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE806.label.xml Template File: sources-sink-82.tmpl.h */ /* * @description * CWE: 121 Stack Based Buffer Overflow * BadSource: Initialize data as a large string * GoodSource: Initialize data as a small string * BadSink : Copy data to string using strncat * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_ncat_82 { class CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_ncat_82_base { public: /* pure virtual function */ virtual void action(char * data) = 0; }; #ifndef OMITBAD class CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_ncat_82_bad : public CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_ncat_82_base { public: void action(char * data); }; #endif /* OMITBAD */ #ifndef OMITGOOD class CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_ncat_82_goodG2B : public CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_ncat_82_base { public: void action(char * data); }; #endif /* OMITGOOD */ }
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
22d6bed54c52cf1942052c5abbf0b44fb1081780
9740c92e917aaf2991ff08238eb87ed8f7323a59
/test/test_thread/NonCopyable.h
ab5c93a033ac6923b1ac8d128c2a4052fe3caf24
[ "MIT" ]
permissive
gggin/RaySync
f37d89ce5089c4981639290b2c74a993cbf8e46f
89cb317b4f3b67bd62d1de54d4c46c557fe90ae0
refs/heads/master
2021-01-10T11:24:29.435958
2015-12-16T10:14:59
2015-12-16T10:14:59
46,699,051
0
1
null
null
null
null
UTF-8
C++
false
false
276
h
#ifndef NONCOPYABLE_H_ #define NONCOPYABLE_H_ class NonCopyable { public: NonCopyable() {} ~NonCopyable() {} private: NonCopyable(const NonCopyable &); void operator=(const NonCopyable &); }; #endif /*NONCOPYABLE_H_*/
[ "fm369o802340@163.com" ]
fm369o802340@163.com
2e1df0793335a96faaabb93be18a741befbbe3f6
b6e92e4f4207421acaa20551b7042477f0410668
/engine/engine/ManagerTexture.cpp
268a301e3b6a078ccd5f57ef206a81d847be7398
[]
no_license
Meldow/CGJ-Chess
f18b6917ec849f2e15097493c522b85e3a50cbd9
aea8427538d4db361445739c41a55011120777b3
refs/heads/master
2016-08-12T17:06:02.951388
2016-01-25T12:57:23
2016-01-25T12:57:23
47,121,351
2
2
null
null
null
null
UTF-8
C++
false
false
807
cpp
#pragma once #include "ManagerTexture.h" #include <iostream> SINGLETON_IMPLEMENTATION_NO_CONSTRUCTOR(ManagerTexture) ManagerTexture::ManagerTexture() {} void ManagerTexture::add(char* name, Texture* texture) { textures.insert(std::pair<char*, Texture*>(name, texture)); } Texture* ManagerTexture::get(char* name) { try { return textures.find(name)->second; } catch (std::exception) { std::cout << "\nManagerTexture::get::Element not found::" << name; } std::cout << "\nManagerTexture::get::Element not found::" << name; return nullptr; } void ManagerTexture::flushManagerMesh() { std::cout << "\nManagerTexture::flush::"; for (_texturesIterator = textures.begin(); _texturesIterator != textures.end(); ++_texturesIterator) { std::cout << "\nElement::" << _texturesIterator->first; } }
[ "alexandremacc@gmail.com" ]
alexandremacc@gmail.com
583bbe80dc50f27ad3e383af3b9207988f6f5c5c
50457fc28800b3cf2f25e06478f33981a1a626dc
/Facebook-Hackercup/2019/qualification/mr_x.cpp
8e1f1df17a3fec9d7690c164e2ce6815969b38d4
[]
no_license
h-sinha/CP-codes
5b1ef5021b7fd180b518270ffdb12997dc8d367b
937174c73d1c80114de4535a6908122158366ad4
refs/heads/master
2021-07-20T18:47:00.500294
2021-07-06T05:11:57
2021-07-06T05:11:57
159,954,721
2
2
null
2020-01-07T18:57:28
2018-12-01T14:51:44
C++
UTF-8
C++
false
false
2,484
cpp
#include<bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define DEBUG #ifdef DEBUG #define debug(...) __f(#__VA_ARGS__, __VA_ARGS__) template <typename Arg1> void __f(const char* name, Arg1&& arg1){ cerr << name << " : " << arg1 << std::endl; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args){ const char* comma = strchr(names + 1, ','); cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...); } #else #define debug(...) #endif #define FOR(i,a,b) for(int i=a;i<b;++i) #define RFOR(i,a,b) for(int i=a;i>=b;--i) #define ln "\n" #define mp make_pair #define pb push_back #define sz(a) ll(a.size()) #define F first #define S second #define all(c) c.begin(),c.end() #define trace(c,x) for(auto &x:c) #define pii pair<ll,ll> typedef long long ll; typedef long double ld; typedef priority_queue<pii,std::vector<pii>,greater<pii> > revpr; typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> pbds; // ordered_set X //K-th smallest //*X.f_by_order(k-1) //NO OF ELEMENTS < A //X.order_of_key(A) const int L=1e6+7; string s; int n; std::map<char, int> hsh; int f(int a, char type, int b) { if(type == '|')return (a|b); if(type == '&')return (a&b); if(type == '^')return (a^b); } int calc(int x, int X) { stack<char> operand; stack<int> val; int cur1, cur2; char exp; FOR(i,0,n) { if(s[i] == ')') { while(operand.top() != '(') { cur1 = val.top(); val.pop(); cur2 = val.top(); val.pop(); exp = operand.top(); operand.pop(); val.push(f(cur1, exp, cur2)); } operand.pop(); } else { if(hsh[s[i]] == 1) { operand.push(s[i]); } else { if(s[i] == 'x')val.push(x); else if(s[i] == 'X')val.push(X); else if(s[i] == '1')val.push(1); else if(s[i] == '0')val.push(0); } } } return val.top(); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t, c1, c2, ans; cin >> t; hsh['('] = 1; hsh[')'] = 1; hsh['|'] = 1; hsh['&'] = 1; hsh['^'] = 1; hsh['x'] = 2; hsh['X'] = 2; hsh['1'] = 2; hsh['0'] = 2; FOR(z,1,t+1) { cin >> s; n = s.length(); c1 = calc(1,0); c2 = calc(0,1); if(c1 == c2) { cout<<"Case #"<<z<<": "<<0<<ln; } else { cout<<"Case #"<<z<<": "<<1<<ln; } } return 0; }
[ "harsh.26020@gmail.com" ]
harsh.26020@gmail.com
5fee67c3a2c387a4c63e71c548d22df10029f609
8bc16b2510188db604429e93c44a0d3393dbc3c2
/PureBasic/AlembicCurves.h
1f8fdc3b384e999bf6d5d07cbc05c772ddc6f4de
[]
no_license
benmalartre/Booze
f3e497a5792c2b9ce0b4fb17d5c11aebdb13a9aa
f3537f667deb6447ce9b65074d32e028f6fefc2b
refs/heads/master
2020-07-09T22:06:03.921219
2019-04-19T21:13:22
2019-04-19T21:13:22
94,262,542
0
0
null
null
null
null
UTF-8
C++
false
false
2,106
h
#ifndef _ALEMBIC_CURVE_H_ #define _ALEMBIC_CURVE_H_ #include "AlembicObject.h" BOOZE_NAMESPACE_OPEN_SCOPE struct ABC_Curves_Sample_Infos { uint64_t m_numPoints; uint64_t m_numCurves; uint64_t m_sampleindex; bool m_hasWidth; bool m_hasUV; bool m_hasNormal; bool m_hasWeight; bool m_hasOrder; bool m_hasKnot; }; struct ABC_Curves_Sample { float* m_position; uint32_t* m_numVerticesPerCurve; AbcG::CurveType m_type; AbcG::CurvePeriodicity m_periodicity; float* m_width; float* m_uv; float* m_normal; AbcG::BasisType m_basis; float* m_weight; char* m_order; float* m_knot; }; //------------------------------------------------------------------------------------------------ // Alembic Import //------------------------------------------------------------------------------------------------ class AlembicICurves : public AlembicIObject { public: AlembicICurves(AbcG::IObject& iObj); virtual ~AlembicICurves(){}; bool initialize() override; protected: AbcG::IXformSchema m_xform; AbcG::ICurvesSchema m_curves; AbcG::ICompoundProperty m_compound; AbcG::ICurvesSchema::Sample m_sample; size_t m_numSamples; size_t m_numPoints; size_t m_numCurves; }; //------------------------------------------------------------------------------------------------ // Alembic Export //------------------------------------------------------------------------------------------------ typedef AbcU::shared_ptr< AbcG::OCurves> ABCOCurvesPtr; class AlembicOCurves : public AlembicOObject { protected: ABCOCurvesPtr m_curves; AbcG::OCurvesSchema m_schema; AbcG::OCurvesSchema::Sample m_sample; size_t m_numsamples; size_t m_numPoints; size_t m_numCurves; public: AlembicOCurves(AlembicOArchive* archive, AlembicOObject* parent, void* customData, const char* name); ~AlembicOCurves(){ /*if (m_curves)delete m_curves.get();*/ }; void save(AbcA::TimeSamplingPtr time) override; AbcG::OObject get(){ return *m_curves; }; ABCOObjectPtr getPtr() override { return m_curves; }; }; BOOZE_NAMESPACE_CLOSE_SCOPE #endif
[ "benmalartre@hotmail.com" ]
benmalartre@hotmail.com
dfbd8a0fdf720fea729d4cb2488e248823f7f0e1
3267680798c8d637d07aeb8d0a93c2bc09a1571f
/sesiones/12 sesion/ejercicio12.12.cpp
c4d61c4ea172869a6ef0826b3ca11a4ea1791c3c
[]
no_license
antOnioOnio/Fundamentos-De-Programacion
05c5cbd502b9181ecfbaf7e0fac940a073698410
84bc7aeb7302c6db81f5577a5c9961f306f84183
refs/heads/master
2020-04-20T22:12:35.458997
2019-02-04T19:19:41
2019-02-04T19:19:41
169,132,079
0
0
null
null
null
null
UTF-8
C++
false
false
3,435
cpp
/*Sobre la clase SecuenciaCaracteres añada el método para eliminar un bloque, desde un determinado valor a otro determninado valor.*/ #include <iostream> using namespace std; struct FrecuenciaCaracteres{ char caracter; int frecuencia; }; class SecuenciaCaracteres{ private: static const int TAMANIO = 1000; char vector_privado[TAMANIO]; int total_utilizados; public: SecuenciaCaracteres() :total_utilizados(0) { } int Capacidad(){ return TAMANIO; } int TotalUtilizados(){ return total_utilizados; } int LeeLongLongMayorQue( int minimo, string mensaje ){ int dato; do { cout << mensaje ; cin >> dato ; }while ( dato < minimo ); return dato; } double LeeDoubleEnrango( double minimo, double maximo, string mensaje){ double dato; do { cout << mensaje; cin >> dato; }while ( dato < minimo || dato > maximo); return dato; } void Aniade(char nuevo){ if (total_utilizados < TAMANIO){ vector_privado[total_utilizados] = nuevo; total_utilizados++; } } char Elemento(int indice){ return vector_privado[indice]; } void EliminaCaracter ( char a_borrar){ for ( int i=0 ; i<total_utilizados ; i++){ if (vector_privado[i]==a_borrar){ vector_privado[i]=vector_privado[i+1]; } } } void EliminaBloque (){ const string Msj_minimo = " introduce minimo\n " , Msj_maximo = " introduce maximo \n "; int minimo, maximo, a_mover; minimo = LeeLongLongMayorQue(0, Msj_minimo); maximo =LeeLongLongMayorQue(minimo, Msj_maximo); a_mover = maximo - minimo; for ( int i=minimo; i<maximo; i++ ){ vector_privado[i]=vector_privado[i + a_mover]; } } void MuestraVector (){ for ( int i = 0; i < total_utilizados ; i++){ cout << vector_privado[i]; } } FrecuenciaCaracteres Moda(){ FrecuenciaCaracteres moda; const int TAMANIO = 255 ; int frecuencia_max = -1; int vector[TAMANIO]; for ( int i =0; i<TAMANIO ; i++){ vector[i]=0; } for(int i=0;i<total_utilizados;i++){ vector[vector_privado[i]]++; if ( vector[vector_privado[i]] > frecuencia_max) moda.caracter = vector_privado[i]; moda.frecuencia=vector[moda.caracter]; frecuencia_max=moda.frecuencia; } return moda; } }; int main() { const char FIN = '#'; SecuenciaCaracteres texto; char caracter; cout << " Introduce una serie de caracteres terminado en '#' " <<endl; caracter=cin.get(); while(caracter!=FIN ){ texto.Aniade(caracter); caracter=cin.get(); } texto.EliminaBloque(); texto.MuestraVector(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
836af18775f6a0eca8ac1fadcdaa9ac332c32c5c
458e8e86d7784b919a0bb80b6cd6654bc7771e68
/ontology_model/my_work/agents_c_plus/0.5.0/problem-solver/cxx/factual_knowledge_similarity_calculation/keynodes/keynodes.cpp
3671ba17bca4f7898fa23352899ab3438a9cb9ad
[]
no_license
liwenzu/BSUIR-OSTIS
50090993810695d0384ef2e0f1225d630370f2f1
980d4628567912c816f333fd4c4d5ea7f195cab3
refs/heads/master
2022-09-21T06:24:29.684173
2022-09-14T19:30:24
2022-09-14T19:30:24
218,078,699
0
0
null
null
null
null
UTF-8
C++
false
false
629
cpp
/* * This source file is part of an OSTIS project. For the latest info, see http://ostis.net * Distributed under the MIT License * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ #include "keynodes.hpp" #include <sc-memory/cpp/sc_memory.hpp> namespace facknowsimcalcu { ScAddr Keynodes::factual_kn_similarity_calculation; ScAddr Keynodes::nrel_correct_answer; ScAddr Keynodes::nrel_user_answer; ScAddr Keynodes::nrel_relation_decomposition; ScAddr Keynodes::nrel_system_identifier; ScAddr Keynodes::nrel_incorrect_answer; ScAddr Keynodes::nrel_coefficient; }
[ "lwzzggml@gmail.com" ]
lwzzggml@gmail.com
5e62e25b8724258d902b24008ae4b243f25e5616
e6e73055224d5b006012340bc00670bace121ba6
/libiop/benchmarks/benchmark_gf64.cpp
4a34a2df889bd45b4880317e956106b06d2cda81
[ "MIT" ]
permissive
AntoineRondelet/libiop
459939b6edd41f3a9de0b4726019bb3196372cff
e73e241b6c750f7713cf59eeaa94b34f4f1fb3b9
refs/heads/master
2021-01-09T00:39:02.457411
2020-02-21T17:08:42
2020-02-21T17:08:42
242,190,775
0
0
MIT
2020-02-21T17:08:53
2020-02-21T17:08:52
null
UTF-8
C++
false
false
3,887
cpp
#include <cmath> #include <cstddef> #include <vector> #include <benchmark/benchmark.h> #include "libiop/algebra/fields/gf64.hpp" #include "libiop/algebra/utils.hpp" namespace libiop { static void BM_gf64_mul_vec(benchmark::State &state) { const size_t sz = state.range(0); const std::vector<gf64> avec = random_vector<gf64>(sz); const std::vector<gf64> bvec = random_vector<gf64>(sz); std::vector<gf64> cvec(sz); for (auto _ : state) { for (size_t i = 0; i < sz; ++i) { cvec[i] = avec[i] * bvec[i]; } } state.SetItemsProcessed(state.iterations() * sz); } BENCHMARK(BM_gf64_mul_vec)->Range(1<<10, 1<<20)->Unit(benchmark::kMicrosecond); static void BM_gf64_mul_vec_data_dependency(benchmark::State &state) { const size_t sz = state.range(0); const std::vector<gf64> avec = random_vector<gf64>(sz); const std::vector<gf64> bvec = random_vector<gf64>(sz); gf64 sum = gf64(0); for (auto _ : state) { for (size_t i = 0; i < sz; ++i) { sum += avec[i] * bvec[i]; } } state.SetItemsProcessed(state.iterations() * sz); } BENCHMARK(BM_gf64_mul_vec_data_dependency)->Range(1<<10, 1<<20)->Unit(benchmark::kMicrosecond); // The goal of this is to measure how long N multiplications take, with no cache misses static void BM_gf64_mul(benchmark::State &state) { // Update per what google benchmark claims the L1 cache size for this system is. const size_t L1_cache_size = 1ull << 15; // 32 KB // divides by 4, since it uses avec, and bvec, and do not optimize will force flushes to memory const size_t num_elems = (L1_cache_size / (4 * sizeof(gf64))); const size_t sz = state.range(0); const std::vector<gf64> avec = random_vector<gf64>(num_elems); std::vector<gf64> bvec = random_vector<gf64>(num_elems); const size_t num_iters = sz / num_elems; // may be off by 1 iteration, but that should be negligible for (auto _ : state) { for (size_t i = 0; i < num_iters; ++i) { for (size_t j = 0; j < num_elems; j++) { bvec[j] = avec[j] * bvec[j]; } } } state.SetItemsProcessed(state.iterations() * sz); } BENCHMARK(BM_gf64_mul)->Range(1<<20, 1<<28)->Unit(benchmark::kMicrosecond); // The goal of this is to measure how long N *= ops take, with no cache misses static void BM_gf64_mul_equals(benchmark::State &state) { // Update per what google benchmark claims the L1 cache size for this system is. const size_t L1_cache_size = 1ull << 15; // 32 KB // divides by 4, since it uses avec, and bvec, and do not optimize will force flushes to memory const size_t num_elems = (L1_cache_size / (4 * sizeof(gf64))); const size_t sz = state.range(0); std::vector<gf64> avec = random_vector<gf64>(num_elems); const std::vector<gf64> bvec = random_vector<gf64>(num_elems); const size_t num_iters = sz / num_elems; // may be off by 1 iteration, but that should be negligible for (auto _ : state) { for (size_t i = 0; i < num_iters; ++i) { for (size_t j = 0; j < num_elems; j++) { avec[j] *= bvec[j]; } } } state.SetItemsProcessed(state.iterations() * sz); } BENCHMARK(BM_gf64_mul_equals)->Range(1<<20, 1<<28)->Unit(benchmark::kMicrosecond); static void BM_gf64_inverse_vec(benchmark::State& state) { const size_t sz = state.range(0); const std::vector<gf64> vec = random_vector<gf64>(sz); std::vector<gf64> result(sz); for (auto _ : state) { for (size_t i = 0; i < sz; ++i) { result[i] = vec[i].inverse(); } } state.SetItemsProcessed(state.iterations() * sz); } BENCHMARK(BM_gf64_inverse_vec)->Range(1<<10, 1<<16)->Unit(benchmark::kMicrosecond); } BENCHMARK_MAIN();
[ "dojha12@gmail.com" ]
dojha12@gmail.com
eaeee1723cf10f03c6ba53c4dc8c4ba34daa1edb
fe072ecf40220abc178c3281a663b94d34d82558
/Filter.h
8aae4b9d5fddcaf516c60a9fa59a803d40ea8819
[]
no_license
connortribbett/CPP-AVX2-OpenMP-3x3-Image-Filtering-Algo
9705e6a377cff5302eb6d974f0f507d9b12f7c37
e624617e30ab8bf841edef0c11399f58046981e4
refs/heads/master
2023-05-08T11:11:47.176626
2021-05-07T05:37:20
2021-05-07T05:37:20
222,013,699
1
0
null
null
null
null
UTF-8
C++
false
false
597
h
//-*-c++-*- #ifndef _Filter_h_ #define _Filter_h_ #include <immintrin.h> using namespace std; struct __2in3Filter{ __m256 upper; __m256 middle; __m256 lower; }; struct __2in3Filter128{ __m128 upper; __m128 middle; __m128 lower; }; class Filter { float divisor; int dim; float *data; public: Filter(int _dim); inline float get(int r, int c) { return data[ r * dim + c ]; }; void set(int r, int c, int value); float getDivisor(); void setDivisor(int value); int getSize(); void info(); __2in3Filter getFilter(); __2in3Filter128 getFilter128(); }; #endif
[ "noreply@github.com" ]
noreply@github.com
353e76cc63861701767559726f8a8dfbd63908e5
d5eb860b97dac6b0f45aaa7dbab66b0ad884dfbf
/CF-Upsolving v001/Solutions/red_maple/I/main.cpp
a3c82f68b4b62ee8415958d2871e0aa820c2306b
[ "MIT" ]
permissive
gmeligio/axon_training
97c6a0ca43a340d0805fd059f9bfa4b2cd85a46b
657f181b732265856c71e97697bfde2062744e5a
refs/heads/master
2020-05-18T12:11:41.531964
2019-05-30T20:38:45
2019-05-30T20:38:45
184,400,460
1
0
MIT
2019-05-01T10:25:36
2019-05-01T10:25:35
null
UTF-8
C++
false
false
1,675
cpp
/* Date 05/13/2019 Brenda E Ramirez. */ #include <bits/stdc++.h> #include <limits.h> #include <algorithm> #include <numeric> #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; using namespace std; #define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] " #define endl '\n' using ll = long long; const int precision = 16; const int modulo = 1000000007; // 10^9 + 7 const ll lmodulo = 1000000007; // 10^9 + 7 const double EPS = 1e-9; bool check(vector<vector<int>> & m) { for(auto r = 0; r < (int)m.size(); ++r) { for(auto c = 1; c < (int)m[0].size(); ++c) { if(m[r][c - 1] >= m[r][c]) return false; } } for(auto c = 0; c < (int)m[0].size(); ++c) { for(auto r = 1; r < (int)m.size(); ++r) { if(m[r - 1][c] >= m[r][c]) return false; } } return true; } void solveI(){ int n, m; cin >> n >> m; vector<vector<int>> a(n, vector<int>(m)), b(n, vector<int>(m)); for(auto &r : a) { for(auto &c : r) { cin >> c; } } for(auto &r : b) { for(auto &c : r) { cin >> c; } } for(auto r = 0; r < n; ++r) { for(auto c = 0; c < m; ++c) { if(a[r][c] > b[r][c]) { swap(a[r][c], b[r][c]); } } } if(check(a) and check(b)) { cout << "Possible"; } else { cout << "Impossible"; } } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cout.precision(precision); cout.setf(ios_base::fixed); solveI(); return 0; }
[ "bem3ly@gmail.com" ]
bem3ly@gmail.com
08f883438532d4260c559c538857e62389cbfef1
9b25cb49b6b30ee5d86bfdf4e2a52f72a9d790a2
/Snakes/Snake/SnakeField.cpp
3ac25a7b59cd10e43df7b99e1f722f6882e4ae57
[]
no_license
ifanzilka/Snakes
de81d7cba74ec6a2384175e717666054d8349716
e1300721cbfba67bf9a61e804ac77ac2fd6d80cd
refs/heads/master
2020-09-14T06:08:31.141643
2019-11-20T23:19:50
2019-11-20T23:19:50
223,044,046
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
4,324
cpp
#include "SnakeField.h" #include <SFML/Graphics.hpp> #include <windows.h> #include <time.h> using namespace sf; // libary sfml void SnakeField::draw_Game() { //draw window.clear(); //draw map for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { sprite1.setPosition(i*size, j*size); window.draw(sprite1); } } //draw snake sprite3.setPosition(s[0].x*size, s[0].y*size); window.draw(sprite3);//brain for (int i = 1; i < num; i++) { sprite2.setPosition(s[i].x*size, s[i].y*size); window.draw(sprite2); } //draw fruit sprite4.setPosition(f.x*size, f.y*size); window.draw(sprite4); //draw score String s; s = "SCORE: "; s += std::to_string(score); text.setString(s);//задает строку тексту text.setPosition(10, (M)*size);//задаем позицию текста, центр камеры text.setFillColor(Color::Blue); window.draw(text);//рисую этот текст window.display();//draw Texture } void SnakeField::StartGame() { HWND hConsole = GetConsoleWindow();//Если компилятор старый заменить на GetForegroundWindow() ShowWindow(hConsole, SW_HIDE);//собственно прячем оконо консоли srand(time(0)); //start position fruit f.x = 10; f.y = 10; while (window.isOpen() && !endGame) { float time = clock.getElapsedTime().asSeconds(); clock.restart(); timer += time; Event e; while (window.pollEvent(e)) { if (e.type == Event::Closed) { //int a=1; window.close(); } } if ((Keyboard::isKeyPressed(Keyboard::Left)) && prev_keyboard != 2) dir = 1, prev_keyboard = 1; if ((Keyboard::isKeyPressed(Keyboard::Right)) && prev_keyboard != 1) dir = 2, prev_keyboard = 2; if ((Keyboard::isKeyPressed(Keyboard::Up)) && prev_keyboard != 0) dir = 3, prev_keyboard = 3; if ((Keyboard::isKeyPressed(Keyboard::Down)) && prev_keyboard != 3) dir = 0, prev_keyboard = 0; if (timer > delay) { timer = 0; Tick(); } draw_Game(); } EndGame(); } void SnakeField::EndGame() { //draw ENDGAME while (window.isOpen()) { window.clear(); Event e; while (window.pollEvent(e)) { if (e.type == Event::Closed) { //int a=1; window.close(); } } text.setStyle(sf::Text::Bold | sf::Text::Underlined);//жирный и подчеркнутый текст. по умолчанию он "худой":)) и не подчеркнутый Text text2(" ", font, 20);//создаем объект текст. закидываем в объект текст строку, шрифт, размер шрифта(в пикселях);//сам объект текст (не строка) text2.setStyle(sf::Text::Bold | sf::Text::Underlined);//жирный и подчеркнутый текст. по умолчанию он "худой":)) и не подчеркнутый String s1, s2; s1 = "TNE END!"; s2 = "YOUR SCORE: "; s2 += std::to_string(score); text.setString(s1);//задает строку тексту text.setPosition(w / 2 - 80, h / 2 - 70);//задаем позицию текста, центр камеры text.setFillColor(Color::Red); text2.setString(s2);//задает строку тексту text2.setPosition(w / 2 - 80, h / 2 - 50);//задаем позицию текста, центр камеры text2.setFillColor(Color::Red); window.draw(text);//исую этот текст window.draw(text2);//исую этот текст window.display();//draw Texture } } SnakeField::SnakeField() { //window window.create(VideoMode(w, h), "Snake Game!",sf::Style::Close); //texture t1.loadFromFile("images/white.png"); t2.loadFromFile("images/red.png"); t3.loadFromFile("images/snake.png"); t4.loadFromFile("images/yellow.png"); //OBJECT sprite1.setTexture(t1); sprite2.setTexture(t2); sprite3.setTexture(t3); sprite4.setTexture(t4); // font.loadFromFile("CyrilicOld.ttf");//передаем нашему шрифту файл шрифта Text tex1("SCORE", font, 20); text = tex1; } SnakeField::~SnakeField() { }
[ "noreply@github.com" ]
noreply@github.com
05b82c3ed00050940d17e227135c47de2d1f377f
0bb3f3cd3c370302f9b85d906b1d4473e1687a56
/second/312_Burst_Balloons/sol.cpp
74016ebee830e04bf104a14575035bbfae41edd7
[]
no_license
yongjianmu/leetcode
5f1ad1a0a8e5ada01221165022d74933ed3db5e3
563a42bee9e0cb4111c3fe49a9fbfa77d381811f
refs/heads/master
2021-09-08T22:00:40.339589
2021-08-31T09:08:39
2021-08-31T09:08:39
60,553,872
0
0
null
null
null
null
UTF-8
C++
false
false
1,240
cpp
#include "../include/header.h" /* Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent. Find the maximum coins you can collect by bursting the balloons wisely. Note: (1) You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them. (2) 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100 */ class Solution { public: int DP(int i, int j, const vector<int> &nums, vector<vector<int> > &dp) { if (dp[i][j] > 0) return dp[i][j]; for (int x = i; x <= j; x++) { int temp = DP(i, x - 1, nums, dp) + nums[i - 1] * nums[x] * nums[j + 1] + DP(x + 1, j, nums, dp); if (temp > dp[i][j]) dp[i][j] = temp; } return dp[i][j]; } int maxCoins(vector<int>& nums) { int n = nums.size(); nums.insert(nums.begin(), 1); nums.insert(nums.end(), 1); vector<vector<int> > dp(n + 2, vector<int>(n + 2, 0)); return DP(1, n, nums, dp); } };
[ "Yongjian@yongjiandembp.uconnect.utah.edu" ]
Yongjian@yongjiandembp.uconnect.utah.edu
81731980cf24b0c922a89232d2a427c1e049ee67
2f4f95bee60d3be5e7489e92f7fc46a2eab24e73
/VANETSim/src/inet/transport/rtp/reports_m.cc
3c3f76678f46c02e07df5a2544d0a6c53299334a
[]
no_license
daliaaaa/VANETProject
72bbb2211e8df9e9a103036361a787c1dce05126
263b604ce0924999ea6d5d72b812f1a236818461
refs/heads/master
2021-01-18T08:47:34.863194
2016-04-10T20:19:10
2016-04-10T20:19:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,213
cc
// // Generated file, do not edit! Created by nedtool 4.6 from inet/transport/rtp/reports.msg. // // Disable warnings about unused variables, empty switch stmts, etc: #ifdef _MSC_VER # pragma warning(disable:4101) # pragma warning(disable:4065) #endif #include <iostream> #include <sstream> #include "reports_m.h" USING_NAMESPACE // Another default rule (prevents compiler from choosing base class' doPacking()) template<typename T> void doPacking(cCommBuffer *, T& t) { throw cRuntimeError("Parsim error: no doPacking() function for type %s or its base class (check .msg and _m.cc/h files!)",opp_typename(typeid(t))); } template<typename T> void doUnpacking(cCommBuffer *, T& t) { throw cRuntimeError("Parsim error: no doUnpacking() function for type %s or its base class (check .msg and _m.cc/h files!)",opp_typename(typeid(t))); } // Template rule for outputting std::vector<T> types template<typename T, typename A> inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec) { out.put('{'); for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it) { if (it != vec.begin()) { out.put(','); out.put(' '); } out << *it; } out.put('}'); char buf[32]; sprintf(buf, " (size=%u)", (unsigned int)vec.size()); out.write(buf, strlen(buf)); return out; } // Template rule which fires if a struct or class doesn't have operator<< template<typename T> inline std::ostream& operator<<(std::ostream& out,const T&) {return out;} SenderReport_Base::SenderReport_Base() : ::cObject() { this->NTPTimeStamp_var = 0; this->RTPTimeStamp_var = 0; this->packetCount_var = 0; this->byteCount_var = 0; } SenderReport_Base::SenderReport_Base(const SenderReport_Base& other) : ::cObject(other) { copy(other); } SenderReport_Base::~SenderReport_Base() { } SenderReport_Base& SenderReport_Base::operator=(const SenderReport_Base& other) { if (this==&other) return *this; ::cObject::operator=(other); copy(other); return *this; } void SenderReport_Base::copy(const SenderReport_Base& other) { this->NTPTimeStamp_var = other.NTPTimeStamp_var; this->RTPTimeStamp_var = other.RTPTimeStamp_var; this->packetCount_var = other.packetCount_var; this->byteCount_var = other.byteCount_var; } void SenderReport_Base::parsimPack(cCommBuffer *b) { doPacking(b,this->NTPTimeStamp_var); doPacking(b,this->RTPTimeStamp_var); doPacking(b,this->packetCount_var); doPacking(b,this->byteCount_var); } void SenderReport_Base::parsimUnpack(cCommBuffer *b) { doUnpacking(b,this->NTPTimeStamp_var); doUnpacking(b,this->RTPTimeStamp_var); doUnpacking(b,this->packetCount_var); doUnpacking(b,this->byteCount_var); } uint64 SenderReport_Base::getNTPTimeStamp() const { return NTPTimeStamp_var; } void SenderReport_Base::setNTPTimeStamp(uint64 NTPTimeStamp) { this->NTPTimeStamp_var = NTPTimeStamp; } uint32 SenderReport_Base::getRTPTimeStamp() const { return RTPTimeStamp_var; } void SenderReport_Base::setRTPTimeStamp(uint32 RTPTimeStamp) { this->RTPTimeStamp_var = RTPTimeStamp; } uint32 SenderReport_Base::getPacketCount() const { return packetCount_var; } void SenderReport_Base::setPacketCount(uint32 packetCount) { this->packetCount_var = packetCount; } uint32 SenderReport_Base::getByteCount() const { return byteCount_var; } void SenderReport_Base::setByteCount(uint32 byteCount) { this->byteCount_var = byteCount; } class SenderReportDescriptor : public cClassDescriptor { public: SenderReportDescriptor(); virtual ~SenderReportDescriptor(); virtual bool doesSupport(cObject *obj) const; virtual const char *getProperty(const char *propertyname) const; virtual int getFieldCount(void *object) const; virtual const char *getFieldName(void *object, int field) const; virtual int findField(void *object, const char *fieldName) const; virtual unsigned int getFieldTypeFlags(void *object, int field) const; virtual const char *getFieldTypeString(void *object, int field) const; virtual const char *getFieldProperty(void *object, int field, const char *propertyname) const; virtual int getArraySize(void *object, int field) const; virtual std::string getFieldAsString(void *object, int field, int i) const; virtual bool setFieldAsString(void *object, int field, int i, const char *value) const; virtual const char *getFieldStructName(void *object, int field) const; virtual void *getFieldStructPointer(void *object, int field, int i) const; }; Register_ClassDescriptor(SenderReportDescriptor); SenderReportDescriptor::SenderReportDescriptor() : cClassDescriptor("SenderReport", "cObject") { } SenderReportDescriptor::~SenderReportDescriptor() { } bool SenderReportDescriptor::doesSupport(cObject *obj) const { return dynamic_cast<SenderReport_Base *>(obj)!=NULL; } const char *SenderReportDescriptor::getProperty(const char *propertyname) const { if (!strcmp(propertyname,"customize")) return "true"; cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : NULL; } int SenderReportDescriptor::getFieldCount(void *object) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 4+basedesc->getFieldCount(object) : 4; } unsigned int SenderReportDescriptor::getFieldTypeFlags(void *object, int field) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount(object)) return basedesc->getFieldTypeFlags(object, field); field -= basedesc->getFieldCount(object); } static unsigned int fieldTypeFlags[] = { FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, }; return (field>=0 && field<4) ? fieldTypeFlags[field] : 0; } const char *SenderReportDescriptor::getFieldName(void *object, int field) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount(object)) return basedesc->getFieldName(object, field); field -= basedesc->getFieldCount(object); } static const char *fieldNames[] = { "NTPTimeStamp", "RTPTimeStamp", "packetCount", "byteCount", }; return (field>=0 && field<4) ? fieldNames[field] : NULL; } int SenderReportDescriptor::findField(void *object, const char *fieldName) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); int base = basedesc ? basedesc->getFieldCount(object) : 0; if (fieldName[0]=='N' && strcmp(fieldName, "NTPTimeStamp")==0) return base+0; if (fieldName[0]=='R' && strcmp(fieldName, "RTPTimeStamp")==0) return base+1; if (fieldName[0]=='p' && strcmp(fieldName, "packetCount")==0) return base+2; if (fieldName[0]=='b' && strcmp(fieldName, "byteCount")==0) return base+3; return basedesc ? basedesc->findField(object, fieldName) : -1; } const char *SenderReportDescriptor::getFieldTypeString(void *object, int field) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount(object)) return basedesc->getFieldTypeString(object, field); field -= basedesc->getFieldCount(object); } static const char *fieldTypeStrings[] = { "uint64", "uint32", "uint32", "uint32", }; return (field>=0 && field<4) ? fieldTypeStrings[field] : NULL; } const char *SenderReportDescriptor::getFieldProperty(void *object, int field, const char *propertyname) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount(object)) return basedesc->getFieldProperty(object, field, propertyname); field -= basedesc->getFieldCount(object); } switch (field) { default: return NULL; } } int SenderReportDescriptor::getArraySize(void *object, int field) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount(object)) return basedesc->getArraySize(object, field); field -= basedesc->getFieldCount(object); } SenderReport_Base *pp = (SenderReport_Base *)object; (void)pp; switch (field) { default: return 0; } } std::string SenderReportDescriptor::getFieldAsString(void *object, int field, int i) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount(object)) return basedesc->getFieldAsString(object,field,i); field -= basedesc->getFieldCount(object); } SenderReport_Base *pp = (SenderReport_Base *)object; (void)pp; switch (field) { case 0: return uint642string(pp->getNTPTimeStamp()); case 1: return ulong2string(pp->getRTPTimeStamp()); case 2: return ulong2string(pp->getPacketCount()); case 3: return ulong2string(pp->getByteCount()); default: return ""; } } bool SenderReportDescriptor::setFieldAsString(void *object, int field, int i, const char *value) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount(object)) return basedesc->setFieldAsString(object,field,i,value); field -= basedesc->getFieldCount(object); } SenderReport_Base *pp = (SenderReport_Base *)object; (void)pp; switch (field) { case 0: pp->setNTPTimeStamp(string2uint64(value)); return true; case 1: pp->setRTPTimeStamp(string2ulong(value)); return true; case 2: pp->setPacketCount(string2ulong(value)); return true; case 3: pp->setByteCount(string2ulong(value)); return true; default: return false; } } const char *SenderReportDescriptor::getFieldStructName(void *object, int field) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount(object)) return basedesc->getFieldStructName(object, field); field -= basedesc->getFieldCount(object); } switch (field) { default: return NULL; }; } void *SenderReportDescriptor::getFieldStructPointer(void *object, int field, int i) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount(object)) return basedesc->getFieldStructPointer(object, field, i); field -= basedesc->getFieldCount(object); } SenderReport_Base *pp = (SenderReport_Base *)object; (void)pp; switch (field) { default: return NULL; } } ReceptionReport_Base::ReceptionReport_Base() : ::cObject() { this->ssrc_var = 0; this->fractionLost_var = 0; this->packetsLostCumulative_var = 0; this->sequenceNumber_var = 0; this->jitter_var = 0; this->lastSR_var = 0; this->delaySinceLastSR_var = 0; } ReceptionReport_Base::ReceptionReport_Base(const ReceptionReport_Base& other) : ::cObject(other) { copy(other); } ReceptionReport_Base::~ReceptionReport_Base() { } ReceptionReport_Base& ReceptionReport_Base::operator=(const ReceptionReport_Base& other) { if (this==&other) return *this; ::cObject::operator=(other); copy(other); return *this; } void ReceptionReport_Base::copy(const ReceptionReport_Base& other) { this->ssrc_var = other.ssrc_var; this->fractionLost_var = other.fractionLost_var; this->packetsLostCumulative_var = other.packetsLostCumulative_var; this->sequenceNumber_var = other.sequenceNumber_var; this->jitter_var = other.jitter_var; this->lastSR_var = other.lastSR_var; this->delaySinceLastSR_var = other.delaySinceLastSR_var; } void ReceptionReport_Base::parsimPack(cCommBuffer *b) { doPacking(b,this->ssrc_var); doPacking(b,this->fractionLost_var); doPacking(b,this->packetsLostCumulative_var); doPacking(b,this->sequenceNumber_var); doPacking(b,this->jitter_var); doPacking(b,this->lastSR_var); doPacking(b,this->delaySinceLastSR_var); } void ReceptionReport_Base::parsimUnpack(cCommBuffer *b) { doUnpacking(b,this->ssrc_var); doUnpacking(b,this->fractionLost_var); doUnpacking(b,this->packetsLostCumulative_var); doUnpacking(b,this->sequenceNumber_var); doUnpacking(b,this->jitter_var); doUnpacking(b,this->lastSR_var); doUnpacking(b,this->delaySinceLastSR_var); } uint32 ReceptionReport_Base::getSsrc() const { return ssrc_var; } void ReceptionReport_Base::setSsrc(uint32 ssrc) { this->ssrc_var = ssrc; } uint8 ReceptionReport_Base::getFractionLost() const { return fractionLost_var; } void ReceptionReport_Base::setFractionLost(uint8 fractionLost) { this->fractionLost_var = fractionLost; } int ReceptionReport_Base::getPacketsLostCumulative() const { return packetsLostCumulative_var; } void ReceptionReport_Base::setPacketsLostCumulative(int packetsLostCumulative) { this->packetsLostCumulative_var = packetsLostCumulative; } uint32 ReceptionReport_Base::getSequenceNumber() const { return sequenceNumber_var; } void ReceptionReport_Base::setSequenceNumber(uint32 sequenceNumber) { this->sequenceNumber_var = sequenceNumber; } int ReceptionReport_Base::getJitter() const { return jitter_var; } void ReceptionReport_Base::setJitter(int jitter) { this->jitter_var = jitter; } int ReceptionReport_Base::getLastSR() const { return lastSR_var; } void ReceptionReport_Base::setLastSR(int lastSR) { this->lastSR_var = lastSR; } int ReceptionReport_Base::getDelaySinceLastSR() const { return delaySinceLastSR_var; } void ReceptionReport_Base::setDelaySinceLastSR(int delaySinceLastSR) { this->delaySinceLastSR_var = delaySinceLastSR; } class ReceptionReportDescriptor : public cClassDescriptor { public: ReceptionReportDescriptor(); virtual ~ReceptionReportDescriptor(); virtual bool doesSupport(cObject *obj) const; virtual const char *getProperty(const char *propertyname) const; virtual int getFieldCount(void *object) const; virtual const char *getFieldName(void *object, int field) const; virtual int findField(void *object, const char *fieldName) const; virtual unsigned int getFieldTypeFlags(void *object, int field) const; virtual const char *getFieldTypeString(void *object, int field) const; virtual const char *getFieldProperty(void *object, int field, const char *propertyname) const; virtual int getArraySize(void *object, int field) const; virtual std::string getFieldAsString(void *object, int field, int i) const; virtual bool setFieldAsString(void *object, int field, int i, const char *value) const; virtual const char *getFieldStructName(void *object, int field) const; virtual void *getFieldStructPointer(void *object, int field, int i) const; }; Register_ClassDescriptor(ReceptionReportDescriptor); ReceptionReportDescriptor::ReceptionReportDescriptor() : cClassDescriptor("ReceptionReport", "cObject") { } ReceptionReportDescriptor::~ReceptionReportDescriptor() { } bool ReceptionReportDescriptor::doesSupport(cObject *obj) const { return dynamic_cast<ReceptionReport_Base *>(obj)!=NULL; } const char *ReceptionReportDescriptor::getProperty(const char *propertyname) const { if (!strcmp(propertyname,"customize")) return "true"; cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : NULL; } int ReceptionReportDescriptor::getFieldCount(void *object) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 7+basedesc->getFieldCount(object) : 7; } unsigned int ReceptionReportDescriptor::getFieldTypeFlags(void *object, int field) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount(object)) return basedesc->getFieldTypeFlags(object, field); field -= basedesc->getFieldCount(object); } static unsigned int fieldTypeFlags[] = { FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, }; return (field>=0 && field<7) ? fieldTypeFlags[field] : 0; } const char *ReceptionReportDescriptor::getFieldName(void *object, int field) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount(object)) return basedesc->getFieldName(object, field); field -= basedesc->getFieldCount(object); } static const char *fieldNames[] = { "ssrc", "fractionLost", "packetsLostCumulative", "sequenceNumber", "jitter", "lastSR", "delaySinceLastSR", }; return (field>=0 && field<7) ? fieldNames[field] : NULL; } int ReceptionReportDescriptor::findField(void *object, const char *fieldName) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); int base = basedesc ? basedesc->getFieldCount(object) : 0; if (fieldName[0]=='s' && strcmp(fieldName, "ssrc")==0) return base+0; if (fieldName[0]=='f' && strcmp(fieldName, "fractionLost")==0) return base+1; if (fieldName[0]=='p' && strcmp(fieldName, "packetsLostCumulative")==0) return base+2; if (fieldName[0]=='s' && strcmp(fieldName, "sequenceNumber")==0) return base+3; if (fieldName[0]=='j' && strcmp(fieldName, "jitter")==0) return base+4; if (fieldName[0]=='l' && strcmp(fieldName, "lastSR")==0) return base+5; if (fieldName[0]=='d' && strcmp(fieldName, "delaySinceLastSR")==0) return base+6; return basedesc ? basedesc->findField(object, fieldName) : -1; } const char *ReceptionReportDescriptor::getFieldTypeString(void *object, int field) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount(object)) return basedesc->getFieldTypeString(object, field); field -= basedesc->getFieldCount(object); } static const char *fieldTypeStrings[] = { "uint32", "uint8", "int", "uint32", "int", "int", "int", }; return (field>=0 && field<7) ? fieldTypeStrings[field] : NULL; } const char *ReceptionReportDescriptor::getFieldProperty(void *object, int field, const char *propertyname) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount(object)) return basedesc->getFieldProperty(object, field, propertyname); field -= basedesc->getFieldCount(object); } switch (field) { default: return NULL; } } int ReceptionReportDescriptor::getArraySize(void *object, int field) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount(object)) return basedesc->getArraySize(object, field); field -= basedesc->getFieldCount(object); } ReceptionReport_Base *pp = (ReceptionReport_Base *)object; (void)pp; switch (field) { default: return 0; } } std::string ReceptionReportDescriptor::getFieldAsString(void *object, int field, int i) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount(object)) return basedesc->getFieldAsString(object,field,i); field -= basedesc->getFieldCount(object); } ReceptionReport_Base *pp = (ReceptionReport_Base *)object; (void)pp; switch (field) { case 0: return ulong2string(pp->getSsrc()); case 1: return ulong2string(pp->getFractionLost()); case 2: return long2string(pp->getPacketsLostCumulative()); case 3: return ulong2string(pp->getSequenceNumber()); case 4: return long2string(pp->getJitter()); case 5: return long2string(pp->getLastSR()); case 6: return long2string(pp->getDelaySinceLastSR()); default: return ""; } } bool ReceptionReportDescriptor::setFieldAsString(void *object, int field, int i, const char *value) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount(object)) return basedesc->setFieldAsString(object,field,i,value); field -= basedesc->getFieldCount(object); } ReceptionReport_Base *pp = (ReceptionReport_Base *)object; (void)pp; switch (field) { case 0: pp->setSsrc(string2ulong(value)); return true; case 1: pp->setFractionLost(string2ulong(value)); return true; case 2: pp->setPacketsLostCumulative(string2long(value)); return true; case 3: pp->setSequenceNumber(string2ulong(value)); return true; case 4: pp->setJitter(string2long(value)); return true; case 5: pp->setLastSR(string2long(value)); return true; case 6: pp->setDelaySinceLastSR(string2long(value)); return true; default: return false; } } const char *ReceptionReportDescriptor::getFieldStructName(void *object, int field) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount(object)) return basedesc->getFieldStructName(object, field); field -= basedesc->getFieldCount(object); } switch (field) { default: return NULL; }; } void *ReceptionReportDescriptor::getFieldStructPointer(void *object, int field, int i) const { cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount(object)) return basedesc->getFieldStructPointer(object, field, i); field -= basedesc->getFieldCount(object); } ReceptionReport_Base *pp = (ReceptionReport_Base *)object; (void)pp; switch (field) { default: return NULL; } }
[ "siroisjo@gmail.com" ]
siroisjo@gmail.com
d1835c6ac9e37f6287fa96a4cbc5e44465f253f3
764d59d448c032dd853d8c4df95a23590f088b59
/src/main.cpp
54534e80417890f57bc1f9da405da2a67b690ba9
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
fire/flow-avatar-asset-pipeline
29d842068359a71149b402a736ddc1a4da544da0
85e9bcbf413865307a58115c32315965a0c22376
refs/heads/main
2023-05-31T13:55:36.578218
2021-04-30T01:39:16
2021-04-30T01:39:16
376,369,022
1
0
null
null
null
null
UTF-8
C++
false
false
9,499
cpp
/* avatar-build is distributed under MIT license: * * Copyright (c) 2021 Kota Iguchi * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <fstream> #include <iostream> #include <string> #include <vector> #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION #define STB_LEAKCHECK_IMPLEMENTATION #include "stb_image.h" #include "stb_image_write.h" #include "stb_leakcheck.h" #include "CLI11.hpp" #include "DSPatch.h" #include "json.hpp" #define CGLTF_IMPLEMENTATION #define CGLTF_WRITE_IMPLEMENTATION #define CGLTF_VRM_v0_0 #define CGLTF_VRM_v0_0_IMPLEMENTATION #include "cgltf_write.h" #pragma warning(push) #pragma warning(disable : 4458) // declaration of 'source' hides class member #include "verbalexpressions.hpp" #pragma warning(pop) #include <ghc/filesystem.hpp> namespace fs = ghc::filesystem; using json = nlohmann::json; #include "pipelines.hpp" #include "gltf_func.inl" #include "gltf_overrides_func.inl" #include "json_func.inl" #include "bones_func.inl" #include "vrm0_func.inl" #include "glb_T_pose.hpp" #include "glb_jpeg_to_png.hpp" #include "glb_fix_roll.hpp" #include "glb_transforms_apply.hpp" #include "glb_z_reverse.hpp" #include "glb_overrides.hpp" #include "vrm0_fix_joint_buffer.hpp" #include "vrm0_default_extensions.hpp" #include "vrm0_remove_extensions.hpp" #include "gltf_pipeline.hpp" #include "gltfpack_execute.hpp" #include "gltfpack_pipeline.hpp" #include "noop.hpp" #include "fbx2gltf_execute.hpp" #include "fbx_pipeline.hpp" using namespace AvatarBuild; using json = nlohmann::json; static std::shared_ptr<DSPatch::Component> create_component(std::string name, cmd_options* options) { if (name == "glb_z_reverse") { return std::make_shared<DSPatch::glb_z_reverse>(options); } else if (name == "glb_transforms_apply") { return std::make_shared<DSPatch::glb_transforms_apply>(options); } else if (name == "glb_jpeg_to_png") { return std::make_shared<DSPatch::glb_jpeg_to_png>(options); } else if (name == "glb_fix_roll") { return std::make_shared<DSPatch::glb_fix_roll>(options); } else if (name == "glb_T_pose") { return std::make_shared<DSPatch::glb_T_pose>(options); } else if (name == "glb_overrides") { return std::make_shared<DSPatch::glb_overrides>(options); } else if (name == "vrm0_fix_joint_buffer") { return std::make_shared<DSPatch::vrm0_fix_joint_buffer>(options); } else if (name == "vrm0_default_extensions") { return std::make_shared<DSPatch::vrm0_default_extensions>(options); } else if (name == "vrm0_remove_extensions") { return std::make_shared<DSPatch::vrm0_remove_extensions>(options); } else if (name == "fbx2gltf_execute") { return std::make_shared<DSPatch::fbx2gltf_execute>(options); } else if (name == "gltfpack_execute") { return std::make_shared<DSPatch::gltfpack_execute>(options); } return std::make_shared<DSPatch::noop>(options, name); } static std::shared_ptr<pipeline_processor> create_pipeline(std::string name, cmd_options* options) { if (name == "gltf_pipeline") { return std::make_shared<AvatarBuild::gltf_pipeline>(name, options); } else if (name == "fbx_pipeline") { return std::make_shared<AvatarBuild::fbx_pipeline>(name, options); } else if (name == "gltfpack_pipeline") { return std::make_shared<AvatarBuild::gltfpack_pipeline>(name, options); } return std::make_shared<AvatarBuild::pipeline_processor>(name, options); } static std::shared_ptr<pipeline_processor> wire_pipeline(pipeline* p, cmd_options* options) { const auto pipeline = create_pipeline(p->name, options); for (size_t i = 0; i < p->components.size(); ++i) { pipeline->add_component(create_component(p->components[i], options)); } pipeline->wire_components(); return pipeline; } static bool build_and_start_circuits(cmd_options* options, json config_json) { try { const auto& pipelines_obj = config_json["pipelines"]; if (!pipelines_obj.is_array()) { std::cout << "[ERROR] pipeline '" << config_json["name"] << "' is not an array" << std::endl; return false; } auto circuit = std::make_shared<DSPatch::Circuit>(); std::vector<std::shared_ptr<pipeline_processor>> pipelines; for (const auto& obj : pipelines_obj) { pipeline p; p.name = obj["name"]; p.components = json_get_string_items("components", obj); auto component = wire_pipeline(&p, options); circuit->AddComponent(component); if (!pipelines.empty()) { circuit->ConnectOutToIn(pipelines.back(), 0, component, 0); } pipelines.push_back(component); } // make sure to execute pipeline in TickMode::Series // because pipeline has state and not thread safe. circuit->Tick(DSPatch::Component::TickMode::Series); // Check if pipeline has failure for (const auto pipeline : pipelines) { if (pipeline->is_discarded()) return false; } return true; } catch (json::exception& e) { std::cout << "[ERROR] error while parsing pipeline '" << config_json["name"] << "'" << std::endl; std::cout << "\t " << e.what() << std::endl; return false; } } static bool start_pipelines(cmd_options* options) { json config_json; if (!json_parse(options->config, &config_json)) { return false; } if (options->verbose) { std::cout << "[INFO] Starting pipeline '" << config_json["name"] << "'" << std::endl; std::cout << "[INFO] " << config_json["description"] << std::endl; } return build_and_start_circuits(options, config_json); } int main(int argc, char** argv) { CLI::App app { "avatar-build: Run avatar asset pipeline" }; std::string config = "pipelines/config.json"; app.add_option("-p,--pipeline", config, "Pipeline configuration file name (JSON)")->required(); bool verbose = false; app.add_flag("-v,--verbose", verbose, "Verbose log output"); bool debug = false; app.add_flag("-d,--debug", debug, "Enable debug output"); std::string input; app.add_option("-i,--input", input, "Input file name")->check(CLI::ExistingFile)->required(); std::string output; app.add_option("-o,--output", output, "Output file name")->required(); std::string input_config; app.add_option("-m,--input_config", input_config, "Input configuration file name (JSON)"); std::string output_config; app.add_option("-n,--output_config", output_config, "Output configuration file name (JSON)"); std::string fbx2gltf = "extern/fbx2gltf.exe"; app.add_option("-x,--fbx2gltf", fbx2gltf, "Path to fbx2gltf executable")->check(CLI::ExistingFile); CLI11_PARSE(app, argc, argv); // common mistake if (input == output) { AVATAR_PIPELINE_LOG("[ERROR] Input and Output file should not be same: " << input); return 1; } cgltf_options gltf_options = { }; // enable multibyte file name gltf_options.file.read = &gltf_file_read; // setup memory allocation check if (debug) { gltf_options.memory.alloc = &gltf_leakcheck_malloc; gltf_options.memory.free = &gltf_leackcheck_free; pipeline_leackcheck_enabled = true; } pipeline_verbose_enabled = verbose; cmd_options options = { config, input, output, input_config, output_config, fbx2gltf, verbose, debug, gltf_options }; if (!options.input_config.empty() && !json_parse(options.input_config, &options.input_config_json)) { AVATAR_PIPELINE_LOG("[ERROR] Unable to load " << options.input_config); return 1; } if (!options.output_config.empty() && !json_parse(options.output_config, &options.output_config_json)) { AVATAR_PIPELINE_LOG("[ERROR] Unable to load " << options.output_config); return 1; } int status = 0; if (!start_pipelines(&options)) { status = 1; } if (debug && stb_leakcheck_dumpmem()) { status = 1; } return status; }
[ "developer@infosia.co.jp" ]
developer@infosia.co.jp
276919294e86ebff18ec203a0eb9641bbc76d43a
c0caed81b5b3e1498cbca4c1627513c456908e38
/src/protocols/magnesium/util.hh
3b584d6c98a5fffa48ff21eed574296a0fd3f78b
[]
no_license
malaifa/source
5b34ac0a4e7777265b291fc824da8837ecc3ee84
fc0af245885de0fb82e0a1144422796a6674aeae
refs/heads/master
2021-01-19T22:10:22.942155
2017-04-19T14:13:07
2017-04-19T14:13:07
88,761,668
0
2
null
null
null
null
UTF-8
C++
false
false
4,300
hh
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington UW TechTransfer, email: license@u.washington.edu. /// @file protocols/magnesium/util.hh /// @brief /// @details /// @author Rhiju Das, rhiju@stanford.edu #ifndef INCLUDED_protocols_magnesium_util_HH #define INCLUDED_protocols_magnesium_util_HH #include <protocols/magnesium/params.hh> #include <core/conformation/Residue.fwd.hh> #include <core/chemical/ResidueTypeSet.fwd.hh> #include <core/id/AtomID.fwd.hh> #include <core/pose/Pose.fwd.hh> #include <core/scoring/ScoreFunction.fwd.hh> #include <core/types.hh> #include <numeric/UniformRotationSampler.fwd.hh> #include <utility/vector1.fwd.hh> #include <map> namespace protocols { namespace magnesium { void fixup_magnesiums( core::pose::Pose & pose ); void hydrate_magnesiums( core::pose::Pose & pose, bool use_virtual_waters_as_placeholders = true, bool test_all_mg_hydration_frames = false ); core::scoring::ScoreFunctionOP get_mg_scorefxn(); numeric::UniformRotationSamplerCOP get_water_uniform_rotation_sampler(); numeric::UniformRotationSamplerCOP get_octahedral_uniform_rotation_sampler( core::Real const rotstep = 2.5, bool const remove_redundant = false ); core::conformation::ResidueOP get_useful_HOH_coords( core::Vector & Oc, core::Vector & OH1c, core::Vector & OH2c, core::chemical::ResidueTypeSet const & residue_set ); void add_single_magnesium( core::pose::Pose & pose ); void strip_out_magnesiums( core::pose::Pose & pose ); std::map< core::Size, utility::vector1< core::Size > > define_mg_water_map( core::pose::Pose const & pose ); utility::vector1< std::pair< core::Size, core::Size > > get_mg_water_pairs( core::pose::Pose const & pose, bool const exclude_virtual_waters = true ) ; utility::vector1< std::pair< core::Size, core::Size > > get_mg_water_pairs( core::pose::Pose const & pose, utility::vector1< core::Size > const & mg_res, bool const exclude_virtual_waters = true ) ; utility::vector1< core::id::AtomID > get_mg_ligands( core::pose::Pose const & pose, core::Size const i, bool const filter_for_acceptors = true, bool const exclude_virtual_waters = true ); utility::vector1< core::id::AtomID > filter_acceptor_ligands( core::pose::Pose const & pose, utility::vector1< core::id::AtomID > const & ligands ); core::Size instantiate_water_at_octahedral_vertex( core::pose::Pose & pose, core::Size const mg_res, core::Size const n /* 1 ... 6*/, core::Distance const hoh_distance = MG_HOH_DISTANCE, bool const replace_residue = false, bool const virtual_water = false ); void update_jump_atoms_for_mg_bound_water( core::pose::Pose & pose, core::Size const n ); core::Size append_mg_bound_water( core::pose::Pose & pose, core::conformation::Residue const & rsd, core::Size const mg_res ); utility::vector1< core::Size > find_bound_waters_that_are_daughters_in_fold_tree( core::pose::Pose const & pose, core::Size const mg_res ); core::conformation::ResidueOP get_mg_rsd(); utility::vector1< core::Size > get_mg_res( core::pose::Pose const & pose ); utility::vector1< core::Size > get_water_res( core::pose::Pose const & pose ); void remove_waters_except_mg_bound( core::pose::Pose & pose, utility::vector1< std::pair< core::Size, core::Size > > const & mg_water_pairs ); void remove_mg_bound_waters( core::pose::Pose & pose, utility::vector1< core::Size > const & mg_res, bool const leave_other_waters = false ); void update_numbers_in_pdb_info( core::pose::Pose & pose, bool const reset_waters = false ); utility::vector1< core::Size > pdbslice( core::pose::Pose & pose, core::Size const center_res, core::Distance distance_cutoff = 12.0 ); void get_hydration_stats( core::pose::Pose const & pose, core::pose::Pose const & reference_pose, utility::vector1< core::Size > const & pdb_mg_res_list_in, std::string const & outfile ); } //magnesium } //protocols #endif
[ "malaifa@yahoo.com" ]
malaifa@yahoo.com
1606340f92905f1b86bf45eb45d421573d7dcd20
56d1226dfefc93768a5f60ce15d1d7ca9bd58a08
/ddraw/IDirectDrawGammaControl.cpp
e9abe7fe5463388d979ca4b5f2501f08ee306f58
[ "Zlib", "GPL-1.0-or-later" ]
permissive
elishacloud/dxwrapper
ef6e047a6c49b98b74bf0adcff80740e8c0fff42
258bc970a72c7a4bd89449527a537e6912acbfb3
refs/heads/master
2023-08-17T06:13:06.649077
2023-08-16T21:17:18
2023-08-16T21:17:18
81,271,358
968
83
Zlib
2023-08-22T19:56:05
2017-02-08T00:58:26
C
UTF-8
C++
false
false
3,592
cpp
/** * Copyright (C) 2023 Elisha Riedlinger * * 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. */ #include "ddraw.h" HRESULT m_IDirectDrawGammaControl::QueryInterface(REFIID riid, LPVOID FAR * ppvObj) { Logging::LogDebug() << __FUNCTION__ << " (" << this << ") " << riid; if (!ppvObj) { return E_POINTER; } if (riid == IID_GetRealInterface) { *ppvObj = ProxyInterface; return DD_OK; } if (ppvObj && riid == IID_GetInterfaceX) { *ppvObj = this; return DD_OK; } if (riid == IID_IDirectDrawGammaControl || riid == IID_IUnknown) { AddRef(); *ppvObj = this; return DD_OK; } return ProxyQueryInterface(ProxyInterface, riid, ppvObj, WrapperID); } ULONG m_IDirectDrawGammaControl::AddRef() { Logging::LogDebug() << __FUNCTION__ << " (" << this << ")"; if (!ProxyInterface) { return InterlockedIncrement(&RefCount); } return ProxyInterface->AddRef(); } ULONG m_IDirectDrawGammaControl::Release() { Logging::LogDebug() << __FUNCTION__ << " (" << this << ")"; ULONG ref; if (!ProxyInterface) { ref = InterlockedDecrement(&RefCount); } else { ref = ProxyInterface->Release(); } if (ref == 0) { delete this; } return ref; } HRESULT m_IDirectDrawGammaControl::GetGammaRamp(DWORD dwFlags, LPDDGAMMARAMP lpRampData) { Logging::LogDebug() << __FUNCTION__ << " (" << this << ")"; if (!ProxyInterface) { if (!lpRampData) { return DDERR_INVALIDPARAMS; } if (dwFlags & DDSGR_CALIBRATE) { LOG_LIMIT(100, __FUNCTION__ << " Warning: Calibrating gamma ramps is not Implemented"); } *lpRampData = RampData; return DD_OK; } return ProxyInterface->GetGammaRamp(dwFlags, lpRampData); } HRESULT m_IDirectDrawGammaControl::SetGammaRamp(DWORD dwFlags, LPDDGAMMARAMP lpRampData) { Logging::LogDebug() << __FUNCTION__ << " (" << this << ")"; if (!ProxyInterface) { if (!(dwFlags || dwFlags == DDSGR_CALIBRATE) || !lpRampData) { return DDERR_INVALIDPARAMS; } RampData = *lpRampData; // Present new gamma setting if (ddrawParent) { ddrawParent->SetVsync(); SetCriticalSection(); m_IDirectDrawSurfaceX *lpDDSrcSurfaceX = ddrawParent->GetPrimarySurface(); if (lpDDSrcSurfaceX) { lpDDSrcSurfaceX->PresentSurface(false); } ReleaseCriticalSection(); } return DD_OK; } return ProxyInterface->SetGammaRamp(dwFlags, lpRampData); } /************************/ /*** Helper functions ***/ /************************/ void m_IDirectDrawGammaControl::InitGammaControl() { // Initialize gamma control for (int x = 0; x < 256; x++) { RampData.red[x] = 255; RampData.green[x] = 255; RampData.blue[x] = 255; } } void m_IDirectDrawGammaControl::ReleaseGammaControl() { if (ddrawParent && !Config.Exiting) { ddrawParent->ClearGammaInterface(); } }
[ "elisha@novicemail.com" ]
elisha@novicemail.com
129f655f81b1652dacade23e78bb23d6b4a8d3d1
258cc0f1875b16d8ec8e75592be90f79e59a9fe0
/Onboard-SDK-ROS-4.0.1/include/dji_osdk_ros/payload_device_node.h
f94977e43587cb74186dc4ab51c659d32c90e8fc
[]
no_license
CatchACat083/Onboard-SDK-ROS_Detection-Geolocation
93cf2085352ce64c8b3d2ba4e8cf3e167c907add
020649a3790b1bac16196be21333b33073f2b36a
refs/heads/master
2023-03-03T04:54:03.265372
2021-02-02T08:55:13
2021-02-02T08:55:13
335,208,771
5
2
null
null
null
null
UTF-8
C++
false
false
1,761
h
/** @file payload_device_node.h * @version 4.0 * @date May 2020 * * @brief sample node of payload device. * * @Copyright (c) 2020 DJI * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #ifndef SRC_PAYLOAD_DEVICE_NODE_H #define SRC_PAYLOAD_DEVICE_NODE_H //include #include <ros/ros.h> #include <dji_osdk_ros/dji_vehicle_node.h> using namespace dji_osdk_ros; //const #define TEST_DATA_0 0x32 #define TEST_DATA_1 0x33 //service ros::ServiceClient send_to_payload_data_client; ros::Subscriber fromPayloadData; //function bool sendToPayload(dji_osdk_ros::SendPayloadData sendPayloadData); void fromPayloadDataSubCallback(const dji_osdk_ros::PayloadData::ConstPtr& fromPayloadData); #endif //SRC_PAYLOAD_DEVICE_NODE_H
[ "linbosen083@gmail.com" ]
linbosen083@gmail.com
3344b25e5d6c9b7e4d5efeb965bf7ccf50a67f77
0958cceb81de1c7ee74b0c436b800a1dc54dd48a
/wincewebkit/WebKit2/Shared/Plugins/NPIdentifierData.cpp
61ebbbe0fd2710d5866a481edfd33fbf9e105258
[]
no_license
datadiode/WinCEWebKit
3586fac69ba7ce9efbde42250266ddbc5c920c5e
d331d103dbc58406ed610410736b59899d688632
refs/heads/master
2023-03-15T23:47:30.374484
2014-08-14T14:41:13
2014-08-14T14:41:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,060
cpp
/* * Copyright (C) 2010 Apple Inc. 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. */ #if ENABLE(PLUGIN_PROCESS) #include "NPIdentifierData.h" #include "ArgumentDecoder.h" #include "ArgumentEncoder.h" #include "NotImplemented.h" #include "WebCoreArgumentCoders.h" #include <WebCore/IdentifierRep.h> using namespace WebCore; namespace WebKit { NPIdentifierData::NPIdentifierData() : m_isString(false) , m_number(0) { } NPIdentifierData NPIdentifierData::fromNPIdentifier(NPIdentifier npIdentifier) { NPIdentifierData npIdentifierData; IdentifierRep* identifierRep = static_cast<IdentifierRep*>(npIdentifier); npIdentifierData.m_isString = identifierRep->isString(); if (npIdentifierData.m_isString) npIdentifierData.m_string = identifierRep->string(); else npIdentifierData.m_number = identifierRep->number(); return npIdentifierData; } NPIdentifier NPIdentifierData::createNPIdentifier() const { if (m_isString) return static_cast<NPIdentifier>(IdentifierRep::get(m_string.data())); return static_cast<NPIdentifier>(IdentifierRep::get(m_number)); } void NPIdentifierData::encode(CoreIPC::ArgumentEncoder* encoder) const { encoder->encode(m_isString); if (m_isString) encoder->encode(m_string); else encoder->encodeInt32(m_number); } bool NPIdentifierData::decode(CoreIPC::ArgumentDecoder* decoder, NPIdentifierData& result) { if (!decoder->decode(result.m_isString)) return false; if (result.m_isString) return decoder->decode(result.m_string); return decoder->decodeInt32(result.m_number); } } // namespace WebKit #endif // ENABLE(PLUGIN_PROCESS)
[ "achellies@163.com" ]
achellies@163.com
916137b2f04c905ba78573593d5a1c57e33b4b9b
002371578ec2ec1a35e1b30a9413a29b7bed8e25
/item.h
9a774efc878474bb1141c7ab75cd42b1d2754ce9
[]
no_license
marcokstephen/bbchallenge
a165f1ce9f5df1a5850414818cf88d8a27a8fd80
ed1b78a430c1030f0e2209f4c79a3219109d891b
refs/heads/master
2022-01-06T15:24:47.546667
2019-07-20T20:43:50
2019-07-20T20:43:50
197,978,987
0
0
null
null
null
null
UTF-8
C++
false
false
625
h
#ifndef INCLUDED_ITEM_H #define INCLUDED_ITEM_H #include <sstream> class Item { public: Item(char key, int row, int column, int attack, int defense); const char& key() const; int& row(); int& column(); int& attack(); int& defense(); bool& equipped(); private: char d_key; int d_row; int d_column; int d_attack; int d_defense; bool d_equipped; }; inline std::ostream& operator<<(std::ostream& oss, Item& rhs) { oss << "[[" << rhs.row() << "," << rhs.column() << "]," << (rhs.equipped() ? "true" : "false") << "]"; return oss; } #endif // INCLUDED_ITEM_H
[ "marcok.stephen@gmail.com" ]
marcok.stephen@gmail.com
31ba776b650406ec8bd41343e4ee8039eec72f8a
f621325245a4157d3d4c363095b43ae522da44d0
/W3/insertionSort.cpp
94b1dcf368c70b2c261e062377cdc2796db59999
[]
no_license
shlokalm/DAA
7951f83923be2ac41c489fb8b3ed6276efb037c2
a7c7e57f9d9c90e2744012e05ef5bfbef045cbea
refs/heads/main
2023-08-26T19:58:26.402064
2021-11-12T16:38:10
2021-11-12T16:38:10
386,038,937
0
0
null
null
null
null
UTF-8
C++
false
false
733
cpp
#include <bits/stdc++.h> using namespace std; void insort(int *ar, int n) { int i,j; int comps = 0, shifts = 0, key; for (i=1;i<n;i++) { key = ar[i]; j = i-1; while (j>=0 && ar[j]>key) { comps ++; shifts ++; ar[j+1] = ar[j]; j--; } shifts ++; ar[j+1] = key; } for(i=0;i<n;i++) cout << ar[i] << " "; cout << endl; cout << "comparisons = " << comps; cout << "shifts = " << shifts; } int main() { int t; cin >> t; while (t--) { int i, n; cin >> n; int ar[n]; for (i=0;i<n;i++) cin >> ar[i]; insort (ar,n); } return 0; }
[ "shlokbishtalm@gmail.com" ]
shlokbishtalm@gmail.com
b365350a6cf92ea947b8d971c74cd45d4c7fd3a4
3eb180a2400c7b1829664a39375f69cc24d1f0b8
/src/net/drivers/input/inputdriver.h
5c17f7423b3f241b8abe8e3dec46fda3a42382d4
[]
no_license
skifcorp/amigo
86b3ca3190f9951178ce3be641f1e6b05c7dec8f
e1c417286b0bd0077e97f6dd856ad5bca489987b
refs/heads/master
2021-01-10T03:22:20.551290
2016-02-15T06:27:40
2016-02-15T06:28:06
51,735,393
0
0
null
null
null
null
UTF-8
C++
false
false
996
h
#ifndef __INPUT_H_ #define __INPUT_H_ #include "inputconnection.h" #include <memory> #include <set> using std::set; using std::shared_ptr; class InputDriver; typedef shared_ptr<InputDriver> InputDriverPtr; class InputDrivers { public: InputDrivers (){} void append (InputDriverPtr p) { drivers.insert (p); } void remove (InputDriverPtr p) { drivers.erase (p); } private: set<InputDriverPtr> drivers; }; class InputDriver : public std::enable_shared_from_this<InputDriver> { public: InputDriver(InputDrivers& dr) : drivers (dr) {} typedef InputDriverPtr pointer; virtual ~InputDriver() {} void start (InputConnection::pointer p) { drivers.append (shared_from_this()); start_(p); } void stop () { //assert (0); stop_(); drivers.remove (shared_from_this()); } protected: //workspace & ws private: InputDrivers & drivers; virtual void start_(InputConnection::pointer p) = 0; virtual void stop_() = 0; }; #endif
[ "amotsok@gmail.com" ]
amotsok@gmail.com
55d689174c2b98057a28ced3efb25e2c6f9e7afc
f3a35f1e9d803a1ad409bec1e58024e825f87141
/08/GraduDeMIS/GraduDeMIS.cpp
8419023ea474941e5fd15c973508021127da7021
[]
no_license
xuezchuang/C-Project
ed4406f913e853b981063e726ab505ada36b1f90
4d5a64429fde2d37ba77974dd6cf7526833e55be
refs/heads/master
2020-03-24T20:04:26.082584
2017-11-14T10:11:40
2017-11-14T10:11:40
null
0
0
null
null
null
null
GB18030
C++
false
false
3,054
cpp
// GraduDeMIS.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "GraduDeMIS.h" #include "GraduDeMISDlg.h" #include "odbcinst.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif CString selectID; CString strExternUser; bool bstuExternFlag,btecrExternFlag,badminExternFlag; ///////////////////////////////////////////////////////////////////////////// // CGraduDeMISApp BEGIN_MESSAGE_MAP(CGraduDeMISApp, CWinApp) //{{AFX_MSG_MAP(CGraduDeMISApp) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG ON_COMMAND(ID_HELP, CWinApp::OnHelp) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CGraduDeMISApp construction CGraduDeMISApp::CGraduDeMISApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } ///////////////////////////////////////////////////////////////////////////// // The one and only CGraduDeMISApp object CGraduDeMISApp theApp; ///////////////////////////////////////////////////////////////////////////// // CGraduDeMISApp initialization BOOL CGraduDeMISApp::InitInstance() { AfxEnableControlContainer(); CString sPath; //保存数据库文件路径名 GetModuleFileName(NULL,sPath.GetBufferSetLength (MAX_PATH+1),MAX_PATH);//为sPath分配存储空间 sPath.ReleaseBuffer(); int nPos; nPos=sPath.ReverseFind('\\');//逆序查找字符 sPath=sPath.Left(nPos);//获取文件的路径 nPos=sPath.ReverseFind('\\'); sPath=sPath.Left(nPos);//获取文件的路径 CString lpszFileName = sPath + "\\db_gradu.mdb";//保存数据库文件名称 CFileFind fFind; if(!fFind.FindFile(lpszFileName)) { ::AfxMessageBox("没有找到数据库"); exit(0); } CString szDesc;//保存对数据源的描述 szDesc.Format( "DSN=GraduDeMIS;FIL=Microsoft Access;DEFAULTDIR=%s;DBQ=%s;" ,sPath,lpszFileName); //添加数据源 if(!::SQLConfigDataSource(NULL,ODBC_ADD_DSN, "Microsoft Access Driver (*.mdb)",(LPCSTR)szDesc)) { ::AfxMessageBox("32位ODBC数据源配置错误!"); exit(0); } // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking to MFC statically #endif CGraduDeMISDlg dlg; m_pMainWnd = &dlg; int nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }
[ "1182741213@qq.com" ]
1182741213@qq.com
0c508a0b8c0b2f64795c8581dff8e8229b7f7038
bbad11a2f0edc04125717ed0114d797148a93f89
/hcs08_programinstruction.cpp
2cc53a4291b5b8b8d8ee257b26cae700c029cbb3
[]
no_license
Brick1x1/MC9S08dbg
8716eba23591ed2af65e91fff2f33e01f35f84d7
5e6819e2316781abddec7be88eb1c38ce3675dc4
refs/heads/master
2023-02-16T21:22:16.164562
2020-11-01T21:24:32
2020-11-01T21:24:32
293,360,899
0
0
null
null
null
null
UTF-8
C++
false
false
390
cpp
#include <iostream> #include <string> #include <cstring> #include <cstdlib> #include "hcs08_programinstruction.h" using namespace std; hcs08_ProgramInstruction::hcs08_ProgramInstruction(unsigned short p_startAddr , char *p_disassembleText, int p_instructionLength) { startAddr = p_startAddr; strcpy(disassembleText,p_disassembleText); instructionLength = p_instructionLength; }
[ "jens.noergaard@outlook.com" ]
jens.noergaard@outlook.com
9eee9cd8f83184eaf7adae52df3bdbc3bbd38332
6559c9c66342c546f41ced1548d239fbfea0d7c9
/Ramjet_Core/Core/Managers/Mesh_Manager.h
2f98a52606b7cb21aa8ea72058b18baa4fa033c5
[]
no_license
Fox3medium/RamjetEngine
e8f3cdbd74dc3e846974ebd3f6fb6c12415d0808
1b6c83f51821d94a8b35720bc09d6a4d28741fa9
refs/heads/master
2022-01-28T13:54:55.575843
2019-07-17T21:45:24
2019-07-17T21:45:24
194,148,095
0
0
null
null
null
null
UTF-8
C++
false
false
1,169
h
#pragma once #include <CoreBasicInclude.h> #include <Core/Common.h> #include <Utils/types.h> #include <Utils/Maths/maths.h> #include <Rendering/Renderer/Buffers/VertexArray.h> #include <Rendering/Renderer/Models/Sprite.h> #include <Rendering/Renderer/Models/Mesh.h> #include <Rendering/Material/Material.h> namespace Core { using namespace Rendering; namespace Manager { class CORE_API Mesh_Manager { private: // TODO add meshes instead of sprites static std::map<String, Sprite*> m_Meshes; public: static void init(); static Sprite* add(const String& name, Sprite* sprite); static Sprite* getMesh(const String& name); static void clean(); static void fromFile(const String& name, const char* filePath); static VertexArray* CreateQuad(float x, float y, float width, float height); static VertexArray* CreateQuad(const Maths::vec2& position, const Maths::vec2& size); static Mesh* CreateCube(float size, MaterialInstance* material); static Mesh* CreatePlan(float width, float height, const Maths::vec3& normal, MaterialInstance* material); private: Mesh_Manager() {} ~Mesh_Manager() { clean(); } }; } }
[ "rmdirsudosu@gmail.com" ]
rmdirsudosu@gmail.com
f5a02604a882767e4156fe48c543298d5966c53b
6767c4eebaf795f478f5d8800b760d4c20131f84
/inference-engine/tests/functional/plugin/cpu/shared_tests_instances/low_precision_transformations/variadic_split_transformation.cpp
214f9f421f432f200d8806fd62ee4fcba07dd8f3
[ "Apache-2.0" ]
permissive
jgespino/openvino
4a9beb4e4beeae8a67bf3d3218505ccdacae1bec
38c41b1ee34797f6ab1c49bbcc0275bd214e39d2
refs/heads/master
2023-01-12T21:31:53.957655
2020-11-06T14:28:33
2020-11-06T14:28:33
289,012,265
0
0
Apache-2.0
2020-10-01T17:33:27
2020-08-20T13:22:35
null
UTF-8
C++
false
false
3,263
cpp
// Copyright (C) 2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <vector> #include <gtest/gtest.h> #include "low_precision_transformations/variadic_split_transformation.hpp" #include "common_test_utils/test_constants.hpp" using namespace LayerTestsDefinitions; namespace { const std::vector<ngraph::element::Type> netPrecisions = { ngraph::element::f32, // ngraph::element::f16 }; const std::vector<ngraph::pass::low_precision::LayerTransformation::Params> trasformationParamValues = { LayerTestsUtils::LayerTransformationParamsNGraphFactory::createParams().setUpdatePrecisions(true), // LayerTestsUtils::LayerTransformationParamsNGraphFactory::createParams().setUpdatePrecisions(false), LayerTestsUtils::LayerTransformationParamsNGraphFactory::createParamsI8I8(), LayerTestsUtils::LayerTransformationParamsNGraphFactory::createParamsU8I8() }; const std::vector<LayerTestsDefinitions::VariadicSplitTransformationParam> params{ // tensor quantization, split second dimension { { 256ul, ngraph::Shape{ }, { 0.f }, { 25.5f }, { 0.f }, { 25.5f / 2.f } }, 2, std::vector<size_t>{9, 7} }, // tensor quantization, split third dimension { { 256ul, ngraph::Shape{ 1, 1, 1, 1 }, { -12.8f }, { 12.7f }, { 0.f }, { 25.5f } }, -1, std::vector<size_t>{15, 1} }, // per-channel quantization with different values, per-channel split { { 256ul, ngraph::Shape{ 1, 3, 1, 1 }, { -127.f, 0.f, 128.f / 2.f }, { 128.f / 4.f, 128.f / 2.f, 128.f }, { 0.f, 0.f, 0.f }, { 255.f / 4.f, 255.f / 2.f, 255.f } }, 1, std::vector<size_t>{1, 1, 1} }, // per-channel quantization with different values, split third dimension { { 256ul, ngraph::Shape{ 1, 3, 1, 1 }, { -127.f, 0.f, 128.f / 2.f }, { 128.f / 4.f, 128.f / 2.f, 128.f }, { 0.f, 0.f, 0.f }, { 255.f / 4.f, 255.f / 2.f, 255.f } }, -1, std::vector<size_t>{4, 3, 2, 7} }, // per-channel quantization with the same values, per-channel split { { 256ul, ngraph::Shape{ 1, 3, 1, 1 }, { -127.f, -127.f, -127.f }, { 128.f, 128.f, 128.f }, { 0.f, 0.f, 0.f }, { 255.f, 255.f, 255.f } }, 1, std::vector<size_t>{1, 1, 1} }, // per-channel quantization with the same values, split third dimension { { 256ul, ngraph::Shape{ 1, 3, 1, 1 }, { -127.f, -127.f, -127.f }, { 128.f, 128.f, 128.f }, { 0.f, 0.f, 0.f }, { 255.f, 255.f, 255.f } }, -1, std::vector<size_t>{4, 3, 2, 7} }, }; INSTANTIATE_TEST_CASE_P(LPT, VariadicSplitTransformation, ::testing::Combine( ::testing::ValuesIn(netPrecisions), ::testing::Values(ngraph::Shape({ 1, 3, 16, 16 })), ::testing::Values(CommonTestUtils::DEVICE_CPU), ::testing::ValuesIn(trasformationParamValues), ::testing::ValuesIn(params)), VariadicSplitTransformation::getTestCaseName); } // namespace
[ "noreply@github.com" ]
noreply@github.com
a7916afdcd20b13f6f9bbd9b75b819feb653b164
0219c8953c98eebccba7957ad0ca371403aa225a
/framework/include/cgv/base/base.h
a85c2141d1ec1e2039f9bfa44536df2ae5014c67
[]
no_license
TomKopp/CG1
6db282a2b73fcff6a08eb53fbf08c91ac884c25c
857ee13f7a911c506bb9b20cb5600d3097d62b83
refs/heads/master
2023-02-06T12:01:08.379385
2020-12-26T15:49:29
2020-12-26T15:49:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,943
h
#pragma once #include <cgv/type/info/type_name.h> #include <cgv/reflect/reflection_handler.h> #include <cgv/data/ref_ptr.h> #include <iostream> #include <cgv/type/lib_begin.h> namespace cgv { namespace type { namespace info { struct CGV_API type_interface; /// pointer to const type interface typedef cgv::data::ref_ptr<const type_interface,true> const_type_ptr; } } } #include <cgv/config/lib_end.h> #include "lib_begin.h" /// the cgv namespace namespace cgv { /// the base namespace holds the base hierarchy, support for plugin registration and signals namespace base { class CGV_API base; class CGV_API named; class CGV_API node; class CGV_API group; /// ref counted pointer to base typedef data::ref_ptr<base,true> base_ptr; struct cast_helper_base { template <class T> static data::ref_ptr<T,true> cast_of_base(base* b); }; template <class T> struct cast_helper : public cast_helper_base { inline static data::ref_ptr<T,true> cast(base* b) { return cast_of_base<T>(b); } }; /** base class for all classes that can be registered with support for dynamic properties (see also section \ref baseSEC of page \ref baseNS). */ class CGV_API base : public data::ref_counted, public cgv::reflect::self_reflection_tag { protected: /// give ref_ptr access to destructor friend class data::ref_ptr_impl<base,true>; /// make destructor virtual and not accessible from outside virtual ~base(); /// give cast_helper_base access to cast_dynamic friend struct cast_helper_base; /// use dynamic cast for upcast to given class template <class T> inline static data::ref_ptr<T,true> cast_dynamic(base* b) { return data::ref_ptr<T,true>(dynamic_cast<T*>(b)); } public: /// overload to return the type name of this object. By default the type interface is queried over get_type. virtual std::string get_type_name() const; /// overload to handle register events that is sent after the instance has been registered virtual void on_register(); /// overload to handle unregistration of instances virtual void unregister(); /// overload to show the content of this object virtual void stream_stats(std::ostream&); /// cast upward to named virtual data::ref_ptr<named,true> get_named(); /// cast upward to node virtual data::ref_ptr<node,true> get_node(); /// cast upward to group virtual data::ref_ptr<group,true> get_group(); /// cast to arbitrary class, but use the casts to named, node and group from the interface template <class T> data::ref_ptr<T,true> cast() { return cast_helper<T>::cast(this); } /// use dynamic type cast to check for the given interface template <class T> T* get_interface() { return dynamic_cast<T*>(this); } /// use dynamic type cast to check for the given interface template <class T> const T* get_const_interface() const { return dynamic_cast<const T*>(this); } /// this virtual update allows for example to ask a view to update the viewed value. The default implementation is empty. virtual void update(); /// this virtual method allows to pass application specific data for internal purposes virtual void* get_user_data() const; /**@name property interface*/ //@{ //! used for simple self reflection /*! The overloaded implementation is used by the default implementations of set_void, get_void and get_property_declarations with corresponding reflection handlers. The default implementation of self_reflect is empty. */ virtual bool self_reflect(cgv::reflect::reflection_handler&); //! return a semicolon separated list of property declarations /*! of the form "name1:type1;name2:type2;...", by default an empty list is returned. The types should by consistent with the names returned by cgv::type::info::type_name::get_name. The default implementation extracts names and types from the self_reflect() method and the meta type information provided by the get_type() method. */ virtual std::string get_property_declarations(); //! abstract interface for the setter of a dynamic property. /*! The default implementation uses the self_reflect() method to find a member with the given property as name. If not found, the set_void method returns false. */ virtual bool set_void(const std::string& property, const std::string& value_type, const void* value_ptr); /// this callback is called when the set_void method has changed a member and can be overloaded in derived class virtual void on_set(void* member_ptr); //! abstract interface for the getter of a dynamic property. /*! The default implementation uses the self_reflect() method to find a member with the given property as name. If not found, the get_void method returns false. */ virtual bool get_void(const std::string& property, const std::string& value_type, void* value_ptr); //! abstract interface to call an action /*! , i.e. a class method based on the action name and the given parameters. The default implementation uses the self_reflect() method to dispatch this call. If not found, the get_void method returns false.*/ virtual bool call_void(const std::string& method, const std::vector<std::string>& param_value_types, const std::vector<const void*>& param_value_ptrs, const std::string& result_type = "", void* result_value_ptr = 0); //! specialization of set method to support const char* as strings void set(const std::string& property, const char* value) { const std::string& s(value); set_void(property, cgv::type::info::type_name<std::string>::get_name(), &s); } //! set a property of the element to the given value and perform standard conversions if necessary. /*! This templated version simply extracts the type of the value from the reference and calls the set_void() method. Note that this only works if the template cgv::type::info::type_name<T> is overloaded for the value type. */ template <typename T> void set(const std::string& property, const T& value) { set_void(property, cgv::type::info::type_name<T>::get_name(), &value); } //! query a property of the element and perform standard conversions if necessary. /*! This templated version simply extracts the type of the value from the reference and calls the set_void() method. Note that this only works if the template cgv::type::info::type_name<T> is overloaded for the value type. */ template <typename T> T get(const std::string& property) { T value; get_void(property, cgv::type::info::type_name<T>::get_name(), &value); return value; } //! set several properties /*! , which are defined as colon separated assignments, where the types are derived automatically to bool, int, double or std::string. */ void multi_set(const std::string& property_assignments, bool report_error = true); //! check if the given name specifies a property. /*! If the type name string pointer is provided, the type of the property is copied to the referenced string. */ bool is_property(const std::string& property_name, std::string* type_name = 0); //! find a member pointer by name. /*! If not found the null pointer is returned. If the type name string pointer is provided, the type of the property is copied to the referenced string.*/ void* find_member_ptr(const std::string& property_name, std::string* type_name = 0); //@} }; template <typename T> inline data::ref_ptr<T,true> cast_helper_base::cast_of_base(base* b) { return base::cast_dynamic<T>(b); } #if _MSC_VER > 1400 #pragma warning(disable:4275) #pragma warning(disable:4231) #pragma warning(disable:4251) CGV_TEMPLATE template class CGV_API cgv::data::ref_ptr<cgv::base::base>; CGV_TEMPLATE template class CGV_API std::vector<cgv::data::ref_ptr<cgv::base::base> >; #endif } } #include <cgv/config/lib_end.h>
[ "witzbould@live.com" ]
witzbould@live.com
d135eb6123bdda61f9c9d9cf0e959f77d69d123d
5f9888aa5ea9a82dc3dd6254ef9284fbaf4ced75
/psp案例修改/main_public.h
b6893c30035806f2247a0f8e1993bd035ebf38ce
[]
no_license
xuqingjie/pspproject
a805f21e876c3977cae79b0e9117ec157cd55867
7f1373415f55cdfee79ff09024aa1944ab4ce27c
refs/heads/master
2021-01-22T17:34:02.885794
2016-06-05T00:36:33
2016-06-05T00:36:33
60,408,689
0
0
null
null
null
null
GB18030
C++
false
false
1,006
h
#pragma once /* 此模块作为时间日志记录的公共部分 主要实现的功能 1.定义公共类:时间日志记录 时间 记录名称 事件 时间id; 其他 想起来再说 作者:徐庆杰 时间:2016-5-30 修改历史:2016-5-30 创建 */ #include"public.h" //公共类的规定 struct Time { int year; int month; int day; int hour; int minute; }; class Timerecord { public: char title[100]; char incident[500]; Time s_time; Time e_time; int id; }; class index_file { public: Timerecord index_way; int id; }; //变量名称的修改******************************************************** typedef Timerecord * TimerecordPtr; //公共函数的规定******************************************************** /* 函数名称:事件日志记录的添加 作 者:徐庆杰 时 间:2016 6 4 功能描述:向内存中追加变量名称输入指针变量 输 入:时间日志记录型变量 输 出:? 返 回 值:时间日志记录的id */
[ "861538803@qq.com" ]
861538803@qq.com
42373cdb519390c51783be5088d91a4f4a255f0c
3e731150a1a5e5211eae36b163be2505fd55d6b3
/trabajo/include/latapeones.h
7df77c455b1d04d40e90ad458ef21b2e5826251f
[]
no_license
jesus-lop-puj/IG
2f19a8d056837fe72e0659685ab9027e7dead9e2
2045d97b0763802ab3c03482eb95c5245eb59762
refs/heads/main
2023-02-22T05:38:51.779491
2021-01-22T10:04:06
2021-01-22T10:04:06
316,946,154
0
0
null
null
null
null
UTF-8
C++
false
false
1,123
h
// Nombre: Jesús, Apellidos: López Pujazón, DNI/pasaporte: 26523483K (DDGG IG curso 20-21) #ifndef LATAPEONES_H #define LATAPEONES_H #include "objeto3d.h" #include "grafo-escena.h" class LataPeones: public NodoGrafoEscena{ public: LataPeones(); }; class PeonMadera: public NodoGrafoEscena{ public: PeonMadera(); }; class PeonBlanco: public NodoGrafoEscena{ public: PeonBlanco(); }; class PeonNegro: public NodoGrafoEscena{ public: PeonNegro(); }; class Lata: public NodoGrafoEscena{ public: Lata(); }; class TapaSuperiorLata: public NodoGrafoEscena{ public: TapaSuperiorLata(); }; class TapaInferiorLata: public NodoGrafoEscena{ public: TapaInferiorLata(); }; class CuerpoLata: public NodoGrafoEscena{ public: CuerpoLata(std::string nombre); }; //Práctica 5 class VariasLatasPeones: public NodoGrafoEscena{ public: VariasLatasPeones(); }; class LataPepsi: public NodoGrafoEscena{ public: LataPepsi(); }; class LataUGR: public NodoGrafoEscena{ public: LataUGR(); }; #endif
[ "jesuslopezpujazon@gmail.com" ]
jesuslopezpujazon@gmail.com
7acd49df8bc138b2ad1dadb96a7f46cad0217ca9
3e422f11c0c38087553f42891f05548081bc9f4d
/src/kll/Behaviours/Behaviour.cpp
a3ab308c491a9e40a5a4c5d060cfb8b43b47f643
[ "MIT" ]
permissive
damian0815/kll
75381e0ca6b878add71e659a29854815a3f313d2
85998f89c2a32f6678c0d5f2d2c2ca4819433e57
refs/heads/master
2021-01-12T09:10:30.623738
2017-04-03T19:24:19
2017-04-03T19:24:19
76,783,457
1
0
null
null
null
null
UTF-8
C++
false
false
74
cpp
// // Created by Damian Stewart on 10/12/2016. // #include "Behaviour.h"
[ "damian@frey.NOSPAMco.nz" ]
damian@frey.NOSPAMco.nz
f1d0397c6331e7352cf0dded1ba9df160eb5f462
86ecdaacf878288c9bd6a1656b5fc33283849498
/GuiLite.h
71d1ec509d4297b0de139c205c30e7441712e01a
[]
no_license
perseverance51/c_star
90e66660378d92607d3f43514b9141cfc0f6c049
015325c971df344ea4be48e8f02b0b521d9b1172
refs/heads/master
2023-07-04T07:02:27.275605
2021-08-07T02:54:19
2021-08-07T02:54:19
393,560,135
0
0
null
null
null
null
UTF-8
C++
false
false
125,321
h
#pragma once #define REAL_TIME_TASK_CYCLE_MS 50 #define MAX(a,b) (((a)>(b))?(a):(b)) #define MIN(a,b) (((a)<(b))?(a):(b)) #define GL_ARGB(a, r, g, b) ((((unsigned int)(a)) << 24) | (((unsigned int)(r)) << 16) | (((unsigned int)(g)) << 8) | ((unsigned int)(b))) #define GL_ARGB_A(rgb) ((((unsigned int)(rgb)) >> 24) & 0xFF) #define GL_RGB(r, g, b) ((0xFF << 24) | (((unsigned int)(r)) << 16) | (((unsigned int)(g)) << 8) | ((unsigned int)(b))) #define GL_RGB_R(rgb) ((((unsigned int)(rgb)) >> 16) & 0xFF) #define GL_RGB_G(rgb) ((((unsigned int)(rgb)) >> 8) & 0xFF) #define GL_RGB_B(rgb) (((unsigned int)(rgb)) & 0xFF) #define GL_RGB_32_to_16(rgb) (((((unsigned int)(rgb)) & 0xFF) >> 3) | ((((unsigned int)(rgb)) & 0xFC00) >> 5) | ((((unsigned int)(rgb)) & 0xF80000) >> 8)) #define GL_RGB_16_to_32(rgb) ((0xFF << 24) | ((((unsigned int)(rgb)) & 0x1F) << 3) | ((((unsigned int)(rgb)) & 0x7E0) << 5) | ((((unsigned int)(rgb)) & 0xF800) << 8)) #define ALIGN_HCENTER 0x00000000L #define ALIGN_LEFT 0x01000000L #define ALIGN_RIGHT 0x02000000L #define ALIGN_HMASK 0x03000000L #define ALIGN_VCENTER 0x00000000L #define ALIGN_TOP 0x00100000L #define ALIGN_BOTTOM 0x00200000L #define ALIGN_VMASK 0x00300000L typedef struct { unsigned short year; unsigned short month; unsigned short date; unsigned short day; unsigned short hour; unsigned short minute; unsigned short second; }T_TIME; void register_debug_function(void(*my_assert)(const char* file, int line), void(*my_log_out)(const char* log)); void _assert(const char* file, int line); #define ASSERT(condition) \ do{ \ if(!(condition))_assert(__FILE__, __LINE__);\ }while(0) void log_out(const char* log); long get_time_in_second(); T_TIME second_to_day(long second); T_TIME get_time(); void start_real_timer(void (*func)(void* arg)); void register_timer(int milli_second, void func(void* param), void* param); unsigned int get_cur_thread_id(); void create_thread(unsigned long* thread_id, void* attr, void *(*start_routine) (void *), void* arg); void thread_sleep(unsigned int milli_seconds); int build_bmp(const char *filename, unsigned int width, unsigned int height, unsigned char *data); #define FIFO_BUFFER_LEN 1024 class c_fifo { public: c_fifo(); int read(void* buf, int len); int write(void* buf, int len); private: unsigned char m_buf[FIFO_BUFFER_LEN]; int m_head; int m_tail; void* m_read_sem; void* m_write_mutex; }; class c_rect { public: c_rect(){ m_left = m_top = m_right = m_bottom = -1; } c_rect(int left, int top, int width, int height) { set_rect(left, top, width, height); } void set_rect(int left, int top, int width, int height) { ASSERT(width > 0 && height > 0); m_left = left; m_top = top; m_right = left + width - 1; m_bottom = top + height -1; } bool pt_in_rect(int x, int y) const { return x >= m_left && x <= m_right && y >= m_top && y <= m_bottom; } int operator==(const c_rect& rect) const { return (m_left == rect.m_left) && (m_top == rect.m_top) && (m_right == rect.m_right) && (m_bottom == rect.m_bottom); } int width() const { return m_right - m_left + 1; } int height() const { return m_bottom - m_top + 1 ; } int m_left; int m_top; int m_right; int m_bottom; }; //BITMAP typedef struct struct_bitmap_info { unsigned short width; unsigned short height; unsigned short color_bits;//support 16 bits only const unsigned short* pixel_color_array; } BITMAP_INFO; //FONT typedef struct struct_lattice { unsigned int utf8_code; unsigned char width; const unsigned char* pixel_buffer; } LATTICE; typedef struct struct_lattice_font_info { unsigned char height; unsigned int count; LATTICE* lattice_array; } LATTICE_FONT_INFO; //Rebuild gui library once you change this file enum FONT_LIST { FONT_NULL, FONT_DEFAULT, FONT_CUSTOM1, FONT_CUSTOM2, FONT_CUSTOM3, FONT_CUSTOM4, FONT_CUSTOM5, FONT_CUSTOM6, FONT_MAX }; enum IMAGE_LIST { IMAGE_CUSTOM1, IMAGE_CUSTOM2, IMAGE_CUSTOM3, IMAGE_CUSTOM4, IMAGE_CUSTOM5, IMAGE_CUSTOM6, IMAGE_MAX }; enum COLOR_LIST { COLOR_WND_FONT, COLOR_WND_NORMAL, COLOR_WND_PUSHED, COLOR_WND_FOCUS, COLOR_WND_BORDER, COLOR_CUSTOME1, COLOR_CUSTOME2, COLOR_CUSTOME3, COLOR_CUSTOME4, COLOR_CUSTOME5, COLOR_CUSTOME6, COLOR_MAX }; class c_theme { public: static int add_font(FONT_LIST index, const void* font) { if (index >= FONT_MAX) { ASSERT(false); return -1; } s_font_map[index] = font; return 0; } static const void* get_font(FONT_LIST index) { if (index >= FONT_MAX) { ASSERT(false); return 0; } return s_font_map[index]; } static int add_image(IMAGE_LIST index, const void* image_info) { if (index >= IMAGE_MAX) { ASSERT(false); return -1; } s_image_map[index] = image_info; return 0; } static const void* get_image(IMAGE_LIST index) { if (index >= IMAGE_MAX) { ASSERT(false); return 0; } return s_image_map[index]; } static int add_color(COLOR_LIST index, const unsigned int color) { if (index >= COLOR_MAX) { ASSERT(false); return -1; } s_color_map[index] = color; return 0; } static const unsigned int get_color(COLOR_LIST index) { if (index >= COLOR_MAX) { ASSERT(false); return 0; } return s_color_map[index]; } private: static const void* s_font_map[FONT_MAX]; static const void* s_image_map[IMAGE_MAX]; static unsigned int s_color_map[COLOR_MAX]; }; #include <string.h> #include <stdio.h> #include <stdlib.h> #define SURFACE_CNT_MAX 6//root + pages typedef enum { Z_ORDER_LEVEL_0,//lowest graphic level Z_ORDER_LEVEL_1,//middle graphic level Z_ORDER_LEVEL_2,//highest graphic level Z_ORDER_LEVEL_MAX }Z_ORDER_LEVEL; struct EXTERNAL_GFX_OP { void(*draw_pixel)(int x, int y, unsigned int rgb); void(*fill_rect)(int x0, int y0, int x1, int y1, unsigned int rgb); }; class c_surface; class c_display { friend class c_surface; public: inline c_display(void* phy_fb, int display_width, int display_height, int surface_width, int surface_height, unsigned int color_bytes, int surface_cnt, EXTERNAL_GFX_OP* gfx_op = 0);//multiple surface or surface_no_fb inline c_display(void* phy_fb, int display_width, int display_height, c_surface* surface);//single custom surface inline c_surface* alloc_surface(Z_ORDER_LEVEL max_zorder, c_rect layer_rect = c_rect());//for multiple surfaces inline int swipe_surface(c_surface* s0, c_surface* s1, int x0, int x1, int y0, int y1, int offset); int get_width() { return m_width; } int get_height() { return m_height; } void* get_updated_fb(int* width, int* height, bool force_update = false) { if (width && height) { *width = get_width(); *height = get_height(); } if (force_update) { return m_phy_fb; } if (m_phy_read_index == m_phy_write_index) {//No update return 0; } m_phy_read_index = m_phy_write_index; return m_phy_fb; } int snap_shot(const char* file_name) { if (!m_phy_fb || (m_color_bytes !=2 && m_color_bytes != 4)) { return -1; } int width = get_width(); int height = get_height(); //16 bits framebuffer if (m_color_bytes == 2) { return build_bmp(file_name, width, height, (unsigned char*)m_phy_fb); } //32 bits framebuffer unsigned short* p_bmp565_data = new unsigned short[width * height]; unsigned int* p_raw_data = (unsigned int*)m_phy_fb; for (int i = 0; i < width * height; i++) { unsigned int rgb = *p_raw_data++; p_bmp565_data[i] = GL_RGB_32_to_16(rgb); } int ret = build_bmp(file_name, width, height, (unsigned char*)p_bmp565_data); delete[]p_bmp565_data; return ret; } private: int m_width; //in pixels int m_height; //in pixels int m_color_bytes; //16 bits, 32 bits only void* m_phy_fb; //physical framebuffer int m_phy_read_index; int m_phy_write_index; c_surface* m_surface_group[SURFACE_CNT_MAX]; int m_surface_cnt; //surface count int m_surface_index; }; class c_layer { public: c_layer() { fb = 0; } void* fb; //framebuffer c_rect rect; //framebuffer area }; class c_surface { friend class c_display; friend class c_bitmap_operator; public: c_surface(unsigned int width, unsigned int height, unsigned int color_bytes, Z_ORDER_LEVEL max_zorder = Z_ORDER_LEVEL_0, c_rect overlpa_rect = c_rect()) : m_width(width), m_height(height), m_color_bytes(color_bytes), m_fb(0), m_is_active(false), m_top_zorder(Z_ORDER_LEVEL_0), m_phy_fb(0), m_phy_write_index(0), m_display(0) { (overlpa_rect == c_rect()) ? set_surface(max_zorder, c_rect(0, 0, width - 1, height - 1)) : set_surface(max_zorder, overlpa_rect); } int get_width() { return m_width; } int get_height() { return m_height; } unsigned int get_pixel(int x, int y, unsigned int z_order) { if (x >= m_width || y >= m_height || x < 0 || y < 0 || z_order >= Z_ORDER_LEVEL_MAX) { ASSERT(false); return 0; } if (m_layers[z_order].fb) { return (m_color_bytes == 4) ? ((unsigned int*)(m_layers[z_order].fb))[y * m_width + x] : GL_RGB_16_to_32(((unsigned short*)(m_layers[z_order].fb))[y * m_width + x]); } else if (m_fb) { return (m_color_bytes == 4) ? ((unsigned int*)m_fb)[y * m_width + x] : GL_RGB_16_to_32(((unsigned short*)m_fb)[y * m_width + x]); } else if (m_phy_fb) { return (m_color_bytes == 4) ? ((unsigned int*)m_phy_fb)[y * m_width + x] : GL_RGB_16_to_32(((unsigned short*)m_phy_fb)[y * m_width + x]); } return 0; } virtual void draw_pixel(int x, int y, unsigned int rgb, unsigned int z_order) { if (x >= m_width || y >= m_height || x < 0 || y < 0) { return; } if (z_order > (unsigned int)m_max_zorder) { ASSERT(false); return; } if (z_order == m_max_zorder) { return draw_pixel_on_fb(x, y, rgb); } if (z_order > (unsigned int)m_top_zorder) { m_top_zorder = (Z_ORDER_LEVEL)z_order; } if (m_layers[z_order].rect.pt_in_rect(x, y)) { c_rect layer_rect = m_layers[z_order].rect; if (m_color_bytes == 4) { ((unsigned int*)(m_layers[z_order].fb))[(x - layer_rect.m_left) + (y - layer_rect.m_top) * layer_rect.width()] = rgb; } else { ((unsigned short*)(m_layers[z_order].fb))[(x - layer_rect.m_left) + (y - layer_rect.m_top) * layer_rect.width()] = GL_RGB_32_to_16(rgb); } } if (z_order == m_top_zorder) { return draw_pixel_on_fb(x, y, rgb); } bool be_overlapped = false; for (unsigned int tmp_z_order = Z_ORDER_LEVEL_MAX - 1; tmp_z_order > z_order; tmp_z_order--) { if (m_layers[tmp_z_order].rect.pt_in_rect(x, y)) { be_overlapped = true; break; } } if (!be_overlapped) { draw_pixel_on_fb(x, y, rgb); } } virtual void fill_rect(int x0, int y0, int x1, int y1, unsigned int rgb, unsigned int z_order) { x0 = (x0 < 0) ? 0 : x0; y0 = (y0 < 0) ? 0 : y0; x1 = (x1 > (m_width - 1)) ? (m_width - 1) : x1; y1 = (y1 > (m_height - 1)) ? (m_height - 1) : y1; if (z_order == m_max_zorder) { return fill_rect_on_fb(x0, y0, x1, y1, rgb); } if (z_order == m_top_zorder) { int x, y; c_rect layer_rect = m_layers[z_order].rect; unsigned int rgb_16 = GL_RGB_32_to_16(rgb); for (y = y0; y <= y1; y++) { for (x = x0; x <= x1; x++) { if (layer_rect.pt_in_rect(x, y)) { if (m_color_bytes == 4) { ((unsigned int*)m_layers[z_order].fb)[(y - layer_rect.m_top) * layer_rect.width() + (x - layer_rect.m_left)] = rgb; } else { ((unsigned short*)m_layers[z_order].fb)[(y - layer_rect.m_top) * layer_rect.width() + (x - layer_rect.m_left)] = rgb_16; } } } } return fill_rect_on_fb(x0, y0, x1, y1, rgb); } for (; y0 <= y1; y0++) { draw_hline(x0, x1, y0, rgb, z_order); } } void draw_hline(int x0, int x1, int y, unsigned int rgb, unsigned int z_order) { for (; x0 <= x1; x0++) { draw_pixel(x0, y, rgb, z_order); } } void draw_vline(int x, int y0, int y1, unsigned int rgb, unsigned int z_order) { for (; y0 <= y1; y0++) { draw_pixel(x, y0, rgb, z_order); } } void draw_line(int x1, int y1, int x2, int y2, unsigned int rgb, unsigned int z_order) { int dx, dy, x, y, e; (x1 > x2) ? (dx = x1 - x2) : (dx = x2 - x1); (y1 > y2) ? (dy = y1 - y2) : (dy = y2 - y1); if (((dx > dy) && (x1 > x2)) || ((dx <= dy) && (y1 > y2))) { x = x2; y = y2; x2 = x1; y2 = y1; x1 = x; y1 = y; } x = x1; y = y1; if (dx > dy) { e = dy - dx / 2; for (; x1 <= x2; ++x1, e += dy) { draw_pixel(x1, y1, rgb, z_order); if (e > 0) { e -= dx; (y > y2) ? --y1 : ++y1; } } } else { e = dx - dy / 2; for (; y1 <= y2; ++y1, e += dx) { draw_pixel(x1, y1, rgb, z_order); if (e > 0) { e -= dy; (x > x2) ? --x1 : ++x1; } } } } void draw_rect(int x0, int y0, int x1, int y1, unsigned int rgb, unsigned int z_order, unsigned int size = 1) { for (unsigned int offset = 0; offset < size; offset++) { draw_hline(x0 + offset, x1 - offset, y0 + offset, rgb, z_order); draw_hline(x0 + offset, x1 - offset, y1 - offset, rgb, z_order); draw_vline(x0 + offset, y0 + offset, y1 - offset, rgb, z_order); draw_vline(x1 - offset, y0 + offset, y1 - offset, rgb, z_order); } } void draw_rect(c_rect rect, unsigned int rgb, unsigned int size, unsigned int z_order) { draw_rect(rect.m_left, rect.m_top, rect.m_right, rect.m_bottom, rgb, z_order, size); } void fill_rect(c_rect rect, unsigned int rgb, unsigned int z_order) { fill_rect(rect.m_left, rect.m_top, rect.m_right, rect.m_bottom, rgb, z_order); } int flush_screen(int left, int top, int right, int bottom) { if (left < 0 || left >= m_width || right < 0 || right >= m_width || top < 0 || top >= m_height || bottom < 0 || bottom >= m_height) { ASSERT(false); } if (!m_is_active || (0 == m_phy_fb) || (0 == m_fb)) { return -1; } int display_width = m_display->get_width(); int display_height = m_display->get_height(); left = (left >= display_width) ? (display_width - 1) : left; right = (right >= display_width) ? (display_width - 1) : right; top = (top >= display_height) ? (display_height - 1) : top; bottom = (bottom >= display_height) ? (display_height - 1) : bottom; for (int y = top; y < bottom; y++) { void* s_addr = (char*)m_fb + ((y * m_width + left) * m_color_bytes); void* d_addr = (char*)m_phy_fb + ((y * display_width + left) * m_color_bytes); memcpy(d_addr, s_addr, (right - left) * m_color_bytes); } *m_phy_write_index = *m_phy_write_index + 1; return 0; } bool is_active() { return m_is_active; } c_display* get_display() { return m_display; } int show_layer(c_rect& rect, unsigned int z_order) { ASSERT(z_order >= Z_ORDER_LEVEL_0 && z_order < Z_ORDER_LEVEL_MAX); c_rect layer_rect = m_layers[z_order].rect; ASSERT(rect.m_left >= layer_rect.m_left && rect.m_right <= layer_rect.m_right && rect.m_top >= layer_rect.m_top && rect.m_bottom <= layer_rect.m_bottom); void* fb = m_layers[z_order].fb; int width = layer_rect.width(); for (int y = rect.m_top; y <= rect.m_bottom; y++) { for (int x = rect.m_left; x <= rect.m_right; x++) { unsigned int rgb = (m_color_bytes == 4) ? ((unsigned int*)fb)[(x - layer_rect.m_left) + (y - layer_rect.m_top) * width] : GL_RGB_16_to_32(((unsigned short*)fb)[(x - layer_rect.m_left) + (y - layer_rect.m_top) * width]); draw_pixel_on_fb(x, y, rgb); } } return 0; } void set_active(bool flag) { m_is_active = flag; } protected: virtual void fill_rect_on_fb(int x0, int y0, int x1, int y1, unsigned int rgb) { int display_width = m_display->get_width(); int display_height = m_display->get_height(); if (m_color_bytes == 4) { int x; unsigned int* fb, * phy_fb; for (; y0 <= y1; y0++) { x = x0; fb = m_fb ? &((unsigned int*)m_fb)[y0 * m_width + x] : 0; phy_fb = &((unsigned int*)m_phy_fb)[y0 * display_width + x]; *m_phy_write_index = *m_phy_write_index + 1; for (; x <= x1; x++) { if (fb) { *fb++ = rgb; } if (m_is_active && (x < display_width) && (y0 < display_height)) { *phy_fb++ = rgb; } } } } else if (m_color_bytes == 2) { int x; unsigned short* fb, * phy_fb; rgb = GL_RGB_32_to_16(rgb); for (; y0 <= y1; y0++) { x = x0; fb = m_fb ? &((unsigned short*)m_fb)[y0 * m_width + x] : 0; phy_fb = &((unsigned short*)m_phy_fb)[y0 * display_width + x]; *m_phy_write_index = *m_phy_write_index + 1; for (; x <= x1; x++) { if (fb) { *fb++ = rgb; } if (m_is_active && (x < display_width) && (y0 < display_height)) { *phy_fb++ = rgb; } } } } } virtual void draw_pixel_on_fb(int x, int y, unsigned int rgb) { if (m_fb) { (m_color_bytes == 4) ? ((unsigned int*)m_fb)[y * m_width + x] = rgb : ((unsigned short*)m_fb)[y * m_width + x] = GL_RGB_32_to_16(rgb); } if (m_is_active && (x < m_display->get_width()) && (y < m_display->get_height())) { if (m_color_bytes == 4) { ((unsigned int*)m_phy_fb)[y * (m_display->get_width()) + x] = rgb; } else { ((unsigned short*)m_phy_fb)[y * (m_display->get_width()) + x] = GL_RGB_32_to_16(rgb); } *m_phy_write_index = *m_phy_write_index + 1; } } void attach_display(c_display* display) { ASSERT(display); m_display = display; m_phy_fb = display->m_phy_fb; m_phy_write_index = &display->m_phy_write_index; } void set_surface(Z_ORDER_LEVEL max_z_order, c_rect layer_rect) { m_max_zorder = max_z_order; if (m_display && (m_display->m_surface_cnt > 1)) { m_fb = calloc(m_width * m_height, m_color_bytes); } for (int i = Z_ORDER_LEVEL_0; i < m_max_zorder; i++) {//Top layber fb always be 0 ASSERT(m_layers[i].fb = calloc(layer_rect.width() * layer_rect.height(), m_color_bytes)); m_layers[i].rect = layer_rect; } } int m_width; //in pixels int m_height; //in pixels int m_color_bytes; //16 bits, 32 bits only void* m_fb; //frame buffer you could see c_layer m_layers[Z_ORDER_LEVEL_MAX];//all graphic layers bool m_is_active; //active flag Z_ORDER_LEVEL m_max_zorder; //the highest graphic layer the surface will have Z_ORDER_LEVEL m_top_zorder; //the current highest graphic layer the surface have void* m_phy_fb; //physical framebufer int* m_phy_write_index; c_display* m_display; }; class c_surface_no_fb : public c_surface {//No physical framebuffer, render with external graphic interface friend class c_display; public: c_surface_no_fb(unsigned int width, unsigned int height, unsigned int color_bytes, struct EXTERNAL_GFX_OP* gfx_op, Z_ORDER_LEVEL max_zorder = Z_ORDER_LEVEL_0, c_rect overlpa_rect = c_rect()) : c_surface(width, height, color_bytes, max_zorder, overlpa_rect), m_gfx_op(gfx_op) {} protected: virtual void fill_rect_on_fb(int x0, int y0, int x1, int y1, unsigned int rgb) { if (!m_gfx_op) { return; } if (m_gfx_op->fill_rect) { return m_gfx_op->fill_rect(x0, y0, x1, y1, rgb); } if (m_gfx_op->draw_pixel && m_is_active) { for (int y = y0; y <= y1; y++) { for (int x = x0; x <= x1; x++) { m_gfx_op->draw_pixel(x, y, rgb); } } } if (!m_fb) { return; } if (m_color_bytes == 4) { unsigned int* fb; for (int y = y0; y <= y1; y++) { fb = &((unsigned int*)m_fb)[y0 * m_width + x0]; for (int x = x0; x <= x1; x++) { *fb++ = rgb; } } } else if (m_color_bytes == 2) { unsigned short* fb; rgb = GL_RGB_32_to_16(rgb); for (int y = y0; y <= y1; y++) { fb = &((unsigned short*)m_fb)[y0 * m_width + x0]; for (int x = x0; x <= x1; x++) { *fb++ = rgb; } } } } virtual void draw_pixel_on_fb(int x, int y, unsigned int rgb) { if (m_gfx_op && m_gfx_op->draw_pixel && m_is_active) { m_gfx_op->draw_pixel(x, y, rgb); } if (!m_fb) { return; } if (m_color_bytes == 4) { ((unsigned int*)m_fb)[y * m_width + x] = rgb; } else if (m_color_bytes == 2) { ((unsigned short*)m_fb)[y * m_width + x] = GL_RGB_32_to_16(rgb); } } struct EXTERNAL_GFX_OP* m_gfx_op;//Rendering by external method }; inline c_display::c_display(void* phy_fb, int display_width, int display_height, int surface_width, int surface_height, unsigned int color_bytes, int surface_cnt, EXTERNAL_GFX_OP* gfx_op) : m_width(display_width), m_height(display_height), m_color_bytes(color_bytes), m_phy_fb(phy_fb), m_phy_read_index(0), m_phy_write_index(0), m_surface_cnt(surface_cnt), m_surface_index(0) { ASSERT(color_bytes == 2 || color_bytes == 4); ASSERT(m_surface_cnt <= SURFACE_CNT_MAX); memset(m_surface_group, 0, sizeof(m_surface_group)); for (int i = 0; i < m_surface_cnt; i++) { m_surface_group[i] = (phy_fb) ? new c_surface(surface_width, surface_height, color_bytes) : new c_surface_no_fb(surface_width, surface_height, color_bytes, gfx_op); m_surface_group[i]->attach_display(this); } } inline c_display::c_display(void* phy_fb, int display_width, int display_height, c_surface* surface) : m_width(display_width), m_height(display_height), m_phy_fb(phy_fb), m_phy_read_index(0), m_phy_write_index(0), m_surface_cnt(1), m_surface_index(0) { m_color_bytes = surface->m_color_bytes; surface->m_is_active = true; (m_surface_group[0] = surface)->attach_display(this); } inline c_surface* c_display::alloc_surface(Z_ORDER_LEVEL max_zorder, c_rect layer_rect) { ASSERT(max_zorder < Z_ORDER_LEVEL_MAX && m_surface_index < m_surface_cnt); (layer_rect == c_rect()) ? m_surface_group[m_surface_index]->set_surface(max_zorder, c_rect(0, 0, m_width - 1, m_height - 1)) : m_surface_group[m_surface_index]->set_surface(max_zorder, layer_rect); return m_surface_group[m_surface_index++]; } inline int c_display::swipe_surface(c_surface* s0, c_surface* s1, int x0, int x1, int y0, int y1, int offset) { int surface_width = s0->get_width(); int surface_height = s0->get_height(); if (offset < 0 || offset > surface_width || y0 < 0 || y0 >= surface_height || y1 < 0 || y1 >= surface_height || x0 < 0 || x0 >= surface_width || x1 < 0 || x1 >= surface_width) { ASSERT(false); return -1; } int width = (x1 - x0 + 1); if (width < 0 || width > surface_width || width < offset) { ASSERT(false); return -1; } x0 = (x0 >= m_width) ? (m_width - 1) : x0; x1 = (x1 >= m_width) ? (m_width - 1) : x1; y0 = (y0 >= m_height) ? (m_height - 1) : y0; y1 = (y1 >= m_height) ? (m_height - 1) : y1; if (m_phy_fb) { for (int y = y0; y <= y1; y++) { //Left surface char* addr_s = ((char*)(s0->m_fb) + (y * (s0->get_width()) + x0 + offset) * m_color_bytes); char* addr_d = ((char*)(m_phy_fb)+(y * m_width + x0) * m_color_bytes); memcpy(addr_d, addr_s, (width - offset) * m_color_bytes); //Right surface addr_s = ((char*)(s1->m_fb) + (y * (s1->get_width()) + x0) * m_color_bytes); addr_d = ((char*)(m_phy_fb)+(y * m_width + x0 + (width - offset)) * m_color_bytes); memcpy(addr_d, addr_s, offset * m_color_bytes); } } else if (m_color_bytes == 4) { void(*draw_pixel)(int x, int y, unsigned int rgb) = ((c_surface_no_fb*)s0)->m_gfx_op->draw_pixel; for (int y = y0; y <= y1; y++) { //Left surface for (int x = x0; x <= (x1 - offset); x++) { draw_pixel(x, y, ((unsigned int*)s0->m_fb)[y * m_width + x + offset]); } //Right surface for (int x = x1 - offset; x <= x1; x++) { draw_pixel(x, y, ((unsigned int*)s1->m_fb)[y * m_width + x + offset - x1 + x0]); } } } else if (m_color_bytes == 2) { void(*draw_pixel)(int x, int y, unsigned int rgb) = ((c_surface_no_fb*)s0)->m_gfx_op->draw_pixel; for (int y = y0; y <= y1; y++) { //Left surface for (int x = x0; x <= (x1 - offset); x++) { draw_pixel(x, y, GL_RGB_16_to_32(((unsigned short*)s0->m_fb)[y * m_width + x + offset])); } //Right surface for (int x = x1 - offset; x <= x1; x++) { draw_pixel(x, y, GL_RGB_16_to_32(((unsigned short*)s1->m_fb)[y * m_width + x + offset - x1 + x0])); } } } m_phy_write_index++; return 0; } #include <string.h> #include <stdio.h> #define VALUE_STR_LEN 16 class c_surface; class c_font_operator { public: virtual void draw_string(c_surface* surface, int z_order, const void* string, int x, int y, const void* font, unsigned int font_color, unsigned int bg_color) = 0; virtual void draw_string_in_rect(c_surface* surface, int z_order, const void* string, c_rect rect, const void* font, unsigned int font_color, unsigned int bg_color, unsigned int align_type = ALIGN_LEFT) = 0; virtual void draw_value(c_surface* surface, int z_order, int value, int dot_position, int x, int y, const void* font, unsigned int font_color, unsigned int bg_color) = 0; virtual void draw_value_in_rect(c_surface* surface, int z_order, int value, int dot_position, c_rect rect, const void* font, unsigned int font_color, unsigned int bg_color, unsigned int align_type = ALIGN_LEFT) = 0; virtual int get_str_size(const void* string, const void* font, int& width, int& height) = 0; void get_string_pos(const void* string, const void* font, c_rect rect, unsigned int align_type, int& x, int& y) { int x_size, y_size; get_str_size(string, font, x_size, y_size); int height = rect.m_bottom - rect.m_top + 1; int width = rect.m_right - rect.m_left + 1; x = y = 0; switch (align_type & ALIGN_HMASK) { case ALIGN_HCENTER: //m_text_org_x=0 if (width > x_size) { x = (width - x_size) / 2; } break; case ALIGN_LEFT: x = 0; break; case ALIGN_RIGHT: //m_text_org_x=0 if (width > x_size) { x = width - x_size; } break; default: ASSERT(0); break; } switch (align_type & ALIGN_VMASK) { case ALIGN_VCENTER: //m_text_org_y=0 if (height > y_size) { y = (height - y_size) / 2; } break; case ALIGN_TOP: y = 0; break; case ALIGN_BOTTOM: //m_text_org_y=0 if (height > y_size) { y = height - y_size; } break; default: ASSERT(0); break; } } }; class c_lattice_font_op : public c_font_operator { public: void draw_string(c_surface* surface, int z_order, const void* string, int x, int y, const void* font, unsigned int font_color, unsigned int bg_color) { const char* s = (const char*)string; if (0 == s) { return; } int offset = 0; unsigned int utf8_code; while (*s) { s += get_utf8_code(s, utf8_code); offset += draw_single_char(surface, z_order, utf8_code, (x + offset), y, (const LATTICE_FONT_INFO*)font, font_color, bg_color); } } void draw_string_in_rect(c_surface* surface, int z_order, const void* string, c_rect rect, const void* font, unsigned int font_color, unsigned int bg_color, unsigned int align_type = ALIGN_LEFT) { const char* s = (const char*)string; if (0 == s) { return; } int x, y; get_string_pos(s, (const LATTICE_FONT_INFO*)font, rect, align_type, x, y); draw_string(surface, z_order, string, rect.m_left + x, rect.m_top + y, font, font_color, bg_color); } void draw_value(c_surface* surface, int z_order, int value, int dot_position, int x, int y, const void* font, unsigned int font_color, unsigned int bg_color) { char buf[VALUE_STR_LEN]; value_2_string(value, dot_position, buf, VALUE_STR_LEN); draw_string(surface, z_order, buf, x, y, (const LATTICE_FONT_INFO*)font, font_color, bg_color); } void draw_value_in_rect(c_surface* surface, int z_order, int value, int dot_position, c_rect rect, const void* font, unsigned int font_color, unsigned int bg_color, unsigned int align_type = ALIGN_LEFT) { char buf[VALUE_STR_LEN]; value_2_string(value, dot_position, buf, VALUE_STR_LEN); draw_string_in_rect(surface, z_order, buf, rect, (const LATTICE_FONT_INFO*)font, font_color, bg_color, align_type); } int get_str_size(const void *string, const void* font, int& width, int& height) { const char* s = (const char*)string; if (0 == s || 0 == font) { width = height = 0; return -1; } int lattice_width = 0; unsigned int utf8_code; int utf8_bytes; while (*s) { utf8_bytes = get_utf8_code(s, utf8_code); const LATTICE* p_lattice = get_lattice((const LATTICE_FONT_INFO*)font, utf8_code); lattice_width += p_lattice ? p_lattice->width : ((const LATTICE_FONT_INFO*)font)->height; s += utf8_bytes; } width = lattice_width; height = ((const LATTICE_FONT_INFO*)font)->height; return 0; } private: void value_2_string(int value, int dot_position, char* buf, int len) { memset(buf, 0, len); switch (dot_position) { case 0: sprintf(buf, "%d", value); break; case 1: sprintf(buf, "%.1f", value * 1.0 / 10); break; case 2: sprintf(buf, "%.2f", value * 1.0 / 100); break; case 3: sprintf(buf, "%.3f", value * 1.0 / 1000); break; default: ASSERT(false); break; } } int draw_single_char(c_surface* surface, int z_order, unsigned int utf8_code, int x, int y, const LATTICE_FONT_INFO* font, unsigned int font_color, unsigned int bg_color) { unsigned int error_color = 0xFFFFFFFF; if (font) { const LATTICE* p_lattice = get_lattice(font, utf8_code); if (p_lattice) { draw_lattice(surface, z_order, x, y, p_lattice->width, font->height, p_lattice->pixel_buffer, font_color, bg_color); return p_lattice->width; } } else { error_color = GL_RGB(255, 0, 0); } //lattice/font not found, draw "X" int len = 16; for (int y_ = 0; y_ < len; y_++) { for (int x_ = 0; x_ < len; x_++) { int diff = (x_ - y_); int sum = (x_ + y_); (diff == 0 || diff == -1 || diff == 1 || sum == len || sum == (len - 1) || sum == (len + 1)) ? surface->draw_pixel((x + x_), (y + y_), error_color, z_order) : surface->draw_pixel((x + x_), (y + y_), 0, z_order); } } return len; } void draw_lattice(c_surface* surface, int z_order, int x, int y, int width, int height, const unsigned char* p_data, unsigned int font_color, unsigned int bg_color) { unsigned int r, g, b, rgb; unsigned char blk_value = *p_data++; unsigned char blk_cnt = *p_data++; b = (GL_RGB_B(font_color) * blk_value + GL_RGB_B(bg_color) * (255 - blk_value)) >> 8; g = (GL_RGB_G(font_color) * blk_value + GL_RGB_G(bg_color) * (255 - blk_value)) >> 8; r = (GL_RGB_R(font_color) * blk_value + GL_RGB_R(bg_color) * (255 - blk_value)) >> 8; rgb = GL_RGB(r, g, b); for (int y_ = 0; y_ < height; y_++) { for (int x_ = 0; x_ < width; x_++) { ASSERT(blk_cnt); if (0x00 == blk_value) { if (GL_ARGB_A(bg_color)) { surface->draw_pixel(x + x_, y + y_, bg_color, z_order); } } else { surface->draw_pixel((x + x_), (y + y_), rgb, z_order); } if (--blk_cnt == 0) {//reload new block blk_value = *p_data++; blk_cnt = *p_data++; b = (GL_RGB_B(font_color) * blk_value + GL_RGB_B(bg_color) * (255 - blk_value)) >> 8; g = (GL_RGB_G(font_color) * blk_value + GL_RGB_G(bg_color) * (255 - blk_value)) >> 8; r = (GL_RGB_R(font_color) * blk_value + GL_RGB_R(bg_color) * (255 - blk_value)) >> 8; rgb = GL_RGB(r, g, b); } } } } const LATTICE* get_lattice(const LATTICE_FONT_INFO* font, unsigned int utf8_code) { int first = 0; int last = font->count - 1; int middle = (first + last) / 2; while (first <= last) { if (font->lattice_array[middle].utf8_code < utf8_code) first = middle + 1; else if (font->lattice_array[middle].utf8_code == utf8_code) { return &font->lattice_array[middle]; } else { last = middle - 1; } middle = (first + last) / 2; } return 0; } static int get_utf8_code(const char* s, unsigned int& output_utf8_code) { static unsigned char s_utf8_length_table[256] = { 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, 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, 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, 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, 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, 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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 1, 1 }; unsigned char* us = (unsigned char*)s; int utf8_bytes = s_utf8_length_table[*us]; switch (utf8_bytes) { case 1: output_utf8_code = *us; break; case 2: output_utf8_code = (*us << 8) | (*(us + 1)); break; case 3: output_utf8_code = (*us << 16) | ((*(us + 1)) << 8) | *(us + 2); break; case 4: output_utf8_code = (*us << 24) | ((*(us + 1)) << 16) | (*(us + 2) << 8) | *(us + 3); break; default: ASSERT(false); break; } return utf8_bytes; } }; class c_word { public: static void draw_string(c_surface* surface, int z_order, const void* string, int x, int y, const void* font, unsigned int font_color, unsigned int bg_color)//string: char or wchar_t { fontOperator->draw_string(surface, z_order, string, x, y, font, font_color, bg_color); } static void draw_string_in_rect(c_surface* surface, int z_order, const void* string, c_rect rect, const void* font, unsigned int font_color, unsigned int bg_color, unsigned int align_type = ALIGN_LEFT)//string: char or wchar_t { fontOperator->draw_string_in_rect(surface, z_order, string, rect, font, font_color, bg_color, align_type); } static void draw_value_in_rect(c_surface* surface, int z_order, int value, int dot_position, c_rect rect, const void* font, unsigned int font_color, unsigned int bg_color, unsigned int align_type = ALIGN_LEFT) { fontOperator->draw_value_in_rect(surface, z_order, value, dot_position, rect, font, font_color, bg_color, align_type); } static void draw_value(c_surface* surface, int z_order, int value, int dot_position, int x, int y, const void* font, unsigned int font_color, unsigned int bg_color) { fontOperator->draw_value(surface, z_order, value, dot_position, x, y, font, font_color, bg_color); } static int get_str_size(const void* string, const void* font, int& width, int& height) { return fontOperator->get_str_size(string, font, width, height); } static c_font_operator* fontOperator; }; #define DEFAULT_MASK_COLOR 0xFF080408 class c_surface; class c_image_operator { public: virtual void draw_image(c_surface* surface, int z_order, const void* image_info, int x, int y, unsigned int mask_rgb = DEFAULT_MASK_COLOR) = 0; virtual void draw_image(c_surface* surface, int z_order, const void* image_info, int x, int y, int src_x, int src_y, int width, int height, unsigned int mask_rgb = DEFAULT_MASK_COLOR) = 0; }; class c_bitmap_operator : public c_image_operator { public: virtual void draw_image(c_surface* surface, int z_order, const void* image_info, int x, int y, unsigned int mask_rgb = DEFAULT_MASK_COLOR) { ASSERT(image_info); BITMAP_INFO* pBitmap = (BITMAP_INFO*)image_info; unsigned short* lower_fb_16 = 0; unsigned int* lower_fb_32 = 0; int lower_fb_width = 0; c_rect lower_fb_rect; if (z_order >= Z_ORDER_LEVEL_1) { lower_fb_16 = (unsigned short*)surface->m_layers[z_order - 1].fb; lower_fb_32 = (unsigned int*)surface->m_layers[z_order - 1].fb; lower_fb_rect = surface->m_layers[z_order - 1].rect; lower_fb_width = lower_fb_rect.width(); } unsigned int mask_rgb_16 = GL_RGB_32_to_16(mask_rgb); int xsize = pBitmap->width; int ysize = pBitmap->height; const unsigned short* pData = (const unsigned short*)pBitmap->pixel_color_array; int color_bytes = surface->m_color_bytes; for (int y_ = y; y_ < y + ysize; y_++) { for (int x_ = x; x_ < x + xsize; x_++) { unsigned int rgb = *pData++; if (mask_rgb_16 == rgb) { if (lower_fb_rect.pt_in_rect(x_, y_)) {//show lower layer surface->draw_pixel(x_, y_, (color_bytes == 4) ? lower_fb_32[(y_ - lower_fb_rect.m_top) * lower_fb_width + (x_ - lower_fb_rect.m_left)] : GL_RGB_16_to_32(lower_fb_16[(y_ - lower_fb_rect.m_top) * lower_fb_width + (x_ - lower_fb_rect.m_left)]), z_order); } } else { surface->draw_pixel(x_, y_, GL_RGB_16_to_32(rgb), z_order); } } } } virtual void draw_image(c_surface* surface, int z_order, const void* image_info, int x, int y, int src_x, int src_y, int width, int height, unsigned int mask_rgb = DEFAULT_MASK_COLOR) { ASSERT(image_info); BITMAP_INFO* pBitmap = (BITMAP_INFO*)image_info; if (0 == pBitmap || (src_x + width > pBitmap->width) || (src_y + height > pBitmap->height)) { return; } unsigned short* lower_fb_16 = 0; unsigned int* lower_fb_32 = 0; int lower_fb_width = 0; c_rect lower_fb_rect; if (z_order >= Z_ORDER_LEVEL_1) { lower_fb_16 = (unsigned short*)surface->m_layers[z_order - 1].fb; lower_fb_32 = (unsigned int*)surface->m_layers[z_order - 1].fb; lower_fb_rect = surface->m_layers[z_order - 1].rect; lower_fb_width = lower_fb_rect.width(); } unsigned int mask_rgb_16 = GL_RGB_32_to_16(mask_rgb); const unsigned short* pData = (const unsigned short*)pBitmap->pixel_color_array; int color_bytes = surface->m_color_bytes; for (int y_ = 0; y_ < height; y_++) { const unsigned short* p = &pData[src_x + (src_y + y_) * pBitmap->width]; for (int x_ = 0; x_ < width; x_++) { unsigned int rgb = *p++; if (mask_rgb_16 == rgb) { if (lower_fb_rect.pt_in_rect(x + x_, y + y_)) {//show lower layer surface->draw_pixel(x + x_, y + y_, (color_bytes == 4) ? lower_fb_32[(y + y_ - lower_fb_rect.m_top) * lower_fb_width + x + x_ - lower_fb_rect.m_left] : GL_RGB_16_to_32(lower_fb_16[(y + y_ - lower_fb_rect.m_top) * lower_fb_width + x + x_ - lower_fb_rect.m_left]), z_order); } } else { surface->draw_pixel(x + x_, y + y_, GL_RGB_16_to_32(rgb), z_order); } } } } }; class c_image { public: static void draw_image(c_surface* surface, int z_order, const void* image_info, int x, int y, unsigned int mask_rgb = DEFAULT_MASK_COLOR) { image_operator->draw_image(surface, z_order, image_info, x, y, mask_rgb); } static void draw_image(c_surface* surface, int z_order, const void* image_info, int x, int y, int src_x, int src_y, int width, int height, unsigned int mask_rgb = DEFAULT_MASK_COLOR) { image_operator->draw_image(surface, z_order, image_info, x, y, src_x, src_y, width, height, mask_rgb); } static c_image_operator* image_operator; }; class c_wnd; class c_surface; typedef enum { ATTR_VISIBLE = 0x40000000L, ATTR_FOCUS = 0x20000000L, ATTR_PRIORITY = 0x10000000L// Handle touch action at high priority }WND_ATTRIBUTION; typedef enum { STATUS_NORMAL, STATUS_PUSHED, STATUS_FOCUSED, STATUS_DISABLED }WND_STATUS; typedef enum { NAV_FORWARD, NAV_BACKWARD, NAV_ENTER }NAVIGATION_KEY; typedef enum { TOUCH_DOWN, TOUCH_UP }TOUCH_ACTION; typedef struct struct_wnd_tree { c_wnd* p_wnd;//window instance unsigned int resource_id;//ID const char* str;//caption short x;//position x short y;//position y short width; short height; struct struct_wnd_tree* p_child_tree;//sub tree }WND_TREE; typedef void (c_wnd::*WND_CALLBACK)(int, int); class c_wnd { public: c_wnd() : m_status(STATUS_NORMAL), m_attr((WND_ATTRIBUTION)(ATTR_VISIBLE | ATTR_FOCUS)), m_parent(0), m_top_child(0), m_prev_sibling(0), m_next_sibling(0), m_str(0), m_font_color(0), m_bg_color(0), m_id(0), m_z_order(Z_ORDER_LEVEL_0), m_focus_child(0), m_surface(0) {}; virtual ~c_wnd() {}; virtual int connect(c_wnd *parent, unsigned short resource_id, const char* str, short x, short y, short width, short height, WND_TREE* p_child_tree = 0) { if (0 == resource_id) { ASSERT(false); return -1; } m_id = resource_id; set_str(str); m_parent = parent; m_status = STATUS_NORMAL; if (parent) { m_z_order = parent->m_z_order; m_surface = parent->m_surface; } if (0 == m_surface) { ASSERT(false); return -2; } /* (cs.x = x * 1024 / 768) for 1027*768=>800*600 quickly*/ m_wnd_rect.m_left = x; m_wnd_rect.m_top = y; m_wnd_rect.m_right = (x + width - 1); m_wnd_rect.m_bottom = (y + height - 1); pre_create_wnd(); if (0 != parent) { parent->add_child_2_tail(this); } if (load_child_wnd(p_child_tree) >= 0) { on_init_children(); } return 0; } void disconnect() { if (0 == m_id) { return; } if (0 != m_top_child) { c_wnd* child = m_top_child; c_wnd* next_child = 0; while (child) { next_child = child->m_next_sibling; child->disconnect(); child = next_child; } } if (0 != m_parent) { m_parent->unlink_child(this); } m_focus_child = 0; m_id = 0; } virtual void on_init_children() {} virtual void on_paint() {} virtual void show_window() { if (ATTR_VISIBLE == (m_attr & ATTR_VISIBLE)) { on_paint(); c_wnd* child = m_top_child; if (0 != child) { while (child) { child->show_window(); child = child->m_next_sibling; } } } } unsigned short get_id() const { return m_id; } int get_z_order() { return m_z_order; } c_wnd* get_wnd_ptr(unsigned short id) const { c_wnd* child = m_top_child; while (child) { if (child->get_id() == id) { break; } child = child->m_next_sibling; } return child; } unsigned int get_attr() const { return m_attr; } void set_str(const char* str) { m_str = str; } void set_attr(WND_ATTRIBUTION attr) { m_attr = attr; } bool is_focus_wnd() const { return ((m_attr & ATTR_VISIBLE) && (m_attr & ATTR_FOCUS)) ? true : false; } void set_font_color(unsigned int color) { m_font_color = color; } unsigned int get_font_color() { return m_font_color; } void set_bg_color(unsigned int color) { m_bg_color = color; } unsigned int get_bg_color() { return m_bg_color; } void set_font_type(const LATTICE_FONT_INFO *font_type) { m_font = font_type; } const void* get_font_type() { return m_font; } void set_wnd_pos(short x, short y, short width, short height) { m_wnd_rect.m_left = x; m_wnd_rect.m_top = y; m_wnd_rect.m_right = x + width - 1; m_wnd_rect.m_bottom = y + height - 1; } void get_wnd_rect(c_rect &rect) const { rect = m_wnd_rect; } void get_screen_rect(c_rect &rect) const { int l = 0; int t = 0; wnd2screen(l, t); rect.set_rect(l, t, m_wnd_rect.width(), m_wnd_rect.height()); } c_wnd* set_child_focus(c_wnd *focus_child) { ASSERT(0 != focus_child); ASSERT(focus_child->m_parent == this); c_wnd* old_focus_child = m_focus_child; if (focus_child->is_focus_wnd()) { if (focus_child != old_focus_child) { if (old_focus_child) { old_focus_child->on_kill_focus(); } m_focus_child = focus_child; m_focus_child->on_focus(); } } return m_focus_child; } c_wnd* get_parent() const { return m_parent; } c_wnd* get_last_child() const { if (0 == m_top_child) { return 0; } c_wnd* child = m_top_child; while (child->m_next_sibling) { child = child->m_next_sibling; } return child; } int unlink_child(c_wnd *child) { if ((0 == child) || (this != child->m_parent)) { return -1; } if (0 == m_top_child) { return -2; } bool find = false; c_wnd* tmp_child = m_top_child; if (tmp_child == child) { m_top_child = child->m_next_sibling; if (0 != child->m_next_sibling) { child->m_next_sibling->m_prev_sibling = 0; } find = true; } else { while (tmp_child->m_next_sibling) { if (child == tmp_child->m_next_sibling) { tmp_child->m_next_sibling = child->m_next_sibling; if (0 != child->m_next_sibling) { child->m_next_sibling->m_prev_sibling = tmp_child; } find = true; break; } tmp_child = tmp_child->m_next_sibling; } } if (true == find) { if (m_focus_child == child) { m_focus_child = 0; } child->m_next_sibling = 0; child->m_prev_sibling = 0; return 1; } else { return 0; } } c_wnd* get_prev_sibling() const { return m_prev_sibling; } c_wnd* get_next_sibling() const { return m_next_sibling; } virtual void on_touch(int x, int y, TOUCH_ACTION action) { x -= m_wnd_rect.m_left; y -= m_wnd_rect.m_top; c_wnd* priority_wnd = 0; c_wnd* tmp_child = m_top_child; while (tmp_child) { if ((tmp_child->m_attr & ATTR_PRIORITY) && (tmp_child->m_attr & ATTR_VISIBLE)) { priority_wnd = tmp_child; break; } tmp_child = tmp_child->m_next_sibling; } if (priority_wnd) { return priority_wnd->on_touch(x, y, action); } c_wnd* child = m_top_child; while (child) { if (child->is_focus_wnd()) { c_rect rect; child->get_wnd_rect(rect); if (true == rect.pt_in_rect(x, y)) { return child->on_touch(x, y, action); } } child = child->m_next_sibling; } } virtual void on_navigate(NAVIGATION_KEY key) { c_wnd* priority_wnd = 0; c_wnd* tmp_child = m_top_child; while (tmp_child) { if ((tmp_child->m_attr & ATTR_PRIORITY) && (tmp_child->m_attr & ATTR_VISIBLE)) { priority_wnd = tmp_child; break; } tmp_child = tmp_child->m_next_sibling; } if (priority_wnd) { return priority_wnd->on_navigate(key); } if (!is_focus_wnd()) { return; } if (key != NAV_BACKWARD && key != NAV_FORWARD) { if (m_focus_child) { m_focus_child->on_navigate(key); } return; } // Move focus c_wnd* old_focus_wnd = m_focus_child; // No current focus wnd, new one. if (!old_focus_wnd) { c_wnd* child = m_top_child; c_wnd* new_focus_wnd = 0; while (child) { if (child->is_focus_wnd()) { new_focus_wnd = child; new_focus_wnd->m_parent->set_child_focus(new_focus_wnd); child = child->m_top_child; continue; } child = child->m_next_sibling; } return; } // Move focus from old wnd to next wnd c_wnd* next_focus_wnd = (key == NAV_FORWARD) ? old_focus_wnd->m_next_sibling : old_focus_wnd->m_prev_sibling; while (next_focus_wnd && (!next_focus_wnd->is_focus_wnd())) {// Search neighbor of old focus wnd next_focus_wnd = (key == NAV_FORWARD) ? next_focus_wnd->m_next_sibling : next_focus_wnd->m_prev_sibling; } if (!next_focus_wnd) {// Search whole brother wnd next_focus_wnd = (key == NAV_FORWARD) ? old_focus_wnd->m_parent->m_top_child : old_focus_wnd->m_parent->get_last_child(); while (next_focus_wnd && (!next_focus_wnd->is_focus_wnd())) { next_focus_wnd = (key == NAV_FORWARD) ? next_focus_wnd->m_next_sibling : next_focus_wnd->m_prev_sibling; } } if (next_focus_wnd) { next_focus_wnd->m_parent->set_child_focus(next_focus_wnd); } } c_surface* get_surface() { return m_surface; } void set_surface(c_surface* surface) { m_surface = surface; } protected: virtual void pre_create_wnd() {}; void add_child_2_tail(c_wnd *child) { if (0 == child)return; if (child == get_wnd_ptr(child->m_id))return; if (0 == m_top_child) { m_top_child = child; child->m_prev_sibling = 0; child->m_next_sibling = 0; } else { c_wnd* last_child = get_last_child(); if (0 == last_child) { ASSERT(false); } last_child->m_next_sibling = child; child->m_prev_sibling = last_child; child->m_next_sibling = 0; } } void wnd2screen(int &x, int &y) const { c_wnd* parent = m_parent; c_rect rect; x += m_wnd_rect.m_left; y += m_wnd_rect.m_top; while (0 != parent) { parent->get_wnd_rect(rect); x += rect.m_left; y += rect.m_top; parent = parent->m_parent; } } int load_child_wnd(WND_TREE *p_child_tree) { if (0 == p_child_tree) { return 0; } int sum = 0; WND_TREE* p_cur = p_child_tree; while (p_cur->p_wnd) { if (0 != p_cur->p_wnd->m_id) {//This wnd has been used! Do not share! ASSERT(false); return -1; } else { p_cur->p_wnd->connect(this, p_cur->resource_id, p_cur->str, p_cur->x, p_cur->y, p_cur->width, p_cur->height, p_cur->p_child_tree); } p_cur++; sum++; } return sum; } void set_active_child(c_wnd* child) { m_focus_child = child; } virtual void on_focus() {}; virtual void on_kill_focus() {}; protected: unsigned short m_id; WND_STATUS m_status; WND_ATTRIBUTION m_attr; c_rect m_wnd_rect; //position relative to parent window. c_wnd* m_parent; //parent window c_wnd* m_top_child; //the first sub window would be navigated c_wnd* m_prev_sibling; //previous brother c_wnd* m_next_sibling; //next brother c_wnd* m_focus_child; //current focused window const char* m_str; //caption const void* m_font; //font face unsigned int m_font_color; unsigned int m_bg_color; int m_z_order; //the graphic level for rendering c_surface* m_surface; }; class c_button : public c_wnd { public: void set_on_click(WND_CALLBACK on_click) { this->on_click = on_click; } protected: virtual void on_paint() { c_rect rect; get_screen_rect(rect); switch (m_status) { case STATUS_NORMAL: m_surface->fill_rect(rect, c_theme::get_color(COLOR_WND_NORMAL), m_z_order); if (m_str) { c_word::draw_string_in_rect(m_surface, m_z_order, m_str, rect, m_font, m_font_color, c_theme::get_color(COLOR_WND_NORMAL), ALIGN_HCENTER | ALIGN_VCENTER); } break; case STATUS_FOCUSED: m_surface->fill_rect(rect, c_theme::get_color(COLOR_WND_FOCUS), m_z_order); if (m_str) { c_word::draw_string_in_rect(m_surface, m_z_order, m_str, rect, m_font, m_font_color, c_theme::get_color(COLOR_WND_FOCUS), ALIGN_HCENTER | ALIGN_VCENTER); } break; case STATUS_PUSHED: m_surface->fill_rect(rect, c_theme::get_color(COLOR_WND_PUSHED), m_z_order); m_surface->draw_rect(rect, c_theme::get_color(COLOR_WND_BORDER), 2, m_z_order); if (m_str) { c_word::draw_string_in_rect(m_surface, m_z_order, m_str, rect, m_font, m_font_color, c_theme::get_color(COLOR_WND_PUSHED), ALIGN_HCENTER | ALIGN_VCENTER); } break; default: ASSERT(false); break; } } virtual void on_focus() { m_status = STATUS_FOCUSED; on_paint(); } virtual void on_kill_focus() { m_status = STATUS_NORMAL; on_paint(); } virtual void pre_create_wnd() { on_click = 0; m_attr = (WND_ATTRIBUTION)(ATTR_VISIBLE | ATTR_FOCUS); m_font = c_theme::get_font(FONT_DEFAULT); m_font_color = c_theme::get_color(COLOR_WND_FONT); } virtual void on_touch(int x, int y, TOUCH_ACTION action) { if (action == TOUCH_DOWN) { m_parent->set_child_focus(this); m_status = STATUS_PUSHED; on_paint(); } else { m_status = STATUS_FOCUSED; on_paint(); if(on_click) { (m_parent->*(on_click))(m_id, 0); } } } virtual void on_navigate(NAVIGATION_KEY key) { switch (key) { case NAV_ENTER: on_touch(m_wnd_rect.m_left, m_wnd_rect.m_top, TOUCH_DOWN); on_touch(m_wnd_rect.m_left, m_wnd_rect.m_top, TOUCH_UP); break; case NAV_FORWARD: case NAV_BACKWARD: break; } return c_wnd::on_navigate(key); } WND_CALLBACK on_click; }; class c_surface; class c_dialog; typedef struct { c_dialog* dialog; c_surface* surface; } DIALOG_ARRAY; class c_dialog : public c_wnd { public: static int open_dialog(c_dialog* p_dlg, bool modal_mode = true) { if (0 == p_dlg) { ASSERT(false); return 0; } c_dialog* cur_dlg = get_the_dialog(p_dlg->get_surface()); if (cur_dlg == p_dlg) { return 1; } if (cur_dlg) { cur_dlg->set_attr(WND_ATTRIBUTION(0)); } p_dlg->set_attr(modal_mode ? (WND_ATTRIBUTION)(ATTR_VISIBLE | ATTR_FOCUS | ATTR_PRIORITY) : (WND_ATTRIBUTION)(ATTR_VISIBLE | ATTR_FOCUS)); p_dlg->show_window(); p_dlg->set_me_the_dialog(); return 1; } static int close_dialog(c_surface* surface) { c_dialog* dlg = get_the_dialog(surface); if (0 == dlg) { return 0; } c_rect rc; dlg->get_screen_rect(rc); dlg->set_attr(WND_ATTRIBUTION(0)); surface->show_layer(rc, dlg->m_z_order - 1); //clear the dialog for (int i = 0; i < SURFACE_CNT_MAX; i++) { if (ms_the_dialogs[i].surface == surface) { ms_the_dialogs[i].dialog = 0; return 1; } } ASSERT(false); return -1; } static c_dialog* get_the_dialog(c_surface* surface) { for (int i = 0; i < SURFACE_CNT_MAX; i++) { if (ms_the_dialogs[i].surface == surface) { return ms_the_dialogs[i].dialog; } } return 0; } protected: virtual void pre_create_wnd() { m_attr = WND_ATTRIBUTION(0);// no focus/visible m_z_order = Z_ORDER_LEVEL_1; m_bg_color = GL_RGB(33, 42, 53); } virtual void on_paint() { c_rect rect; get_screen_rect(rect); m_surface->fill_rect(rect, m_bg_color, m_z_order); if (m_str) { c_word::draw_string(m_surface, m_z_order, m_str, rect.m_left + 35, rect.m_top, c_theme::get_font(FONT_DEFAULT), GL_RGB(255, 255, 255), GL_ARGB(0, 0, 0, 0)); } } private: int set_me_the_dialog() { c_surface* surface = get_surface(); for (int i = 0; i < SURFACE_CNT_MAX; i++) { if (ms_the_dialogs[i].surface == surface) { ms_the_dialogs[i].dialog = this; return 0; } } for (int i = 0; i < SURFACE_CNT_MAX; i++) { if (ms_the_dialogs[i].surface == 0) { ms_the_dialogs[i].dialog = this; ms_the_dialogs[i].surface = surface; return 1; } } ASSERT(false); return -2; } static DIALOG_ARRAY ms_the_dialogs[SURFACE_CNT_MAX]; }; #include <string.h> //Changing key width/height will change the width/height of keyboard #define KEY_WIDTH 65 #define KEY_HEIGHT 38 #define KEYBOARD_WIDTH ((KEY_WIDTH + 2) * 10) #define KEYBOARD_HEIGHT ((KEY_HEIGHT + 2) * 4) #define NUM_BOARD_WIDTH ((KEY_WIDTH + 2) * 4) #define NUM_BOARD_HEIGHT ((KEY_HEIGHT + 2) * 4) #define CAPS_WIDTH (KEY_WIDTH * 3 / 2) #define DEL_WIDTH (KEY_WIDTH * 3 / 2 + 1) #define ESC_WIDTH (KEY_WIDTH * 2 + 2) #define SWITCH_WIDTH (KEY_WIDTH * 3 / 2 ) #define SPACE_WIDTH (KEY_WIDTH * 3 + 2 * 2) #define DOT_WIDTH (KEY_WIDTH * 3 / 2 + 3) #define ENTER_WIDTH (KEY_WIDTH * 2 + 2) #define POS_X(c) ((KEY_WIDTH * c) + (c + 1) * 2) #define POS_Y(r) ((KEY_HEIGHT * r) + (r + 1) * 2) #define KEYBORAD_CLICK 0x5014 #define ON_KEYBORAD_UPDATE(func) \ {MSG_TYPE_WND, KEYBORAD_CLICK, 0, msgCallback(&func)}, typedef enum { STATUS_UPPERCASE, STATUS_LOWERCASE }KEYBOARD_STATUS; typedef enum { STYLE_ALL_BOARD, STYLE_NUM_BOARD }KEYBOARD_STYLE; typedef enum { CLICK_CHAR, CLICK_ENTER, CLICK_ESC }CLICK_STATUS; extern WND_TREE g_key_board_children[]; extern WND_TREE g_number_board_children[]; class c_keyboard: public c_wnd { public: virtual int connect(c_wnd *user, unsigned short resource_id, KEYBOARD_STYLE style) { c_rect user_rect; user->get_wnd_rect(user_rect); if (style == STYLE_ALL_BOARD) {//Place keyboard at the bottom of user's parent window. c_rect user_parent_rect; user->get_parent()->get_wnd_rect(user_parent_rect); return c_wnd::connect(user, resource_id, 0, (0 - user_rect.m_left), (user_parent_rect.height() - user_rect.m_top - KEYBOARD_HEIGHT - 1), KEYBOARD_WIDTH, KEYBOARD_HEIGHT, g_key_board_children); } else if (style == STYLE_NUM_BOARD) {//Place keyboard below the user window. return c_wnd::connect(user, resource_id, 0, 0, user_rect.height(), NUM_BOARD_WIDTH, NUM_BOARD_HEIGHT, g_number_board_children); } else { ASSERT(false); } return -1; } virtual void on_init_children() { c_wnd* child = m_top_child; if (0 != child) { while (child) { ((c_button*)child)->set_on_click(WND_CALLBACK(&c_keyboard::on_key_clicked)); child = child->get_next_sibling(); } } } KEYBOARD_STATUS get_cap_status(){return m_cap_status;} char* get_str() { return m_str; } void set_on_click(WND_CALLBACK on_click) { this->on_click = on_click; } protected: virtual void pre_create_wnd() { m_attr = (WND_ATTRIBUTION)(ATTR_VISIBLE | ATTR_FOCUS); m_cap_status = STATUS_UPPERCASE; memset(m_str, 0, sizeof(m_str)); m_str_len = 0; } virtual void on_paint() { c_rect rect; get_screen_rect(rect); m_surface->fill_rect(rect, GL_RGB(0, 0, 0), m_z_order); } void on_key_clicked(int id, int param) { switch (id) { case 0x14: on_caps_clicked(id, param); break; case '\n': on_enter_clicked(id, param); break; case 0x1B: on_esc_clicked(id, param); break; case 0x7F: on_del_clicked(id, param); break; default: on_char_clicked(id, param); break; } } void on_char_clicked(int id, int param) {//id = char ascii code. if (m_str_len >= sizeof(m_str)) { return; } if ((id >= '0' && id <= '9') || id == ' ' || id == '.') { goto InputChar; } if (id >= 'A' && id <= 'Z') { if (STATUS_LOWERCASE == m_cap_status) { id += 0x20; } goto InputChar; } ASSERT(false); InputChar: m_str[m_str_len++] = id; (m_parent->*(on_click))(m_id, CLICK_CHAR); } void on_del_clicked(int id, int param) { if (m_str_len <= 0) { return; } m_str[--m_str_len] = 0; (m_parent->*(on_click))(m_id, CLICK_CHAR); } void on_caps_clicked(int id, int param) { m_cap_status = (m_cap_status == STATUS_LOWERCASE) ? STATUS_UPPERCASE : STATUS_LOWERCASE; show_window(); } void on_enter_clicked(int id, int param) { memset(m_str, 0, sizeof(m_str)); (m_parent->*(on_click))(m_id, CLICK_ENTER); } void on_esc_clicked(int id, int param) { memset(m_str, 0, sizeof(m_str)); (m_parent->*(on_click))(m_id, CLICK_ESC); } private: char m_str[32]; int m_str_len; KEYBOARD_STATUS m_cap_status; WND_CALLBACK on_click; }; class c_keyboard_button : public c_button { protected: virtual void on_paint() { c_rect rect; get_screen_rect(rect); switch (m_status) { case STATUS_NORMAL: m_surface->fill_rect(rect, c_theme::get_color(COLOR_WND_NORMAL), m_z_order); break; case STATUS_FOCUSED: m_surface->fill_rect(rect, c_theme::get_color(COLOR_WND_FOCUS), m_z_order); break; case STATUS_PUSHED: m_surface->fill_rect(rect, c_theme::get_color(COLOR_WND_PUSHED), m_z_order); m_surface->draw_rect(rect, c_theme::get_color(COLOR_WND_BORDER), 2, m_z_order); break; default: ASSERT(false); break; } if (m_id == 0x14) { return c_word::draw_string_in_rect(m_surface, m_z_order, "Caps", rect, m_font, m_font_color, GL_ARGB(0, 0, 0, 0), m_attr); } else if (m_id == 0x1B) { return c_word::draw_string_in_rect(m_surface, m_z_order, "Esc", rect, m_font, m_font_color, GL_ARGB(0, 0, 0, 0), m_attr); } else if (m_id == ' ') { return c_word::draw_string_in_rect(m_surface, m_z_order, "Space", rect, m_font, m_font_color, GL_ARGB(0, 0, 0, 0), m_attr); } else if (m_id == '\n') { return c_word::draw_string_in_rect(m_surface, m_z_order, "Enter", rect, m_font, m_font_color, GL_ARGB(0, 0, 0, 0), m_attr); } else if (m_id == '.') { return c_word::draw_string_in_rect(m_surface, m_z_order, ".", rect, m_font, m_font_color, GL_ARGB(0, 0, 0, 0), m_attr); } else if (m_id == 0x7F) { return c_word::draw_string_in_rect(m_surface, m_z_order, "Back", rect, m_font, m_font_color, GL_ARGB(0, 0, 0, 0), m_attr); } else if (m_id == 0x90) { return c_word::draw_string_in_rect(m_surface, m_z_order, "?123", rect, m_font, m_font_color, GL_ARGB(0, 0, 0, 0), m_attr); } char letter[] = { 0, 0 }; if (m_id >= 'A' && m_id <= 'Z') { letter[0] = (((c_keyboard*)m_parent)->get_cap_status() == STATUS_UPPERCASE) ? m_id : (m_id + 0x20); } else if (m_id >= '0' && m_id <= '9') { letter[0] = (char)m_id; } c_word::draw_string_in_rect(m_surface, m_z_order, letter, rect, m_font, m_font_color, GL_ARGB(0, 0, 0, 0), m_attr); } }; #include <string.h> #define MAX_EDIT_STRLEN 32 #define IDD_KEY_BOARD 0x1 class c_edit : public c_wnd { friend class c_keyboard; public: const char* get_text(){return m_str;} void set_text(const char* str) { if (str != 0 && strlen(str) < sizeof(m_str)) { strcpy(m_str, str); } } void set_keyboard_style(KEYBOARD_STYLE kb_sytle) { m_kb_style = kb_sytle; } protected: virtual void pre_create_wnd() { m_attr = (WND_ATTRIBUTION)(ATTR_VISIBLE | ATTR_FOCUS); m_kb_style = STYLE_ALL_BOARD; m_font = c_theme::get_font(FONT_DEFAULT); m_font_color = c_theme::get_color(COLOR_WND_FONT); memset(m_str_input, 0, sizeof(m_str_input)); memset(m_str, 0, sizeof(m_str)); set_text(c_wnd::m_str); } virtual void on_paint() { c_rect rect, kb_rect; get_screen_rect(rect); s_keyboard.get_screen_rect(kb_rect); switch (m_status) { case STATUS_NORMAL: if (m_z_order > m_parent->get_z_order()) { s_keyboard.disconnect(); m_z_order = m_parent->get_z_order(); m_surface->show_layer(kb_rect, m_z_order); m_attr = (WND_ATTRIBUTION)(ATTR_VISIBLE | ATTR_FOCUS); } m_surface->fill_rect(rect, c_theme::get_color(COLOR_WND_NORMAL), m_z_order); c_word::draw_string_in_rect(m_surface, m_parent->get_z_order(), m_str, rect, m_font, m_font_color, c_theme::get_color(COLOR_WND_NORMAL), ALIGN_HCENTER | ALIGN_VCENTER); break; case STATUS_FOCUSED: if (m_z_order > m_parent->get_z_order()) { s_keyboard.disconnect(); m_z_order = m_parent->get_z_order(); m_surface->show_layer(kb_rect, m_z_order); m_attr = (WND_ATTRIBUTION)(ATTR_VISIBLE | ATTR_FOCUS); } m_surface->fill_rect(rect, c_theme::get_color(COLOR_WND_FOCUS), m_z_order); c_word::draw_string_in_rect(m_surface, m_parent->get_z_order(), m_str, rect, m_font, m_font_color, c_theme::get_color(COLOR_WND_FOCUS), ALIGN_HCENTER | ALIGN_VCENTER); break; case STATUS_PUSHED: if (m_z_order == m_parent->get_z_order()) { m_z_order++; m_attr = (WND_ATTRIBUTION)(ATTR_VISIBLE | ATTR_FOCUS | ATTR_PRIORITY); show_keyboard(); } m_surface->fill_rect(rect.m_left, rect.m_top, rect.m_right, rect.m_bottom, c_theme::get_color(COLOR_WND_PUSHED), m_parent->get_z_order()); m_surface->draw_rect(rect.m_left, rect.m_top, rect.m_right, rect.m_bottom, c_theme::get_color(COLOR_WND_BORDER), m_parent->get_z_order(), 2); strlen(m_str_input) ? c_word::draw_string_in_rect(m_surface, m_parent->get_z_order(), m_str_input, rect, m_font, m_font_color, c_theme::get_color(COLOR_WND_PUSHED), ALIGN_HCENTER | ALIGN_VCENTER) : c_word::draw_string_in_rect(m_surface, m_parent->get_z_order(), m_str, rect, m_font, m_font_color, c_theme::get_color(COLOR_WND_PUSHED), ALIGN_HCENTER | ALIGN_VCENTER); break; default: ASSERT(false); } } virtual void on_focus() { m_status = STATUS_FOCUSED; on_paint(); } virtual void on_kill_focus() { m_status = STATUS_NORMAL; on_paint(); } virtual void on_navigate(NAVIGATION_KEY key) { switch (key) { case NAV_ENTER: (m_status == STATUS_PUSHED) ? s_keyboard.on_navigate(key) : (on_touch(m_wnd_rect.m_left, m_wnd_rect.m_top, TOUCH_DOWN), on_touch(m_wnd_rect.m_left, m_wnd_rect.m_top, TOUCH_UP)); return; case NAV_BACKWARD: case NAV_FORWARD: return (m_status == STATUS_PUSHED) ? s_keyboard.on_navigate(key) : c_wnd::on_navigate(key); } } virtual void on_touch(int x, int y, TOUCH_ACTION action) { (action == TOUCH_DOWN) ? on_touch_down(x, y) : on_touch_up(x, y); } void on_key_board_click(int id, int param) { switch (param) { case CLICK_CHAR: strcpy(m_str_input, s_keyboard.get_str()); on_paint(); break; case CLICK_ENTER: if (strlen(m_str_input)) { memcpy(m_str, m_str_input, sizeof(m_str_input)); } m_status = STATUS_FOCUSED; on_paint(); break; case CLICK_ESC: memset(m_str_input, 0, sizeof(m_str_input)); m_status = STATUS_FOCUSED; on_paint(); break; default: ASSERT(false); break; } } private: void show_keyboard() { s_keyboard.connect(this, IDD_KEY_BOARD, m_kb_style); s_keyboard.set_on_click(WND_CALLBACK(&c_edit::on_key_board_click)); s_keyboard.show_window(); } void on_touch_down(int x, int y) { c_rect kb_rect_relate_2_edit_parent; s_keyboard.get_wnd_rect(kb_rect_relate_2_edit_parent); kb_rect_relate_2_edit_parent.m_left += m_wnd_rect.m_left; kb_rect_relate_2_edit_parent.m_right += m_wnd_rect.m_left; kb_rect_relate_2_edit_parent.m_top += m_wnd_rect.m_top; kb_rect_relate_2_edit_parent.m_bottom += m_wnd_rect.m_top; if (m_wnd_rect.pt_in_rect(x, y)) {//click edit box if (STATUS_NORMAL == m_status) { m_parent->set_child_focus(this); } } else if (kb_rect_relate_2_edit_parent.pt_in_rect(x, y)) {//click key board c_wnd::on_touch(x, y, TOUCH_DOWN); } else { if (STATUS_PUSHED == m_status) { m_status = STATUS_FOCUSED; on_paint(); } } } void on_touch_up(int x, int y) { if (STATUS_FOCUSED == m_status) { m_status = STATUS_PUSHED; on_paint(); } else if (STATUS_PUSHED == m_status) { if (m_wnd_rect.pt_in_rect(x, y)) {//click edit box m_status = STATUS_FOCUSED; on_paint(); } else { c_wnd::on_touch(x, y, TOUCH_UP); } } } static c_keyboard s_keyboard; KEYBOARD_STYLE m_kb_style; char m_str_input[MAX_EDIT_STRLEN]; char m_str[MAX_EDIT_STRLEN]; }; class c_label : public c_wnd { public: virtual void on_paint() { c_rect rect; unsigned int bg_color = m_bg_color ? m_bg_color : m_parent->get_bg_color(); get_screen_rect(rect); if (m_str) { m_surface->fill_rect(rect.m_left, rect.m_top, rect.m_right, rect.m_bottom, bg_color, m_z_order); c_word::draw_string_in_rect(m_surface, m_z_order, m_str, rect, m_font, m_font_color, bg_color, ALIGN_LEFT | ALIGN_VCENTER); } } protected: virtual void pre_create_wnd() { m_attr = ATTR_VISIBLE; m_font_color = c_theme::get_color(COLOR_WND_FONT); m_font = c_theme::get_font(FONT_DEFAULT); } }; #include <string.h> #define MAX_ITEM_NUM 4 #define ITEM_HEIGHT 45 class c_list_box : public c_wnd { public: void set_on_change(WND_CALLBACK on_change) { this->on_change = on_change; } short get_item_count() { return m_item_total; } int add_item(char* str) { if (m_item_total >= MAX_ITEM_NUM) { ASSERT(false); return -1; } m_item_array[m_item_total++] = str; update_list_size(); return 0; } void clear_item() { m_selected_item = m_item_total = 0; memset(m_item_array, 0, sizeof(m_item_array)); update_list_size(); } void select_item(short index) { if (index < 0 || index >= m_item_total) { ASSERT(false); } m_selected_item = index; } protected: virtual void pre_create_wnd() { m_attr = (WND_ATTRIBUTION)(ATTR_VISIBLE | ATTR_FOCUS); memset(m_item_array, 0, sizeof(m_item_array)); m_item_total = 0; m_selected_item = 0; m_font = c_theme::get_font(FONT_DEFAULT); m_font_color = c_theme::get_color(COLOR_WND_FONT); } virtual void on_paint() { c_rect rect; get_screen_rect(rect); switch (m_status) { case STATUS_NORMAL: if (m_z_order > m_parent->get_z_order()) { m_z_order = m_parent->get_z_order(); m_surface->show_layer(m_list_screen_rect, m_z_order); m_attr = (WND_ATTRIBUTION)(ATTR_VISIBLE | ATTR_FOCUS); } m_surface->fill_rect(rect, c_theme::get_color(COLOR_WND_NORMAL), m_z_order); c_word::draw_string_in_rect(m_surface, m_z_order, m_item_array[m_selected_item], rect, m_font, m_font_color, c_theme::get_color(COLOR_WND_NORMAL), ALIGN_HCENTER | ALIGN_VCENTER); break; case STATUS_FOCUSED: if (m_z_order > m_parent->get_z_order()) { m_z_order = m_parent->get_z_order(); m_surface->show_layer(m_list_screen_rect, m_z_order); m_attr = (WND_ATTRIBUTION)(ATTR_VISIBLE | ATTR_FOCUS); } m_surface->fill_rect(rect, c_theme::get_color(COLOR_WND_FOCUS), m_z_order); c_word::draw_string_in_rect(m_surface, m_z_order, m_item_array[m_selected_item], rect, m_font, m_font_color, c_theme::get_color(COLOR_WND_FOCUS), ALIGN_HCENTER | ALIGN_VCENTER); break; case STATUS_PUSHED: m_surface->fill_rect(rect, c_theme::get_color(COLOR_WND_PUSHED), m_z_order); m_surface->draw_rect(rect, c_theme::get_color(COLOR_WND_BORDER), 2, m_z_order); c_word::draw_string_in_rect(m_surface, m_z_order, m_item_array[m_selected_item], rect, m_font, GL_RGB(2, 124, 165), GL_ARGB(0, 0, 0, 0), ALIGN_HCENTER | ALIGN_VCENTER); //draw list if (m_item_total > 0) { if (m_z_order == m_parent->get_z_order()) { m_z_order++; } m_attr = (WND_ATTRIBUTION)(ATTR_VISIBLE | ATTR_FOCUS | ATTR_PRIORITY); show_list(); } break; default: ASSERT(false); } } virtual void on_focus() { m_status = STATUS_FOCUSED; on_paint(); } virtual void on_kill_focus() { m_status = STATUS_NORMAL; on_paint(); } virtual void on_navigate(NAVIGATION_KEY key) { switch (key) { case NAV_ENTER: on_touch(m_wnd_rect.m_left, m_wnd_rect.m_top, TOUCH_DOWN); on_touch(m_wnd_rect.m_left, m_wnd_rect.m_top, TOUCH_UP); return; case NAV_BACKWARD: if (m_status != STATUS_PUSHED) { return c_wnd::on_navigate(key); } m_selected_item = (m_selected_item > 0) ? (m_selected_item - 1) : m_selected_item; return show_list(); case NAV_FORWARD: if (m_status != STATUS_PUSHED) { return c_wnd::on_navigate(key); } m_selected_item = (m_selected_item < (m_item_total - 1)) ? (m_selected_item + 1) : m_selected_item; return show_list(); } } virtual void on_touch(int x, int y, TOUCH_ACTION action) { (action == TOUCH_DOWN) ? on_touch_down(x, y) : on_touch_up(x, y); } private: void update_list_size() { m_list_wnd_rect = m_wnd_rect; m_list_wnd_rect.m_top = m_wnd_rect.m_bottom + 1; m_list_wnd_rect.m_bottom = m_list_wnd_rect.m_top + m_item_total * ITEM_HEIGHT; get_screen_rect(m_list_screen_rect); m_list_screen_rect.m_top = m_list_screen_rect.m_bottom + 1; m_list_screen_rect.m_bottom = m_list_screen_rect.m_top + m_item_total * ITEM_HEIGHT; } void show_list() { //draw all items c_rect tmp_rect; for (int i = 0; i < m_item_total; i++) { tmp_rect.m_left = m_list_screen_rect.m_left; tmp_rect.m_right = m_list_screen_rect.m_right; tmp_rect.m_top = m_list_screen_rect.m_top + i * ITEM_HEIGHT; tmp_rect.m_bottom = tmp_rect.m_top + ITEM_HEIGHT; if (m_selected_item == i) { m_surface->fill_rect(tmp_rect, c_theme::get_color(COLOR_WND_FOCUS), m_z_order); c_word::draw_string_in_rect(m_surface, m_z_order, m_item_array[i], tmp_rect, m_font, m_font_color, c_theme::get_color(COLOR_WND_FOCUS), ALIGN_HCENTER | ALIGN_VCENTER); } else { m_surface->fill_rect(tmp_rect, GL_RGB(17, 17, 17), m_z_order); c_word::draw_string_in_rect(m_surface, m_z_order, m_item_array[i], tmp_rect, m_font, m_font_color, GL_RGB(17, 17, 17), ALIGN_HCENTER | ALIGN_VCENTER); } } } void on_touch_down(int x, int y) { if (m_wnd_rect.pt_in_rect(x, y)) {//click base if (STATUS_NORMAL == m_status) { m_parent->set_child_focus(this); } } else if (m_list_wnd_rect.pt_in_rect(x, y)) {//click extend list c_wnd::on_touch(x, y, TOUCH_DOWN); } else { if (STATUS_PUSHED == m_status) { m_status = STATUS_FOCUSED; on_paint(); if(on_change) { (m_parent->*(on_change))(m_id, m_selected_item); } } } } void on_touch_up(int x, int y) { if (STATUS_FOCUSED == m_status) { m_status = STATUS_PUSHED; on_paint(); } else if (STATUS_PUSHED == m_status) { if (m_wnd_rect.pt_in_rect(x, y)) {//click base m_status = STATUS_FOCUSED; on_paint(); } else if (m_list_wnd_rect.pt_in_rect(x, y)) {//click extend list m_status = STATUS_FOCUSED; select_item((y - m_list_wnd_rect.m_top) / ITEM_HEIGHT); on_paint(); if(on_change) { (m_parent->*(on_change))(m_id, m_selected_item); } } else { c_wnd::on_touch(x, y, TOUCH_UP); } } } short m_selected_item; short m_item_total; char* m_item_array[MAX_ITEM_NUM]; c_rect m_list_wnd_rect; //rect relative to parent wnd. c_rect m_list_screen_rect; //rect relative to physical screen(frame buffer) WND_CALLBACK on_change; }; #include <stdlib.h> #define MAX_PAGES 5 class c_gesture; class c_slide_group : public c_wnd { public: inline c_slide_group(); int set_active_slide(int index, bool is_redraw = true) { if (index >= MAX_PAGES || index < 0) { return -1; } if (0 == m_slides[index]) { return -2; } m_active_slide_index = index; for (int i = 0; i < MAX_PAGES; i++) { if (m_slides[i] == 0) { continue; } if (i == index) { m_slides[i]->get_surface()->set_active(true); add_child_2_tail(m_slides[i]); if (is_redraw) { c_rect rc; get_screen_rect(rc); m_slides[i]->get_surface()->flush_screen(rc.m_left, rc.m_top, rc.m_right, rc.m_bottom); } } else { m_slides[i]->get_surface()->set_active(false); } } return 0; } c_wnd* get_slide(int index){return m_slides[index];} c_wnd* get_active_slide(){return m_slides[m_active_slide_index];} int get_active_slide_index(){return m_active_slide_index;} int add_slide(c_wnd* slide, unsigned short resource_id, short x, short y, short width, short height, WND_TREE* p_child_tree = 0, Z_ORDER_LEVEL max_zorder = Z_ORDER_LEVEL_0) { if (0 == slide) { return -1; } c_surface* old_surface = get_surface(); c_surface* new_surface = old_surface->get_display()->alloc_surface(max_zorder); new_surface->set_active(false); set_surface(new_surface); slide->connect(this, resource_id, 0, x, y, width, height, p_child_tree); set_surface(old_surface); int i = 0; while (i < MAX_PAGES) { if (m_slides[i] == slide) {//slide has lived ASSERT(false); return -2; } i++; } //new slide i = 0; while (i < MAX_PAGES) { if (m_slides[i] == 0) { m_slides[i] = slide; slide->show_window(); return 0; } i++; } //no more slide can be add ASSERT(false); return -3; } void disabel_all_slide() { for (int i = 0; i < MAX_PAGES; i++) { if (m_slides[i]) { m_slides[i]->get_surface()->set_active(false); } } } inline virtual void on_touch(int x, int y, TOUCH_ACTION action); virtual void on_navigate(NAVIGATION_KEY key) { if (m_slides[m_active_slide_index]) { m_slides[m_active_slide_index]->on_navigate(key); } } protected: c_wnd* m_slides[MAX_PAGES]; int m_active_slide_index; c_gesture* m_gesture; }; //#define SWIPE_STEP 300//for arm #define SWIPE_STEP 10//for PC & ANDROID #define MOVE_THRESHOLD 10 typedef enum { TOUCH_MOVE, TOUCH_IDLE }TOUCH_STATE; class c_slide_group; class c_gesture { public: c_gesture(c_slide_group* group) { m_slide_group = group; m_state = TOUCH_IDLE; m_down_x = m_down_y = m_move_x = m_move_y = 0; } bool handle_swipe(int x, int y, TOUCH_ACTION action) { if (action == TOUCH_DOWN)//MOUSE_LBUTTONDOWN { if (m_state == TOUCH_IDLE) { m_state = TOUCH_MOVE; m_move_x = m_down_x = x; return true; } else//TOUCH_MOVE { return on_move(x); } } else if (action == TOUCH_UP)//MOUSE_LBUTTONUP { if (m_state == TOUCH_MOVE) { m_state = TOUCH_IDLE; return on_swipe(x); } else { return false; //ASSERT(false); } } return true; } private: bool on_move(int x) { if (m_slide_group == 0) { return true; } if (abs(x - m_move_x) < MOVE_THRESHOLD) { return false; } m_slide_group->disabel_all_slide(); m_move_x = x; if ((m_move_x - m_down_x) > 0) { move_right(); } else { move_left(); } return false; } bool on_swipe(int x) { if (m_slide_group == 0) { return true; } if ((m_down_x == m_move_x) && (abs(x - m_down_x) < MOVE_THRESHOLD)) { return true; } m_slide_group->disabel_all_slide(); int page = -1; m_move_x = x; if ((m_move_x - m_down_x) > 0) { page = swipe_right(); } else { page = swipe_left(); } if (page >= 0) { m_slide_group->set_active_slide(page); } else { m_slide_group->set_active_slide(m_slide_group->get_active_slide_index(), false); } return false; } int swipe_left() { if (m_slide_group == 0) { return -1; } int index = m_slide_group->get_active_slide_index(); if ((index + 1) >= MAX_PAGES || m_slide_group->get_slide(index + 1) == 0 || m_slide_group->get_slide(index) == 0) { return -2; } c_surface* s1 = m_slide_group->get_slide(index + 1)->get_surface(); c_surface * s2 = m_slide_group->get_slide(index)->get_surface(); if (s1->get_display() != s2->get_display()) { return -3; } int step = m_down_x - m_move_x; c_rect rc; m_slide_group->get_screen_rect(rc); while (step < rc.width()) { s1->get_display()->swipe_surface(s2, s1, rc.m_left, rc.m_right, rc.m_top, rc.m_bottom, step); step += SWIPE_STEP; } if (step != rc.width()) { s1->get_display()->swipe_surface(s2, s1, rc.m_left, rc.m_right, rc.m_top, rc.m_bottom, rc.width()); } return (index + 1); } int swipe_right() { if (m_slide_group == 0) { return -1; } int index = m_slide_group->get_active_slide_index(); if (index <= 0 || m_slide_group->get_slide(index - 1) == 0 || m_slide_group->get_slide(index) == 0) { return -2; } c_surface* s1 = m_slide_group->get_slide(index - 1)->get_surface(); c_surface * s2 = m_slide_group->get_slide(index)->get_surface(); if (s1->get_display() != s2->get_display()) { return -3; } c_rect rc; m_slide_group->get_screen_rect(rc); int step = rc.width() - (m_move_x - m_down_x); while (step > 0) { s1->get_display()->swipe_surface(s1, s2, rc.m_left, rc.m_right, rc.m_top, rc.m_bottom, step); step -= SWIPE_STEP; } if (step != 0) { s1->get_display()->swipe_surface(s1, s2, rc.m_left, rc.m_right, rc.m_top, rc.m_bottom, 0); } return (index - 1); } void move_left() { int index = m_slide_group->get_active_slide_index(); if ((index + 1) >= MAX_PAGES || m_slide_group->get_slide(index + 1) == 0 || m_slide_group->get_slide(index) == 0) { return; } c_surface* s1 = m_slide_group->get_slide(index + 1)->get_surface(); c_surface * s2 = m_slide_group->get_slide(index)->get_surface(); c_rect rc; m_slide_group->get_screen_rect(rc); if (s1->get_display() == s2->get_display()) { s1->get_display()->swipe_surface(s2, s1, rc.m_left, rc.m_right, rc.m_top, rc.m_bottom, (m_down_x - m_move_x)); } } void move_right() { int index = m_slide_group->get_active_slide_index(); if (index <= 0 || m_slide_group->get_slide(index - 1) == 0 || m_slide_group->get_slide(index) == 0) { return; } c_surface* s1 = m_slide_group->get_slide(index - 1)->get_surface(); c_surface * s2 = m_slide_group->get_slide(index)->get_surface(); c_rect rc; m_slide_group->get_screen_rect(rc); if (s1->get_display() == s2->get_display()) { s1->get_display()->swipe_surface(s1, s2, rc.m_left, rc.m_right, rc.m_top, rc.m_bottom, (rc.width() - (m_move_x - m_down_x))); } } int m_down_x; int m_down_y; int m_move_x; int m_move_y; TOUCH_STATE m_state; c_slide_group* m_slide_group; }; inline c_slide_group::c_slide_group() { m_gesture = new c_gesture(this); for (int i = 0; i < MAX_PAGES; i++) { m_slides[i] = 0; } m_active_slide_index = 0; } inline void c_slide_group::on_touch(int x, int y, TOUCH_ACTION action) { x -= m_wnd_rect.m_left; y -= m_wnd_rect.m_top; if (m_gesture->handle_swipe(x, y, action)) { if (m_slides[m_active_slide_index]) { m_slides[m_active_slide_index]->on_touch(x, y, action); } } } #define ID_BT_ARROW_UP 0x1111 #define ID_BT_ARROW_DOWN 0x2222 class c_spin_box; class c_spin_button : public c_button { friend class c_spin_box; inline virtual void on_touch(int x, int y, TOUCH_ACTION action); c_spin_box* m_spin_box; }; class c_spin_box : public c_wnd { friend class c_spin_button; public: short get_value() { return m_value; } void set_value(unsigned short value) { m_value = m_cur_value = value; } void set_max_min(short max, short min) { m_max = max; m_min = min; } void set_step(short step) { m_step = step; } short get_min() { return m_min; } short get_max() { return m_max; } short get_step() { return m_step; } void set_value_digit(short digit) { m_digit = digit; } short get_value_digit() { return m_digit; } void set_on_change(WND_CALLBACK on_change) { this->on_change = on_change; } protected: virtual void on_paint() { c_rect rect; get_screen_rect(rect); rect.m_right = rect.m_left + (rect.width() * 2 / 3); m_surface->fill_rect(rect, c_theme::get_color(COLOR_WND_NORMAL), m_z_order); c_word::draw_value_in_rect(m_surface, m_parent->get_z_order(), m_cur_value, m_digit, rect, m_font, m_font_color, c_theme::get_color(COLOR_WND_NORMAL), ALIGN_HCENTER | ALIGN_VCENTER); } virtual void pre_create_wnd() { m_attr = (WND_ATTRIBUTION)(ATTR_VISIBLE); m_font = c_theme::get_font(FONT_DEFAULT); m_font_color = c_theme::get_color(COLOR_WND_FONT); m_max = 6; m_min = 1; m_digit = 0; m_step = 1; //link arrow button position. c_rect rect; get_wnd_rect(rect); m_bt_down.m_spin_box = m_bt_up.m_spin_box = this; m_bt_up.connect(m_parent, ID_BT_ARROW_UP, "+", (rect.m_left + rect.width() * 2 / 3), rect.m_top, (rect.width() / 3), (rect.height() / 2)); m_bt_down.connect(m_parent, ID_BT_ARROW_DOWN, "-", (rect.m_left + rect.width() * 2 / 3), (rect.m_top + rect.height() / 2), (rect.width() / 3), (rect.height() / 2)); } void on_arrow_up_bt_click() { if (m_cur_value + m_step > m_max) { return; } m_cur_value += m_step; if(on_change) { (m_parent->*(on_change))(m_id, m_cur_value); } on_paint(); } void on_arrow_down_bt_click() { if (m_cur_value - m_step < m_min) { return; } m_cur_value -= m_step; if(on_change) { (m_parent->*(on_change))(m_id, m_cur_value); } on_paint(); } short m_cur_value; short m_value; short m_step; short m_max; short m_min; short m_digit; c_spin_button m_bt_up; c_spin_button m_bt_down; WND_CALLBACK on_change; }; inline void c_spin_button::on_touch(int x, int y, TOUCH_ACTION action) { if (action == TOUCH_UP) { (m_id == ID_BT_ARROW_UP) ? m_spin_box->on_arrow_up_bt_click() : m_spin_box->on_arrow_down_bt_click(); } c_button::on_touch(x, y, action); } #define MAX_COL_NUM 30 #define MAX_ROW_NUM 30 class c_table: public c_wnd { public: void set_sheet_align(unsigned int align_type){ m_align_type = align_type;} void set_row_num(unsigned int row_num){ m_row_num = row_num;} void set_col_num(unsigned int col_num){ m_col_num = col_num;} void set_row_height(unsigned int height) { for (unsigned int i = 0; i < m_row_num; i++) { m_row_height[i] = height; } } void set_col_width(unsigned int width) { for (unsigned int i = 0; i < m_col_num; i++) { m_col_width[i] = width; } } int set_row_height(unsigned int index, unsigned int height) { if (m_row_num > index) { m_row_height[index] = height; return index; } return -1; } int set_col_width(unsigned int index, unsigned int width) { if (m_col_num > index) { m_col_width[index] = width; return index; } return -1; } void set_item(int row, int col, char* str, unsigned int color) { draw_item(row, col, str, color); } unsigned int get_row_num(){ return m_row_num;} unsigned int get_col_num(){ return m_col_num;} c_rect get_item_rect(int row, int col) { static c_rect rect; if (row >= MAX_ROW_NUM || col >= MAX_COL_NUM) { return rect; } unsigned int width = 0; unsigned int height = 0; for (int i = 0; i < col; i++) { width += m_col_width[i]; } for (int j = 0; j < row; j++) { height += m_row_height[j]; } c_rect wRect; get_screen_rect(wRect); rect.m_left = wRect.m_left + width; rect.m_right = rect.m_left + m_col_width[col]; if (rect.m_right > wRect.m_right) { rect.m_right = wRect.m_right; } rect.m_top = wRect.m_top + height; rect.m_bottom = rect.m_top + m_row_height[row]; if (rect.m_bottom > wRect.m_bottom) { rect.m_bottom = wRect.m_bottom; } return rect; } protected: virtual void pre_create_wnd() { m_attr = (WND_ATTRIBUTION)(ATTR_VISIBLE); m_font = c_theme::get_font(FONT_DEFAULT); m_font_color = c_theme::get_color(COLOR_WND_FONT); } void draw_item(int row, int col, const char* str, unsigned int color) { c_rect rect = get_item_rect(row, col); m_surface->fill_rect(rect.m_left + 1, rect.m_top + 1, rect.m_right - 1, rect.m_bottom - 1, color, m_z_order); c_word::draw_string_in_rect(m_surface, m_z_order, str, rect, m_font, m_font_color, GL_ARGB(0, 0, 0, 0), m_align_type); } unsigned int m_align_type; unsigned int m_row_num; unsigned int m_col_num; unsigned int m_row_height[MAX_ROW_NUM]; unsigned int m_col_width[MAX_COL_NUM]; }; #include <string.h> #include <stdio.h> #define WAVE_BUFFER_LEN 1024 #define WAVE_READ_CACHE_LEN 8 #define BUFFER_EMPTY -1111 #define BUFFER_FULL -2222; class c_wave_buffer { public: c_wave_buffer() { m_head = m_tail = m_min_old = m_max_old = m_min_older = m_max_older = m_last_data = m_read_cache_sum = m_refresh_sequence = 0; memset(m_wave_buf, 0, sizeof(m_wave_buf)); memset(m_read_cache_min, 0, sizeof(m_read_cache_min)); memset(m_read_cache_mid, 0, sizeof(m_read_cache_mid)); memset(m_read_cache_max, 0, sizeof(m_read_cache_max)); } int write_wave_data(short data) { if ((m_tail + 1) % WAVE_BUFFER_LEN == m_head) {//full //log_out("wave buf full\n"); return BUFFER_FULL; } m_wave_buf[m_tail] = data; m_tail = (m_tail + 1) % WAVE_BUFFER_LEN; return 1; } int read_wave_data_by_frame(short &max, short &min, short frame_len, unsigned int sequence, short offset) { if (m_refresh_sequence != sequence) { m_refresh_sequence = sequence; m_read_cache_sum = 0; } else if (offset < m_read_cache_sum)//(m_refresh_sequence == sequence && offset < m_fb_sum) { max = m_read_cache_max[offset]; min = m_read_cache_min[offset]; return m_read_cache_mid[offset]; } m_read_cache_sum++; ASSERT(m_read_cache_sum <= WAVE_READ_CACHE_LEN); int i, data; int tmp_min = m_last_data; int tmp_max = m_last_data; int mid = (m_min_old + m_max_old) >> 1; i = 0; while (i++ < frame_len) { data = read_data(); if (BUFFER_EMPTY == data) { break; } m_last_data = data; if (data < tmp_min) { tmp_min = data; } if (data > tmp_max) { tmp_max = data; } } min = m_read_cache_min[offset] = MIN(m_min_old, MIN(tmp_min, m_min_older)); max = m_read_cache_max[offset] = MAX(m_max_old, MAX(tmp_max, m_max_older)); m_min_older = m_min_old; m_max_older = m_max_old; m_min_old = tmp_min; m_max_old = tmp_max; return (m_read_cache_mid[offset] = mid); } void reset() { m_head = m_tail; } void clear_data() { m_head = m_tail = 0; memset(m_wave_buf, 0, sizeof(m_wave_buf)); } short get_cnt() { return (m_tail >= m_head) ? (m_tail - m_head) : (m_tail - m_head + WAVE_BUFFER_LEN); } private: int read_data() { if (m_head == m_tail) {//empty //log_out("wave buf empty\n"); return BUFFER_EMPTY; } int ret = m_wave_buf[m_head]; m_head = (m_head + 1) % WAVE_BUFFER_LEN; return ret; } short m_wave_buf[WAVE_BUFFER_LEN]; short m_head; short m_tail; int m_min_old; int m_max_old; int m_min_older; int m_max_older; int m_last_data; short m_read_cache_min[WAVE_READ_CACHE_LEN]; short m_read_cache_mid[WAVE_READ_CACHE_LEN]; short m_read_cache_max[WAVE_READ_CACHE_LEN]; short m_read_cache_sum; unsigned int m_refresh_sequence; }; #include <stdlib.h> #include <string.h> #define CORRECT(x, high_limit, low_limit) {\ x = (x > high_limit) ? high_limit : x;\ x = (x < low_limit) ? low_limit : x;\ }while(0) #define WAVE_CURSOR_WIDTH 8 #define WAVE_LINE_WIDTH 1 #define WAVE_MARGIN 5 typedef enum { FILL_MODE, SCAN_MODE }E_WAVE_DRAW_MODE; class c_wave_buffer; class c_wave_ctrl : public c_wnd { public: c_wave_ctrl() { m_wave = 0; m_bg_fb = 0; m_wave_name_font = m_wave_unit_font = 0; m_wave_name = m_wave_unit = 0; m_max_data = 500; m_min_data = 0; m_wave_speed = 1; m_wave_data_rate = 0; m_wave_refresh_rate = 1000; m_frame_len_map_index = 0; m_wave_name_color = m_wave_unit_color = m_wave_color = GL_RGB(255, 0, 0); m_back_color = GL_RGB(0, 0, 0); } virtual void on_init_children()//should be pre_create { c_rect rect; get_screen_rect(rect); m_wave_left = rect.m_left + WAVE_MARGIN; m_wave_right = rect.m_right - WAVE_MARGIN; m_wave_top = rect.m_top + WAVE_MARGIN; m_wave_bottom = rect.m_bottom - WAVE_MARGIN; m_wave_cursor = m_wave_left; m_bg_fb = (unsigned int*)calloc(rect.width() * rect.height(), 4); } virtual void on_paint() { c_rect rect; get_screen_rect(rect); m_surface->fill_rect(rect, m_back_color, m_z_order); //show name c_word::draw_string(m_surface, m_z_order, m_wave_name, m_wave_left + 10, rect.m_top, m_wave_name_font, m_wave_name_color, GL_ARGB(0, 0, 0, 0)); //show unit c_word::draw_string(m_surface, m_z_order, m_wave_unit, m_wave_left + 60, rect.m_top, m_wave_unit_font, m_wave_unit_color, GL_ARGB(0, 0, 0, 0)); save_background(); } void set_wave_name(char* wave_name){ m_wave_name = wave_name;} void set_wave_unit(char* wave_unit){ m_wave_unit = wave_unit;} void set_wave_name_font(const LATTICE_FONT_INFO* wave_name_font_type){ m_wave_name_font = wave_name_font_type;} void set_wave_unit_font(const LATTICE_FONT_INFO* wave_unit_font_type){ m_wave_unit_font = wave_unit_font_type;} void set_wave_name_color(unsigned int wave_name_color){ m_wave_name_color = wave_name_color;} void set_wave_unit_color(unsigned int wave_unit_color){ m_wave_unit_color = wave_unit_color;} void set_wave_color(unsigned int color){ m_wave_color = color;} void set_wave_in_out_rate(unsigned int data_rate, unsigned int refresh_rate) { m_wave_data_rate = data_rate; m_wave_refresh_rate = refresh_rate; int read_times_per_second = m_wave_speed * 1000 / m_wave_refresh_rate; memset(m_frame_len_map, 0, sizeof(m_frame_len_map)); for (unsigned int i = 1; i < sizeof(m_frame_len_map) + 1; i++) { m_frame_len_map[i - 1] = data_rate * i / read_times_per_second - data_rate * (i - 1) / read_times_per_second; } m_frame_len_map_index = 0; } void set_wave_speed(unsigned int speed) { m_wave_speed = speed; set_wave_in_out_rate(m_wave_data_rate, m_wave_refresh_rate); } void set_max_min(short max_data, short min_data) { m_max_data = max_data; m_min_data = min_data; } void set_wave(c_wave_buffer* wave){m_wave = wave;} c_wave_buffer* get_wave(){return m_wave;} void clear_data() { if (m_wave == 0) { ASSERT(false); return; } m_wave->clear_data(); } bool is_data_enough() { if (m_wave == 0) { ASSERT(false); return false; } return (m_wave->get_cnt() - m_frame_len_map[m_frame_len_map_index] * m_wave_speed); } void refresh_wave(unsigned char frame) { if (m_wave == 0) { ASSERT(false); return; } short max, min, mid; for (short offset = 0; offset < m_wave_speed; offset++) { //get wave value mid = m_wave->read_wave_data_by_frame(max, min, m_frame_len_map[m_frame_len_map_index++], frame, offset); m_frame_len_map_index %= sizeof(m_frame_len_map); //map to wave ctrl int y_min, y_max; if (m_max_data == m_min_data) { ASSERT(false); } y_max = m_wave_bottom + WAVE_LINE_WIDTH - (m_wave_bottom - m_wave_top) * (min - m_min_data) / (m_max_data - m_min_data); y_min = m_wave_bottom - WAVE_LINE_WIDTH - (m_wave_bottom - m_wave_top) * (max - m_min_data) / (m_max_data - m_min_data); mid = m_wave_bottom - (m_wave_bottom - m_wave_top) * (mid - m_min_data) / (m_max_data - m_min_data); CORRECT(y_min, m_wave_bottom, m_wave_top); CORRECT(y_max, m_wave_bottom, m_wave_top); CORRECT(mid, m_wave_bottom, m_wave_top); if (m_wave_cursor > m_wave_right) { m_wave_cursor = m_wave_left; } draw_smooth_vline(y_min, y_max, mid, m_wave_color); restore_background(); m_wave_cursor++; } } void clear_wave() { m_surface->fill_rect(m_wave_left, m_wave_top, m_wave_right, m_wave_bottom, m_back_color, m_z_order); m_wave_cursor = m_wave_left; } protected: void draw_smooth_vline(int y_min, int y_max, int mid, unsigned int rgb) { int dy = y_max - y_min; short r = GL_RGB_R(rgb); short g = GL_RGB_G(rgb); short b = GL_RGB_B(rgb); int index = (dy >> 1) + 2; int y; m_surface->draw_pixel(m_wave_cursor, mid, rgb, m_z_order); if (dy < 1) { return; } unsigned char cur_r, cur_g, cur_b; unsigned int cur_rgb; for (int i = 1; i <= (dy >> 1) + 1; ++i) { if ((mid + i) <= y_max) { y = mid + i; cur_r = r * (index - i) / index; cur_g = g * (index - i) / index; cur_b = b * (index - i) / index; cur_rgb = GL_RGB(cur_r, cur_g, cur_b); m_surface->draw_pixel(m_wave_cursor, y, cur_rgb, m_z_order); } if ((mid - i) >= y_min) { y = mid - i; cur_r = r * (index - i) / index; cur_g = g * (index - i) / index; cur_b = b * (index - i) / index; cur_rgb = GL_RGB(cur_r, cur_g, cur_b); m_surface->draw_pixel(m_wave_cursor, y, cur_rgb, m_z_order); } } } void restore_background() { int x = m_wave_cursor + WAVE_CURSOR_WIDTH; if (x > m_wave_right) { x -= (m_wave_right - m_wave_left + 1); } c_rect rect; get_screen_rect(rect); register int width = rect.width(); register int top = rect.m_top; register int left = rect.m_left; for (int y_pos = (m_wave_top - 1); y_pos <= (m_wave_bottom + 1); y_pos++) { (m_bg_fb) ? m_surface->draw_pixel(x, y_pos, m_bg_fb[(y_pos - top) * width + (x - left)], m_z_order) : m_surface->draw_pixel(x, y_pos, 0, m_z_order); } } void save_background() { if (!m_bg_fb) { return; } c_rect rect; get_screen_rect(rect); register unsigned int* p_des = m_bg_fb; for (int y = rect.m_top; y <= rect.m_bottom; y++) { for (int x = rect.m_left; x <= rect.m_right; x++) { *p_des++ = m_surface->get_pixel(x, y, m_z_order); } } } char* m_wave_name; char* m_wave_unit; const LATTICE_FONT_INFO* m_wave_name_font; const LATTICE_FONT_INFO* m_wave_unit_font; unsigned int m_wave_name_color; unsigned int m_wave_unit_color; unsigned int m_wave_color; unsigned int m_back_color; int m_wave_left; int m_wave_right; int m_wave_top; int m_wave_bottom; short m_max_data; short m_min_data; private: c_wave_buffer* m_wave; unsigned int* m_bg_fb; //background frame buffer, could be used to draw scale line. int m_wave_cursor; int m_wave_speed; //pixels per refresh unsigned int m_wave_data_rate; //data sample rate unsigned int m_wave_refresh_rate;//refresh cycle in millisecond unsigned char m_frame_len_map[64]; unsigned char m_frame_len_map_index; }; #ifdef GUILITE_ON c_bitmap_operator the_bitmap_op = c_bitmap_operator(); c_image_operator* c_image::image_operator = &the_bitmap_op; #endif #ifdef GUILITE_ON const void* c_theme::s_font_map[FONT_MAX]; const void* c_theme::s_image_map[IMAGE_MAX]; unsigned int c_theme::s_color_map[COLOR_MAX]; #endif #ifdef GUILITE_ON c_lattice_font_op the_lattice_font_op = c_lattice_font_op(); c_font_operator* c_word::fontOperator = &the_lattice_font_op; #endif #ifdef GUILITE_ON #if (defined __linux__) || (defined __APPLE__) #include <unistd.h> #include <pthread.h> #include <string.h> #include <time.h> #include <sys/time.h> #include <signal.h> #include <sys/times.h> #include <fcntl.h> #include <termios.h> #include <sys/stat.h> #include <semaphore.h> #include <errno.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #define MAX_TIMER_CNT 10 #define TIMER_UNIT 50//ms static void(*do_assert)(const char* file, int line); static void(*do_log_out)(const char* log); void register_debug_function(void(*my_assert)(const char* file, int line), void(*my_log_out)(const char* log)) { do_assert = my_assert; do_log_out = my_log_out; } void _assert(const char* file, int line) { if(do_assert) { do_assert(file, line); } else { printf("assert@ file:%s, line:%d, error no: %d\n", file, line, errno); } } void log_out(const char* log) { if (do_log_out) { do_log_out(log); } else { printf("%s", log); fflush(stdout); } } typedef struct _timer_manage { struct _timer_info { int state; /* on or off */ int interval; int elapse; /* 0~interval */ void (* timer_proc) (void* param); void* param; }timer_info[MAX_TIMER_CNT]; void (* old_sigfunc)(int); void (* new_sigfunc)(int); }_timer_manage_t; static struct _timer_manage timer_manage; static void* timer_routine(void*) { int i; while(true) { for(i = 0; i < MAX_TIMER_CNT; i++) { if(timer_manage.timer_info[i].state == 0) { continue; } timer_manage.timer_info[i].elapse++; if(timer_manage.timer_info[i].elapse == timer_manage.timer_info[i].interval) { timer_manage.timer_info[i].elapse = 0; timer_manage.timer_info[i].timer_proc(timer_manage.timer_info[i].param); } } usleep(1000 * TIMER_UNIT); } return NULL; } static int init_mul_timer() { static bool s_is_init = false; if(s_is_init == true) { return 0; } memset(&timer_manage, 0, sizeof(struct _timer_manage)); pthread_t pid; pthread_create(&pid, NULL, timer_routine, NULL); s_is_init = true; return 1; } static int set_a_timer(int interval, void (* timer_proc)(void* param), void* param) { init_mul_timer(); int i; if(timer_proc == NULL || interval <= 0) { return (-1); } for(i = 0; i < MAX_TIMER_CNT; i++) { if(timer_manage.timer_info[i].state == 1) { continue; } memset(&timer_manage.timer_info[i], 0, sizeof(timer_manage.timer_info[i])); timer_manage.timer_info[i].timer_proc = timer_proc; timer_manage.timer_info[i].param = param; timer_manage.timer_info[i].interval = interval; timer_manage.timer_info[i].elapse = 0; timer_manage.timer_info[i].state = 1; break; } if(i >= MAX_TIMER_CNT) { ASSERT(false); return (-1); } return (i); } typedef void (*EXPIRE_ROUTINE)(void* arg); EXPIRE_ROUTINE s_expire_function; static c_fifo s_real_timer_fifo; static void* real_timer_routine(void*) { char dummy; while(1) { if(s_real_timer_fifo.read(&dummy, 1) > 0) { if(s_expire_function)s_expire_function(0); } else { ASSERT(false); } } return 0; } static void expire_real_timer(int sigo) { char dummy = 0x33; if(s_real_timer_fifo.write(&dummy, 1) <= 0) { ASSERT(false); } } void start_real_timer(void (*func)(void* arg)) { if(NULL == func) { return; } s_expire_function = func; signal(SIGALRM, expire_real_timer); struct itimerval value, ovalue; value.it_value.tv_sec = 0; value.it_value.tv_usec = REAL_TIME_TASK_CYCLE_MS * 1000; value.it_interval.tv_sec = 0; value.it_interval.tv_usec = REAL_TIME_TASK_CYCLE_MS * 1000; setitimer(ITIMER_REAL, &value, &ovalue); static pthread_t s_pid; if(s_pid == 0) { pthread_create(&s_pid, NULL, real_timer_routine, NULL); } } unsigned int get_cur_thread_id() { return (unsigned long)pthread_self(); } void register_timer(int milli_second,void func(void* param), void* param) { set_a_timer(milli_second/TIMER_UNIT,func, param); } long get_time_in_second() { return time(NULL); /* + 8*60*60*/ } T_TIME get_time() { T_TIME ret = {0}; struct tm *fmt; time_t timer; timer = get_time_in_second(); fmt = localtime(&timer); ret.year = fmt->tm_year + 1900; ret.month = fmt->tm_mon + 1; ret.day = fmt->tm_mday; ret.hour = fmt->tm_hour; ret.minute = fmt->tm_min; ret.second = fmt->tm_sec; return ret; } T_TIME second_to_day(long second) { T_TIME ret = {0}; struct tm *fmt; fmt = localtime(&second); ret.year = fmt->tm_year + 1900; ret.month = fmt->tm_mon + 1; ret.day = fmt->tm_mday; ret.hour = fmt->tm_hour; ret.minute = fmt->tm_min; ret.second = fmt->tm_sec; return ret; } void create_thread(unsigned long* thread_id, void* attr, void *(*start_routine) (void *), void* arg) { pthread_create((pthread_t*)thread_id, (pthread_attr_t const*)attr, start_routine, arg); } void thread_sleep(unsigned int milli_seconds) { usleep(milli_seconds * 1000); } typedef struct { unsigned short bfType; unsigned int bfSize; unsigned short bfReserved1; unsigned short bfReserved2; unsigned int bfOffBits; }__attribute__((packed))FileHead; typedef struct{ unsigned int biSize; int biWidth; int biHeight; unsigned short biPlanes; unsigned short biBitCount; unsigned int biCompress; unsigned int biSizeImage; int biXPelsPerMeter; int biYPelsPerMeter; unsigned int biClrUsed; unsigned int biClrImportant; unsigned int biRedMask; unsigned int biGreenMask; unsigned int biBlueMask; }__attribute__((packed))Infohead; int build_bmp(const char *filename, unsigned int width, unsigned int height, unsigned char *data) { FileHead bmp_head; Infohead bmp_info; int size = width * height * 2; //initialize bmp head. bmp_head.bfType = 0x4d42; bmp_head.bfSize = size + sizeof(FileHead) + sizeof(Infohead); bmp_head.bfReserved1 = bmp_head.bfReserved2 = 0; bmp_head.bfOffBits = bmp_head.bfSize - size; //initialize bmp info. bmp_info.biSize = 40; bmp_info.biWidth = width; bmp_info.biHeight = height; bmp_info.biPlanes = 1; bmp_info.biBitCount = 16; bmp_info.biCompress = 3; bmp_info.biSizeImage = size; bmp_info.biXPelsPerMeter = 0; bmp_info.biYPelsPerMeter = 0; bmp_info.biClrUsed = 0; bmp_info.biClrImportant = 0; //RGB565 bmp_info.biRedMask = 0xF800; bmp_info.biGreenMask = 0x07E0; bmp_info.biBlueMask = 0x001F; //copy the data FILE *fp; if(!(fp=fopen(filename,"wb"))) { return -1; } fwrite(&bmp_head, 1, sizeof(FileHead),fp); fwrite(&bmp_info, 1, sizeof(Infohead),fp); //fwrite(data, 1, size, fp);//top <-> bottom for (int i = (height - 1); i >= 0; --i) { fwrite(&data[i * width * 2], 1, width * 2, fp); } fclose(fp); return 0; } c_fifo::c_fifo() { m_head = m_tail = 0; m_read_sem = malloc(sizeof(sem_t)); m_write_mutex = malloc(sizeof(pthread_mutex_t)); sem_init((sem_t*)m_read_sem, 0, 0); pthread_mutex_init((pthread_mutex_t*)m_write_mutex, 0); } int c_fifo::read(void* buf, int len) { unsigned char* pbuf = (unsigned char*)buf; int i = 0; while(i < len) { if (m_tail == m_head) {//empty sem_wait((sem_t*)m_read_sem); continue; } *pbuf++ = m_buf[m_head]; m_head = (m_head + 1) % FIFO_BUFFER_LEN; i++; } if(i != len) { ASSERT(false); } return i; } int c_fifo::write(void* buf, int len) { unsigned char* pbuf = (unsigned char*)buf; int i = 0; int tail = m_tail; pthread_mutex_lock((pthread_mutex_t*)m_write_mutex); while(i < len) { if ((m_tail + 1) % FIFO_BUFFER_LEN == m_head) {//full, clear data has been written; m_tail = tail; log_out("Warning: fifo full\n"); pthread_mutex_unlock((pthread_mutex_t*)m_write_mutex); return 0; } m_buf[m_tail] = *pbuf++; m_tail = (m_tail + 1) % FIFO_BUFFER_LEN; i++; } pthread_mutex_unlock((pthread_mutex_t*)m_write_mutex); if(i != len) { ASSERT(false); } else { sem_post((sem_t*)m_read_sem); } return i; } #endif #endif #ifdef GUILITE_ON #if (!defined _WIN32) && (!defined WIN32) && (!defined _WIN64) && (!defined WIN64) && (!defined __linux__) && (!defined __APPLE__) #include <stdio.h> static void(*do_assert)(const char* file, int line); static void(*do_log_out)(const char* log); void register_debug_function(void(*my_assert)(const char* file, int line), void(*my_log_out)(const char* log)) { do_assert = my_assert; do_log_out = my_log_out; } void _assert(const char* file, int line) { if(do_assert) { do_assert(file, line); } while(1); } void log_out(const char* log) { if (do_log_out) { do_log_out(log); } } long get_time_in_second() { return 0; } T_TIME second_to_day(long second) { T_TIME ret = {0}; return ret; } T_TIME get_time() { T_TIME ret = {0}; return ret; } void start_real_timer(void (*func)(void* arg)) { log_out("Not support now"); } void register_timer(int milli_second, void func(void* ptmr, void* parg)) { log_out("Not support now"); } unsigned int get_cur_thread_id() { log_out("Not support now"); return 0; } void create_thread(unsigned long* thread_id, void* attr, void *(*start_routine) (void *), void* arg) { log_out("Not support now"); } extern "C" void delay_ms(unsigned short nms); void thread_sleep(unsigned int milli_seconds) {//MCU alway implemnet driver code in APP. delay_ms(milli_seconds); } int build_bmp(const char *filename, unsigned int width, unsigned int height, unsigned char *data) { log_out("Not support now"); return 0; } c_fifo::c_fifo() { m_head = m_tail = 0; m_read_sem = m_write_mutex = 0; } int c_fifo::read(void* buf, int len) { unsigned char* pbuf = (unsigned char*)buf; int i = 0; while(i < len) { if (m_tail == m_head) {//empty continue; } *pbuf++ = m_buf[m_head]; m_head = (m_head + 1) % FIFO_BUFFER_LEN; i++; } if(i != len) { ASSERT(false); } return i; } int c_fifo::write(void* buf, int len) { unsigned char* pbuf = (unsigned char*)buf; int i = 0; int tail = m_tail; while(i < len) { if ((m_tail + 1) % FIFO_BUFFER_LEN == m_head) {//full, clear data has been written; m_tail = tail; log_out("Warning: fifo full\n"); return 0; } m_buf[m_tail] = *pbuf++; m_tail = (m_tail + 1) % FIFO_BUFFER_LEN; i++; } if(i != len) { ASSERT(false); } return i; } #endif #endif #ifdef GUILITE_ON #if (defined _WIN32) || (defined WIN32) || (defined _WIN64) || (defined WIN64) #include <string.h> #include <stdio.h> #include <time.h> #include <conio.h> #include <windows.h> #include <assert.h> #define MAX_TIMER_CNT 10 #define TIMER_UNIT 50//ms static void(*do_assert)(const char* file, int line); static void(*do_log_out)(const char* log); void register_debug_function(void(*my_assert)(const char* file, int line), void(*my_log_out)(const char* log)) { do_assert = my_assert; do_log_out = my_log_out; } void _assert(const char* file, int line) { static char s_buf[192]; if (do_assert) { do_assert(file, line); } else { memset(s_buf, 0, sizeof(s_buf)); sprintf_s(s_buf, sizeof(s_buf), "vvvvvvvvvvvvvvvvvvvvvvvvvvvv\n\nAssert@ file = %s, line = %d\n\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", file, line); OutputDebugStringA(s_buf); printf("%s", s_buf); fflush(stdout); assert(false); } } void log_out(const char* log) { if (do_log_out) { do_log_out(log); } else { printf("%s", log); fflush(stdout); OutputDebugStringA(log); } } typedef struct _timer_manage { struct _timer_info { int state; /* on or off */ int interval; int elapse; /* 0~interval */ void (* timer_proc) (void* param); void* param; }timer_info[MAX_TIMER_CNT]; void (* old_sigfunc)(int); void (* new_sigfunc)(int); }_timer_manage_t; static struct _timer_manage timer_manage; DWORD WINAPI timer_routine(LPVOID lpParam) { int i; while(true) { for(i = 0; i < MAX_TIMER_CNT; i++) { if(timer_manage.timer_info[i].state == 0) { continue; } timer_manage.timer_info[i].elapse++; if(timer_manage.timer_info[i].elapse == timer_manage.timer_info[i].interval) { timer_manage.timer_info[i].elapse = 0; timer_manage.timer_info[i].timer_proc(timer_manage.timer_info[i].param); } } Sleep(TIMER_UNIT); } return 0; } static int init_mul_timer() { static bool s_is_init = false; if(s_is_init == true) { return 0; } memset(&timer_manage, 0, sizeof(struct _timer_manage)); DWORD pid; CreateThread(0, 0, timer_routine, 0, 0, &pid); s_is_init = true; return 1; } static int set_a_timer(int interval, void (* timer_proc) (void* param), void* param) { init_mul_timer(); int i; if(timer_proc == 0 || interval <= 0) { return (-1); } for(i = 0; i < MAX_TIMER_CNT; i++) { if(timer_manage.timer_info[i].state == 1) { continue; } memset(&timer_manage.timer_info[i], 0, sizeof(timer_manage.timer_info[i])); timer_manage.timer_info[i].timer_proc = timer_proc; timer_manage.timer_info[i].param = param; timer_manage.timer_info[i].interval = interval; timer_manage.timer_info[i].elapse = 0; timer_manage.timer_info[i].state = 1; break; } if(i >= MAX_TIMER_CNT) { ASSERT(false); return (-1); } return (i); } typedef void (*EXPIRE_ROUTINE)(void* arg); EXPIRE_ROUTINE s_expire_function; static c_fifo s_real_timer_fifo; static DWORD WINAPI fire_real_timer(LPVOID lpParam) { char dummy; while(1) { if(s_real_timer_fifo.read(&dummy, 1) > 0) { if(s_expire_function)s_expire_function(0); } else { ASSERT(false); } } return 0; } /*Win32 desktop only static void CALLBACK trigger_real_timer(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR) { char dummy = 0x33; s_real_timer_fifo.write(&dummy, 1); } */ static DWORD WINAPI trigger_real_timer(LPVOID lpParam) { char dummy = 0x33; while (1) { s_real_timer_fifo.write(&dummy, 1); Sleep(REAL_TIME_TASK_CYCLE_MS); } return 0; } void start_real_timer(void (*func)(void* arg)) { if(0 == func) { return; } s_expire_function = func; //timeSetEvent(REAL_TIME_TASK_CYCLE_MS, 0, trigger_real_timer, 0, TIME_PERIODIC);//Win32 desktop only static DWORD s_pid; if(s_pid == 0) { CreateThread(0, 0, trigger_real_timer, 0, 0, &s_pid); CreateThread(0, 0, fire_real_timer, 0, 0, &s_pid); } } unsigned int get_cur_thread_id() { return GetCurrentThreadId(); } void register_timer(int milli_second,void func(void* param), void* param) { set_a_timer(milli_second/TIMER_UNIT,func, param); } long get_time_in_second() { return (long)time(0); } T_TIME get_time() { T_TIME ret = {0}; SYSTEMTIME time; GetLocalTime(&time); ret.year = time.wYear; ret.month = time.wMonth; ret.day = time.wDay; ret.hour = time.wHour; ret.minute = time.wMinute; ret.second = time.wSecond; return ret; } T_TIME second_to_day(long second) { T_TIME ret; ret.year = 1999; ret.month = 10; ret.date = 1; ret.second = second % 60; second /= 60; ret.minute = second % 60; second /= 60; ret.hour = (second + 8) % 24;//China time zone. return ret; } void create_thread(unsigned long* thread_id, void* attr, void *(*start_routine) (void *), void* arg) { DWORD pid = 0; CreateThread(0, 0, LPTHREAD_START_ROUTINE(start_routine), arg, 0, &pid); *thread_id = pid; } void thread_sleep(unsigned int milli_seconds) { Sleep(milli_seconds); } #pragma pack(push,1) typedef struct { unsigned short bfType; unsigned int bfSize; unsigned short bfReserved1; unsigned short bfReserved2; unsigned int bfOffBits; }FileHead; typedef struct { unsigned int biSize; int biWidth; int biHeight; unsigned short biPlanes; unsigned short biBitCount; unsigned int biCompress; unsigned int biSizeImage; int biXPelsPerMeter; int biYPelsPerMeter; unsigned int biClrUsed; unsigned int biClrImportant; unsigned int biRedMask; unsigned int biGreenMask; unsigned int biBlueMask; }Infohead; #pragma pack(pop) int build_bmp(const char *filename, unsigned int width, unsigned int height, unsigned char *data) { FileHead bmp_head; Infohead bmp_info; int size = width * height * 2; //initialize bmp head. bmp_head.bfType = 0x4d42; bmp_head.bfSize = size + sizeof(FileHead) + sizeof(Infohead); bmp_head.bfReserved1 = bmp_head.bfReserved2 = 0; bmp_head.bfOffBits = bmp_head.bfSize - size; //initialize bmp info. bmp_info.biSize = 40; bmp_info.biWidth = width; bmp_info.biHeight = height; bmp_info.biPlanes = 1; bmp_info.biBitCount = 16; bmp_info.biCompress = 3; bmp_info.biSizeImage = size; bmp_info.biXPelsPerMeter = 0; bmp_info.biYPelsPerMeter = 0; bmp_info.biClrUsed = 0; bmp_info.biClrImportant = 0; //RGB565 bmp_info.biRedMask = 0xF800; bmp_info.biGreenMask = 0x07E0; bmp_info.biBlueMask = 0x001F; //copy the data FILE *fp; if (!(fp = fopen(filename, "wb"))) { return -1; } fwrite(&bmp_head, 1, sizeof(FileHead), fp); fwrite(&bmp_info, 1, sizeof(Infohead), fp); //fwrite(data, 1, size, fp);//top <-> bottom for (int i = (height - 1); i >= 0; --i) { fwrite(&data[i * width * 2], 1, width * 2, fp); } fclose(fp); return 0; } c_fifo::c_fifo() { m_head = m_tail = 0; m_read_sem = CreateSemaphore(0, // default security attributes 0, // initial count 1, // maximum count 0); // unnamed semaphore m_write_mutex = CreateMutex(0, false, 0); } int c_fifo::read(void* buf, int len) { unsigned char* pbuf = (unsigned char*)buf; int i = 0; while (i < len) { if (m_tail == m_head) {//empty WaitForSingleObject(m_read_sem, INFINITE); continue; } *pbuf++ = m_buf[m_head]; m_head = (m_head + 1) % FIFO_BUFFER_LEN; i++; } if (i != len) { ASSERT(false); } return i; } int c_fifo::write(void* buf, int len) { unsigned char* pbuf = (unsigned char*)buf; int i = 0; int tail = m_tail; WaitForSingleObject(m_write_mutex, INFINITE); while (i < len) { if ((m_tail + 1) % FIFO_BUFFER_LEN == m_head) {//full, clear data has been written; m_tail = tail; log_out("Warning: fifo full\n"); ReleaseMutex(m_write_mutex); return 0; } m_buf[m_tail] = *pbuf++; m_tail = (m_tail + 1) % FIFO_BUFFER_LEN; i++; } ReleaseMutex(m_write_mutex); if (i != len) { ASSERT(false); } else { ReleaseSemaphore(m_read_sem, 1, 0); } return i; } #endif #endif #ifdef GUILITE_ON DIALOG_ARRAY c_dialog::ms_the_dialogs[SURFACE_CNT_MAX]; #endif #ifdef GUILITE_ON c_keyboard c_edit::s_keyboard; #endif #ifdef GUILITE_ON static c_keyboard_button s_key_0, s_key_1, s_key_2, s_key_3, s_key_4, s_key_5, s_key_6, s_key_7, s_key_8, s_key_9; static c_keyboard_button s_key_A, s_key_B, s_key_C, s_key_D, s_key_E, s_key_F, s_key_G, s_key_H, s_key_I, s_key_J; static c_keyboard_button s_key_K, s_key_L, s_key_M, s_key_N, s_key_O, s_key_P, s_key_Q, s_key_R, s_key_S, s_key_T; static c_keyboard_button s_key_U, s_key_V, s_key_W, s_key_X, s_key_Y, s_key_Z; static c_keyboard_button s_key_dot, s_key_caps, s_key_space, s_key_enter, s_key_del, s_key_esc, s_key_num_switch; WND_TREE g_key_board_children[] = { //Row 1 {&s_key_Q, 'Q', 0, POS_X(0), POS_Y(0), KEY_WIDTH, KEY_HEIGHT}, {&s_key_W, 'W', 0, POS_X(1), POS_Y(0), KEY_WIDTH, KEY_HEIGHT}, {&s_key_E, 'E', 0, POS_X(2), POS_Y(0), KEY_WIDTH, KEY_HEIGHT}, {&s_key_R, 'R', 0, POS_X(3), POS_Y(0), KEY_WIDTH, KEY_HEIGHT}, {&s_key_T, 'T', 0, POS_X(4), POS_Y(0), KEY_WIDTH, KEY_HEIGHT}, {&s_key_Y, 'Y', 0, POS_X(5), POS_Y(0), KEY_WIDTH, KEY_HEIGHT}, {&s_key_U, 'U', 0, POS_X(6), POS_Y(0), KEY_WIDTH, KEY_HEIGHT}, {&s_key_I, 'I', 0, POS_X(7), POS_Y(0), KEY_WIDTH, KEY_HEIGHT}, {&s_key_O, 'O', 0, POS_X(8), POS_Y(0), KEY_WIDTH, KEY_HEIGHT}, {&s_key_P, 'P', 0, POS_X(9), POS_Y(0), KEY_WIDTH, KEY_HEIGHT}, //Row 2 {&s_key_A, 'A', 0, ((KEY_WIDTH / 2) + POS_X(0)), POS_Y(1), KEY_WIDTH, KEY_HEIGHT}, {&s_key_S, 'S', 0, ((KEY_WIDTH / 2) + POS_X(1)), POS_Y(1), KEY_WIDTH, KEY_HEIGHT}, {&s_key_D, 'D', 0, ((KEY_WIDTH / 2) + POS_X(2)), POS_Y(1), KEY_WIDTH, KEY_HEIGHT}, {&s_key_F, 'F', 0, ((KEY_WIDTH / 2) + POS_X(3)), POS_Y(1), KEY_WIDTH, KEY_HEIGHT}, {&s_key_G, 'G', 0, ((KEY_WIDTH / 2) + POS_X(4)), POS_Y(1), KEY_WIDTH, KEY_HEIGHT}, {&s_key_H, 'H', 0, ((KEY_WIDTH / 2) + POS_X(5)), POS_Y(1), KEY_WIDTH, KEY_HEIGHT}, {&s_key_J, 'J', 0, ((KEY_WIDTH / 2) + POS_X(6)), POS_Y(1), KEY_WIDTH, KEY_HEIGHT}, {&s_key_K, 'K', 0, ((KEY_WIDTH / 2) + POS_X(7)), POS_Y(1), KEY_WIDTH, KEY_HEIGHT}, {&s_key_L, 'L', 0, ((KEY_WIDTH / 2) + POS_X(8)), POS_Y(1), KEY_WIDTH, KEY_HEIGHT}, //Row 3 {&s_key_caps, 0x14, 0, POS_X(0), POS_Y(2), CAPS_WIDTH, KEY_HEIGHT}, {&s_key_Z, 'Z', 0, ((KEY_WIDTH / 2) + POS_X(1)), POS_Y(2), KEY_WIDTH, KEY_HEIGHT}, {&s_key_X, 'X', 0, ((KEY_WIDTH / 2) + POS_X(2)), POS_Y(2), KEY_WIDTH, KEY_HEIGHT}, {&s_key_C, 'C', 0, ((KEY_WIDTH / 2) + POS_X(3)), POS_Y(2), KEY_WIDTH, KEY_HEIGHT}, {&s_key_V, 'V', 0, ((KEY_WIDTH / 2) + POS_X(4)), POS_Y(2), KEY_WIDTH, KEY_HEIGHT}, {&s_key_B, 'B', 0, ((KEY_WIDTH / 2) + POS_X(5)), POS_Y(2), KEY_WIDTH, KEY_HEIGHT}, {&s_key_N, 'N', 0, ((KEY_WIDTH / 2) + POS_X(6)), POS_Y(2), KEY_WIDTH, KEY_HEIGHT}, {&s_key_M, 'M', 0, ((KEY_WIDTH / 2) + POS_X(7)), POS_Y(2), KEY_WIDTH, KEY_HEIGHT}, {&s_key_del, 0x7F, 0, ((KEY_WIDTH / 2) + POS_X(8)), POS_Y(2), DEL_WIDTH, KEY_HEIGHT}, //Row 4 {&s_key_esc, 0x1B, 0, POS_X(0), POS_Y(3), ESC_WIDTH, KEY_HEIGHT}, {&s_key_num_switch, 0x90, 0, POS_X(2), POS_Y(3), SWITCH_WIDTH, KEY_HEIGHT}, {&s_key_space, ' ', 0, ((KEY_WIDTH / 2) + POS_X(3)), POS_Y(3), SPACE_WIDTH, KEY_HEIGHT}, {&s_key_dot, '.', 0, ((KEY_WIDTH / 2) + POS_X(6)), POS_Y(3), DOT_WIDTH, KEY_HEIGHT}, {&s_key_enter, '\n', 0, POS_X(8), POS_Y(3), ENTER_WIDTH, KEY_HEIGHT}, {0,0,0,0,0,0,0} }; WND_TREE g_number_board_children[] = { {&s_key_1, '1', 0, POS_X(0), POS_Y(0), KEY_WIDTH, KEY_HEIGHT}, {&s_key_2, '2', 0, POS_X(1), POS_Y(0), KEY_WIDTH, KEY_HEIGHT}, {&s_key_3, '3', 0, POS_X(2), POS_Y(0), KEY_WIDTH, KEY_HEIGHT}, {&s_key_4, '4', 0, POS_X(0), POS_Y(1), KEY_WIDTH, KEY_HEIGHT}, {&s_key_5, '5', 0, POS_X(1), POS_Y(1), KEY_WIDTH, KEY_HEIGHT}, {&s_key_6, '6', 0, POS_X(2), POS_Y(1), KEY_WIDTH, KEY_HEIGHT}, {&s_key_7, '7', 0, POS_X(0), POS_Y(2), KEY_WIDTH, KEY_HEIGHT}, {&s_key_8, '8', 0, POS_X(1), POS_Y(2), KEY_WIDTH, KEY_HEIGHT}, {&s_key_9, '9', 0, POS_X(2), POS_Y(2), KEY_WIDTH, KEY_HEIGHT}, {&s_key_esc, 0x1B, 0, POS_X(0), POS_Y(3), KEY_WIDTH, KEY_HEIGHT}, {&s_key_0, '0', 0, POS_X(1), POS_Y(3), KEY_WIDTH, KEY_HEIGHT}, {&s_key_dot, '.', 0, POS_X(2), POS_Y(3), KEY_WIDTH, KEY_HEIGHT}, {&s_key_del, 0x7F, 0, POS_X(3), POS_Y(0), KEY_WIDTH, KEY_HEIGHT * 2 + 2}, {&s_key_enter,'\n', 0, POS_X(3), POS_Y(2), KEY_WIDTH, KEY_HEIGHT * 2 + 2}, {0,0,0,0,0,0,0} }; #endif
[ "perseverance51@126.com" ]
perseverance51@126.com
66e5dfefdd36177da65c2e84deaae1690f726eb7
e8dd6e3001d14ac07f9b10d1960b2384827ab20b
/examples/gaussian-process-regression/main.cpp
aa42febafd74326f3c84351ae3d5bc68fa2a6c5e
[ "MIT" ]
permissive
giovastabile/mathtoolbox
8c3ceb7497c2099016e58fbd3939459eff15ce63
5fcbaa1b0287f6715d2a3e4172e2a4e28e7604c3
refs/heads/master
2020-05-20T06:16:33.453557
2019-05-07T00:40:43
2019-05-07T00:40:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,357
cpp
#include <vector> #include <random> #include <iostream> #include <fstream> #include <string> #include <cmath> #include <Eigen/Core> #include <mathtoolbox/gaussian-process-regression.hpp> using Eigen::VectorXd; using Eigen::MatrixXd; namespace { std::random_device seed; std::default_random_engine engine(seed()); std::uniform_real_distribution<double> uniform_dist(0.0, 1.0); double CalculateFunction(double x) { return x * std::sin(10.0 * x); } } int main(int argc, char** argv) { // Display usage when necessary arguments are not provided if (argc < 2) { std::cout << "Usage: gaussian-process-regression-test [output directory path]" << std::endl; exit(0); } // Set a output directory path const std::string output_directory_path(argv[1]); // Generate (and export) scattered data constexpr int number_of_samples = 10; constexpr double noise_intensity = 0.10; std::ofstream scattered_data_stream(output_directory_path + "/scattered_data.csv"); scattered_data_stream << "x,y" << std::endl; Eigen::MatrixXd X(1, number_of_samples); Eigen::VectorXd y(number_of_samples); for (int i = 0; i < number_of_samples; ++ i) { X(0, i) = uniform_dist(engine); y(i) = CalculateFunction(X(0, i)) + noise_intensity * uniform_dist(engine); scattered_data_stream << X(0, i) << "," << y(i) << std::endl; } scattered_data_stream.close(); // Instantiate the interpolation object mathtoolbox::GaussianProcessRegression regressor(X, y); regressor.PerformMaximumLikelihood(0.10, 0.01, Eigen::VectorXd::Constant(1, 0.10)); // Calculate (and export) estimated values std::ofstream estimated_data_stream(output_directory_path + "/estimated_data.csv"); estimated_data_stream << "x,y,s" << std::endl; constexpr int resolution = 300; for (int i = 0; i <= resolution; ++ i) { const double x = (1.0 / static_cast<double>(resolution)) * i; const double y = regressor.EstimateY(Eigen::VectorXd::Constant(1, x)); const double s = std::sqrt(regressor.EstimateVariance(Eigen::VectorXd::Constant(1, x))); estimated_data_stream << x << "," << y << "," << s << std::endl; } estimated_data_stream.close(); return 0; }
[ "yuki@koyama.xyz" ]
yuki@koyama.xyz
24aa6031f255998a1a4f5442509b1f65c1319ac2
b8c7d99801e446ed5159ae8d0a10235b778ced0f
/physics/layerRef.cpp
c944f391cc3e6dcaf1827194fd1af06a111967f1
[ "MIT" ]
permissive
iomeone/Physics3D
ac24ac975172bf912758c50443f0228a1ce4cce0
f9abe877d5c4dae0c9473969f219be796416785f
refs/heads/master
2022-11-29T05:58:23.500223
2020-08-18T08:48:40
2020-08-18T08:48:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
723
cpp
#include "layerRef.h" #include "layer.h" void LayerRef::notifyPartBoundsUpdated(const Part* updatedPart, const Bounds& oldBounds) { if(layer != nullptr) layer->trees[static_cast<int>(subLayer)].updateObjectBounds(updatedPart, oldBounds); } void LayerRef::notifyPartGroupBoundsUpdated(const Part* mainPart, const Bounds& oldMainPartBounds) { if(layer != nullptr) layer->trees[static_cast<int>(subLayer)].updateObjectGroupBounds(mainPart, oldMainPartBounds); } void LayerRef::notifyPartStdMoved(Part* oldPartPtr, Part* newPartPtr) noexcept { if(layer != nullptr) { bool success = layer->trees[static_cast<int>(subLayer)].findAndReplaceObject(oldPartPtr, newPartPtr, newPartPtr->getBounds()); assert(success); } }
[ "lennart.vanhirtum@gmail.com" ]
lennart.vanhirtum@gmail.com
45d5f6a43daab62d2066780b875a95614446f0f2
d97735ef39079b45f89e4381965cd1026c6ba2ec
/AggOO-0.1.7/AggOO/include/agg_svg_path_renderer2.h
6e8d551b6435cde12398fb52d96f465e5fb225d9
[ "BSD-3-Clause" ]
permissive
prepare/Graphics2DVariants
36d0bb503ecc00ae9b19a704830310597e272af6
0f59169b332e23b166adcad63e5427de2449bf70
refs/heads/master
2021-01-22T05:33:29.575665
2014-11-18T13:39:28
2014-11-18T13:39:28
22,535,508
1
1
null
null
null
null
UTF-8
C++
false
false
4,261
h
/*! $Id: agg_svg_path_renderer2.h,v 1.1 2007/05/23 12:36:36 dratek Exp $ * @file agg_svg_path_renderer2.h * @author Chad M. Draper * @date May 7, 2007 * @brief A subclass of agg::svg::path_renderer which allows for vertex retrieval. * * Derived from agg::svg::path_renderer. path_renderer2 implements an * additional method which will return the vertices of the SVG path in an * array. See method documentation for more information. */ #ifndef AGG_SVG_PATH_RENDERER2_H_ #define AGG_SVG_PATH_RENDERER2_H_ #include "AggOOTypes.h" #include "svg/agg_svg_path_renderer.h" #include <vector> namespace AggOO { namespace svg { class path_renderer2 : public agg::svg::path_renderer { public: /** Structure to define a shape in the path. */ struct ShapeData { size_t numVertices; /**< Number of vertices in the shape */ std::vector< PointF > vertices; /**< Vertices in the shape */ }; /** Retrieve the vertices of the path. */ bool RenderVertices( const agg::trans_affine& mtx ) { using namespace agg; unsigned i; m_curved_count.count(0); for(i = 0; i < m_attr_storage.size(); i++) { const path_attributes& attr = m_attr_storage[i]; m_transform = attr.transform; m_transform *= mtx; double scl = m_transform.scale(); //m_curved.approximation_method(curve_inc); m_curved.approximation_scale(scl); m_curved.angle_tolerance(0.0); rgba8 color; /* if(attr.fill_flag) { ras.reset(); ras.filling_rule(attr.even_odd_flag ? fill_even_odd : fill_non_zero); if(fabs(m_curved_trans_contour.width()) < 0.0001) { ras.add_path(m_curved_trans, attr.index); } else { m_curved_trans_contour.miter_limit(attr.miter_limit); ras.add_path(m_curved_trans_contour, attr.index); } color = attr.fill_color; color.opacity(color.opacity() * opacity); ren.color(color); agg::render_scanlines(ras, sl, ren); } if(attr.stroke_flag) { m_curved_stroked.width(attr.stroke_width); //m_curved_stroked.line_join((attr.line_join == miter_join) ? miter_join_round : attr.line_join); m_curved_stroked.line_join(attr.line_join); m_curved_stroked.line_cap(attr.line_cap); m_curved_stroked.miter_limit(attr.miter_limit); m_curved_stroked.inner_join(inner_round); m_curved_stroked.approximation_scale(scl); // If the *visual* line width is considerable we // turn on processing of curve cusps. //--------------------- if(attr.stroke_width * scl > 1.0) { m_curved.angle_tolerance(0.2); } ras.reset(); ras.filling_rule(fill_non_zero); ras.add_path(m_curved_stroked_trans, attr.index); color = attr.stroke_color; color.opacity(color.opacity() * opacity); ren.color(color); agg::render_scanlines(ras, sl, ren); } */ } } }; // class path_renderer2 } // namespace svg } // namespace AggOO #endif // AGG_SVG_PATH_RENDERER2_H_
[ "wintercoredev@gmail.com" ]
wintercoredev@gmail.com
e402d0b76a45e85b2eb0c18a671274be666f0431
aac2f7b52c9104f683b98f88bfa40ec9e89ad360
/课程c++代码/大一上程序设计代码/我写的木马/10-6/123/main.cpp
c6ebc22a323a25d223fb2e97897dcdec97a347f7
[]
no_license
sjyjytu/My-All-Code
988a21429782b9901a0ee3c4cd19e73e9521f685
0456bcc8b6fe7aabb58b747facfb92b578371912
refs/heads/master
2020-05-04T00:33:07.525129
2019-04-02T02:47:08
2019-04-02T02:47:08
178,886,944
1
0
null
null
null
null
UTF-8
C++
false
false
342
cpp
#include <iostream> #include<stdlib.h> using namespace std; int main() { cout <<"\aOperation\"HyperHype\"is now activated!\n"; cout <<"Enter your agent code:______\b\b\b\b\b\b"; long code; cin>>code ; cout<<"\aYou entered"<<code<<"...\n"; cout<<"\aCode verified!Proceed with Plan Z3!\n"; return 0; system("pause"); }
[ "1332372004@qq.com" ]
1332372004@qq.com
5b7b5e406aca25be290ca910ee95bad4a751731f
287dc1683f7e19a5239c2b8addbc8531809f9177
/mooc43-bobo-algo/Play-with-Algorithms-master/08-Minimum-Span-Trees/Course Code (C++)/05-Implementation-of-Optimized-Prim-Algorithm/Edge.h
a3826cab12c6b0da513db59834135466a8d202a0
[ "Apache-2.0" ]
permissive
yaominzh/CodeLrn2019
ea192cf18981816c6adafe43d85e2462d4bc6e5d
adc727d92904c5c5d445a2621813dfa99474206d
refs/heads/master
2023-01-06T14:11:45.281011
2020-10-28T07:16:32
2020-10-28T07:16:32
164,027,453
2
0
Apache-2.0
2023-01-06T00:39:06
2019-01-03T22:02:24
C++
UTF-8
C++
false
false
1,569
h
// // Created by liuyubobobo on 9/26/16. // #ifndef INC_05_IMPLEMENTATION_OF_OPTIMIZED_PRIM_ALGORITHM_EDGE_H #define INC_05_IMPLEMENTATION_OF_OPTIMIZED_PRIM_ALGORITHM_EDGE_H #include <iostream> #include <cassert> using namespace std; // 边 template<typename Weight> class Edge{ private: int a,b; // 边的两个端点 Weight weight; // 边的权值 public: // 构造函数 Edge(int a, int b, Weight weight){ this->a = a; this->b = b; this->weight = weight; } // 空的构造函数, 所有的成员变量都取默认值 Edge(){} ~Edge(){} int v(){ return a;} // 返回第一个顶点 int w(){ return b;} // 返回第二个顶点 Weight wt(){ return weight;} // 返回权值 // 给定一个顶点, 返回另一个顶点 int other(int x){ assert( x == a || x == b ); return x == a ? b : a; } // 输出边的信息 friend ostream& operator<<(ostream &os, const Edge &e){ os<<e.a<<"-"<<e.b<<": "<<e.weight; return os; } // 边的大小比较, 是对边的权值的大小比较 bool operator<(Edge<Weight>& e){ return weight < e.wt(); } bool operator<=(Edge<Weight>& e){ return weight <= e.wt(); } bool operator>(Edge<Weight>& e){ return weight > e.wt(); } bool operator>=(Edge<Weight>& e){ return weight >= e.wt(); } bool operator==(Edge<Weight>& e){ return weight == e.wt(); } }; #endif //INC_05_IMPLEMENTATION_OF_OPTIMIZED_PRIM_ALGORITHM_EDGE_H
[ "mcuallen@gmail.com" ]
mcuallen@gmail.com
cf0aef65a92fe734f037e6fba13e61dffe16e938
00a05ffcb21d87b295618badafb3ab9ea623f445
/marktest.cc
72fda68cb74bf4c9ddfe52775d0f49e6adec2464
[]
no_license
lets-make-something/camserv
ca39253292eabc6b1a2785cba94506a85c91406a
078af95ffa353bbae19d9e87a34da7274c40f153
refs/heads/master
2021-08-30T10:26:48.912563
2017-12-17T14:06:30
2017-12-17T14:06:30
107,996,954
1
0
null
null
null
null
UTF-8
C++
false
false
2,235
cc
#include "markpos.h" #include "png/png.h" #include <fstream> #include <stdint.h> #include <vector> #include <random> #include <algorithm> #include <array> #include <map> void writestepcolor(const char *name, uint8_t *mono, int width, int height) { using namespace std; vector<uint8_t> data; data.resize(width*height * 3); vector<uint8_t> pal; pal.resize(256); mt19937 mt(123456); for (int i = 0; i < 256; i++) { int a = mt() % 256; pal[i] = a; } for (int i = 0; i < width*height; i++) { if (mono[i]) { data[i * 3 + 0] = pal[mono[i]%256]; data[i * 3 + 1] = 255 - pal[mono[i] % 256]; data[i * 3 + 2] = mono[i] % 256; } else { data[i * 3 + 0] = 0; data[i * 3 + 1] = 0; data[i * 3 + 2] = 0; } } wts::Raw raw; wts::WriteFromR8G8B8(&raw, width, height, data.data()); ofstream of(name, ios::binary | ios::out); if (of.is_open()) { of.write(reinterpret_cast<const char*>(raw.data), raw.size); } } void writestep(const char *name, uint8_t *mono, int width, int height) { using namespace std; vector<uint8_t> data; data.resize(width*height * 3); for (int i = 0; i < width*height; i++) { data[i * 3 + 0] = mono[i]; data[i * 3 + 1] = mono[i]; data[i * 3 + 2] = mono[i]; } wts::Raw raw; wts::WriteFromR8G8B8(&raw, width, height, data.data()); ofstream of(name, ios::binary | ios::out); if (of.is_open()) { of.write(reinterpret_cast<const char*>(raw.data), raw.size); } } void filter(uint8_t *mono, int width, int height,int *pattern) { std::vector<uint8_t> out; out.resize(width*height); for (int y = 1; y < height-1; y++) { for (int x = 1; x < width-1; x++) { } } } int main() { using namespace std; ifstream file("../mark.png", ios::binary | ios::in); if (file.is_open()) { vector<uint8_t> data; file.seekg(0, file.end); data.resize((int)file.tellg()); file.seekg(0, file.beg); file.read(reinterpret_cast<char*>(&*data.begin()), data.size()); file.close(); wts::Raw raw = { &*data.begin(),data.size() }; wts::Png png; wts::ReadFromRaw(&png, &raw); } }
[ "wate@wate.jp" ]
wate@wate.jp
9598e7a80304f492686d7a39a46ecf0310986338
190219e4aca487f7c65de81484b993b362825131
/v2/external/llvm-2.8/lib/CodeGen/SimpleRegisterCoalescing.h
855bdb98b36c6de2ec2b03f4c6fa0ff381a9149d
[ "NCSA", "LicenseRef-scancode-unknown-license-reference" ]
permissive
dilawar/ahir
b6a56ed5c61f121c09ef6636d7dd2752d97529b5
9c5592a4df7a47b9c1e406778cc7c17316bcfb4e
refs/heads/master
2021-07-14T18:04:20.484255
2020-07-26T20:18:34
2020-07-26T20:18:34
184,123,680
1
0
NOASSERTION
2019-04-29T18:34:26
2019-04-29T18:34:26
null
UTF-8
C++
false
false
7,889
h
//===-- SimpleRegisterCoalescing.h - Register Coalescing --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a simple register copy coalescing phase. // //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_SIMPLE_REGISTER_COALESCING_H #define LLVM_CODEGEN_SIMPLE_REGISTER_COALESCING_H #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/LiveIntervalAnalysis.h" #include "llvm/CodeGen/RegisterCoalescer.h" #include "llvm/ADT/BitVector.h" namespace llvm { class SimpleRegisterCoalescing; class LiveVariables; class TargetRegisterInfo; class TargetInstrInfo; class VirtRegMap; class MachineLoopInfo; /// CopyRec - Representation for copy instructions in coalescer queue. /// struct CopyRec { MachineInstr *MI; unsigned LoopDepth; CopyRec(MachineInstr *mi, unsigned depth) : MI(mi), LoopDepth(depth) {} }; class SimpleRegisterCoalescing : public MachineFunctionPass, public RegisterCoalescer { MachineFunction* mf_; MachineRegisterInfo* mri_; const TargetMachine* tm_; const TargetRegisterInfo* tri_; const TargetInstrInfo* tii_; LiveIntervals *li_; const MachineLoopInfo* loopInfo; AliasAnalysis *AA; DenseMap<const TargetRegisterClass*, BitVector> allocatableRCRegs_; /// JoinedCopies - Keep track of copies eliminated due to coalescing. /// SmallPtrSet<MachineInstr*, 32> JoinedCopies; /// ReMatCopies - Keep track of copies eliminated due to remat. /// SmallPtrSet<MachineInstr*, 32> ReMatCopies; /// ReMatDefs - Keep track of definition instructions which have /// been remat'ed. SmallPtrSet<MachineInstr*, 8> ReMatDefs; public: static char ID; // Pass identifcation, replacement for typeid SimpleRegisterCoalescing() : MachineFunctionPass(ID) {} struct InstrSlots { enum { LOAD = 0, USE = 1, DEF = 2, STORE = 3, NUM = 4 }; }; virtual void getAnalysisUsage(AnalysisUsage &AU) const; virtual void releaseMemory(); /// runOnMachineFunction - pass entry point virtual bool runOnMachineFunction(MachineFunction&); bool coalesceFunction(MachineFunction &mf, RegallocQuery &) { // This runs as an independent pass, so don't do anything. return false; } /// print - Implement the dump method. virtual void print(raw_ostream &O, const Module* = 0) const; private: /// joinIntervals - join compatible live intervals void joinIntervals(); /// CopyCoalesceInMBB - Coalesce copies in the specified MBB, putting /// copies that cannot yet be coalesced into the "TryAgain" list. void CopyCoalesceInMBB(MachineBasicBlock *MBB, std::vector<CopyRec> &TryAgain); /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg, /// which are the src/dst of the copy instruction CopyMI. This returns true /// if the copy was successfully coalesced away. If it is not currently /// possible to coalesce this interval, but it may be possible if other /// things get coalesced, then it returns true by reference in 'Again'. bool JoinCopy(CopyRec &TheCopy, bool &Again); /// JoinIntervals - Attempt to join these two intervals. On failure, this /// returns false. The output "SrcInt" will not have been modified, so we can /// use this information below to update aliases. bool JoinIntervals(CoalescerPair &CP); /// Return true if the two specified registers belong to different register /// classes. The registers may be either phys or virt regs. bool differingRegisterClasses(unsigned RegA, unsigned RegB) const; /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy. If /// the source value number is defined by a copy from the destination reg /// see if we can merge these two destination reg valno# into a single /// value number, eliminating a copy. bool AdjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI); /// HasOtherReachingDefs - Return true if there are definitions of IntB /// other than BValNo val# that can reach uses of AValno val# of IntA. bool HasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB, VNInfo *AValNo, VNInfo *BValNo); /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy. /// If the source value number is defined by a commutable instruction and /// its other operand is coalesced to the copy dest register, see if we /// can transform the copy into a noop by commuting the definition. bool RemoveCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI); /// TrimLiveIntervalToLastUse - If there is a last use in the same basic /// block as the copy instruction, trim the ive interval to the last use /// and return true. bool TrimLiveIntervalToLastUse(SlotIndex CopyIdx, MachineBasicBlock *CopyMBB, LiveInterval &li, const LiveRange *LR); /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial /// computation, replace the copy by rematerialize the definition. bool ReMaterializeTrivialDef(LiveInterval &SrcInt, unsigned DstReg, unsigned DstSubIdx, MachineInstr *CopyMI); /// isWinToJoinCrossClass - Return true if it's profitable to coalesce /// two virtual registers from different register classes. bool isWinToJoinCrossClass(unsigned SrcReg, unsigned DstReg, const TargetRegisterClass *SrcRC, const TargetRegisterClass *DstRC, const TargetRegisterClass *NewRC); /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and /// update the subregister number if it is not zero. If DstReg is a /// physical register and the existing subregister number of the def / use /// being updated is not zero, make sure to set it to the correct physical /// subregister. void UpdateRegDefsUses(const CoalescerPair &CP); /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy. /// Return true if live interval is removed. bool ShortenDeadCopyLiveRange(LiveInterval &li, MachineInstr *CopyMI); /// ShortenDeadCopyLiveRange - Shorten a live range as it's artificially /// extended by a dead copy. Mark the last use (if any) of the val# as kill /// as ends the live range there. If there isn't another use, then this /// live range is dead. Return true if live interval is removed. bool ShortenDeadCopySrcLiveRange(LiveInterval &li, MachineInstr *CopyMI); /// RemoveDeadDef - If a def of a live interval is now determined dead, /// remove the val# it defines. If the live interval becomes empty, remove /// it as well. bool RemoveDeadDef(LiveInterval &li, MachineInstr *DefMI); /// RemoveCopyFlag - If DstReg is no longer defined by CopyMI, clear the /// VNInfo copy flag for DstReg and all aliases. void RemoveCopyFlag(unsigned DstReg, const MachineInstr *CopyMI); /// lastRegisterUse - Returns the last use of the specific register between /// cycles Start and End or NULL if there are no uses. MachineOperand *lastRegisterUse(SlotIndex Start, SlotIndex End, unsigned Reg, SlotIndex &LastUseIdx) const; }; } // End llvm namespace #endif
[ "dilawars@ncbs.res.in" ]
dilawars@ncbs.res.in
981a65929bcfd3612780278eb947ed053e3057eb
cec628def1aad94ccbefa814d2a0dbd51588e9bd
/cnd.completion/test/unit/data/org/netbeans/modules/cnd/completion/cplusplus/hyperlink/ClassMembersHyperlinkTestCase/IZ144062.cc
a46ecd6dfdf42cbdbbfacbf7cb7d8d417862c959
[]
no_license
emilianbold/netbeans-releases
ad6e6e52a896212cb628d4522a4f8ae685d84d90
2fd6dc84c187e3c79a959b3ddb4da1a9703659c7
refs/heads/master
2021-01-12T04:58:24.877580
2017-10-17T14:38:27
2017-10-17T14:38:27
78,269,363
30
15
null
2020-10-13T08:36:08
2017-01-07T09:07:28
null
UTF-8
C++
false
false
276
cc
static void type_test() { struct Uni { int ii; unsigned bit1:1; unsigned bit2:2; union { int j; char c; } u; void foo(int x) { int y = x + 1; } } uni; struct Uni2{}uni2; }
[ "alexey_vladykin@netbeans.org" ]
alexey_vladykin@netbeans.org
070ef6fb8e15632521d11c1bc7db1d8d264f94af
13822ad67648e1294a16f3a0ef5e7893b9bc46bc
/xtree_interface/PrintGraphSet.hpp
e6c56fe33e687a98463f9064aff12e75a85955ce
[]
no_license
mlikt/ft_container
5493d66c1bdfe73518919cbf83c335bf91e64cf7
03ef4784d9fd0399b02aa51c73222f7af99d4e4e
refs/heads/master
2023-08-29T21:00:46.062720
2021-11-12T22:38:35
2021-11-12T22:38:35
409,779,883
0
1
null
null
null
null
UTF-8
C++
false
false
3,070
hpp
#ifndef __PGS__ #define __PGS__ #define BLACK "\033[22;2m" #define YELLOW "\033[22;33m" #define RED "\033[22;31m" #define GREEN "\e[0;32m" #define BLUE "\033[40;34m" #define RESETCOLOR "\033[0m" #define ON 1 #define OFF 0 namespace ft { template <class tree_traits> void xtree<tree_traits>::PrintGraphSet() { if (this->Root == NIL) { return; } if (this->Root->colour == Paint::Red) { std::cout << RED << Root->Value << RESETCOLOR << std::endl; } else { std::cout << BLACK << Root->Value << RESETCOLOR << std::endl; } PrintSubtreeSet(this->Root, "", OFF); std::cout << std::endl; } template <class tree_traits> void xtree<tree_traits>::PrintSubtreeSet(nodeptr Root, const std::string& prefix, bool tumbler) { if (Root == NIL) { return; } bool hasLeft; bool hasRight; if (tumbler) { hasLeft = (Left(Root) != NULL); // NIL - если не хочешь отображать листья hasRight = (Right(Root) != NULL); } else { hasLeft = (Left(Root) != NIL); // NIL - если не хочешь отображать листья hasRight = (Right(Root) != NIL); } if (!hasLeft && !hasRight) { return; } std::cout << GREEN << prefix << RESETCOLOR << std::flush; std::cout << BLUE << ((hasLeft && hasRight) ? "├── " : "") << RESETCOLOR << std::flush; std::cout << BLUE << ((!hasLeft && hasRight) ? "└── " : "") << RESETCOLOR << std::flush; if (hasRight) { bool printStrand = (hasLeft && hasRight && (Right(Root)->Right != NULL || Right(Root)->Left != NULL)); std::string newPrefix = prefix + (printStrand ? "│ " : " "); if (Right(Root) == NIL){ std::cout << BLACK << "NIL" << RESETCOLOR << std::endl; } else if (Right(Root)->colour == Paint::Red) { std::cout << RED << Right(Root)->Value << RESETCOLOR << std::endl; } else { std::cout << BLACK << Right(Root)->Value << RESETCOLOR << std::endl; } PrintSubtreeSet(Right(Root), newPrefix, tumbler); } if (hasLeft) { std::cout << GREEN << (hasRight ? prefix : "") << "└── " << RESETCOLOR; if (Left(Root) == NIL){ std::cout << BLACK << "NIL" << RESETCOLOR << std::endl; } else if (Left(Root)->colour == Paint::Red) { std::cout << RED << Left(Root)->Value << RESETCOLOR << std::endl; } else { std::cout << BLACK << Left(Root)->Value << RESETCOLOR << std::endl; } PrintSubtreeSet(Left(Root), prefix + " ", tumbler); } } } #endif
[ "mlikt@ev-j4.kzn.21-school.ru" ]
mlikt@ev-j4.kzn.21-school.ru
92ae2535762892e342e6c7733589f80c8a72afd4
8374f90034628900e3b2be5b0727158bef540a98
/考核二.cpp
21c499d1b92682f54e4d53845302a9e25f7416cf
[]
no_license
QAQAQAQAQQAQ/exam
19820261c73df2262af7e2626baf500b81fe49de
d39c32f117a0ac4fed13dee5dff78c2dd7e4f94a
refs/heads/main
2023-08-20T18:24:11.733009
2021-10-29T08:33:06
2021-10-29T08:33:06
null
0
0
null
null
null
null
GB18030
C++
false
false
1,039
cpp
#include <iostream> #include <cstdio> using namespace std; const int Edge = 500;//设定一个边界的值 int n, m, a = 0;//m,n为边界的值 a为最后结果的值 int F[Edge][Edge];//利用边界创建二维数组 int dx[4] = { -1,0,1,0 }; int dy[4] = { 0,-1,0,1 }; void dfs(int x, int y) { if (x<0 || x>n + 1 || y<0 || y>m + 1||F[x][y]) return; F[x][y] = 1; for (int i = 0; i < 4; i++) { int a = x + dx[i], b = y + dy[i]; dfs(a, b);//遍历数组搜索 } } int main() { cin >> n >> m;//输入想要的边界长度 for (int i =1;i<=n;i++) for(int j = 1;j<=m;j++)//经过二维数组 { char q; cin >> q;//输入该位置上是0还是* if (q == '*') F[i][j] = 1; else F[i][j] = 0; //如果该位置上是星号,则该位置值为一,否则为零 } dfs(0, 0); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (!F[i][j])//如果该位置值为0 则a+1 a++; cout << a << endl;//输出a return 0; }
[ "noreply@github.com" ]
noreply@github.com
e6c725ff35068848af6992d4bd39c219bf085ec4
53662d3cb19f44f1a344a48e10d65c0c36b0d50e
/components/integratedHand/src/touchpointsI.h
b91e69a4ed744a52091bde14be394561eb1fe95d
[]
no_license
robocomp/euroage-tv
7b639338169ecb67470abde056732a4cbcebedf9
8aaa4c668a46ad1dea869ff3b6c826769b20eac6
refs/heads/master
2021-06-24T19:59:26.425779
2019-08-29T11:07:01
2019-08-29T11:07:01
140,541,711
0
1
null
null
null
null
UTF-8
C++
false
false
1,216
h
/* * Copyright (C)2019 by YOUR NAME HERE * * This file is part of RoboComp * * RoboComp 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. * * RoboComp 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 RoboComp. If not, see <http://www.gnu.org/licenses/>. */ #ifndef TOUCHPOINTS_H #define TOUCHPOINTS_H // Ice includes #include <Ice/Ice.h> #include <TouchPoints.h> #include <config.h> #include "genericworker.h" using namespace RoboCompTouchPoints; class TouchPointsI : public virtual RoboCompTouchPoints::TouchPoints { public: TouchPointsI(GenericWorker *_worker); ~TouchPointsI(); void detectedTouchPoints(const TouchPointsSeq &touchpoints, const Ice::Current&); private: GenericWorker *worker; }; #endif
[ "orensbruli@gmail.com" ]
orensbruli@gmail.com
b4918b4665d5a0b648891faff91a54fa46b64a3b
7e2dec5d88ac1403340f76eb13aea42682726008
/src/vk/video_profile.h
8546360ba3d00a7344bf8b782a2d43a9d99f0e6b
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
ogukei/fuurin
84f94f74fbed31dd5ec2dea7c1d2f1b3d267daec
f6109e56661aa977459e7d4b01eac60e3cc0d66f
refs/heads/master
2023-06-01T10:05:16.633864
2021-06-13T21:26:15
2021-06-13T21:26:15
365,659,214
1
0
MIT
2021-06-13T21:26:15
2021-05-09T03:31:13
C++
UTF-8
C++
false
false
868
h
#pragma once extern "C" { #define VK_ENABLE_BETA_EXTENSIONS #include <vulkan/vulkan.h> } #include <memory> namespace vk { class Device; class VideoProfile { private: VkVideoProfileKHR profile_; VkVideoProfileKHR profile_with_ext_; VkVideoDecodeH264ProfileEXT decode_h264_profile_; std::shared_ptr<vk::Device> device_; void InitializeH264Decode(); public: static std::shared_ptr<VideoProfile> CreateH264Decode( const std::shared_ptr<vk::Device>& device); explicit VideoProfile( const std::shared_ptr<vk::Device>& device); VideoProfile(const VideoProfile&) = delete; ~VideoProfile(); const VkVideoProfileKHR& Profile() const { return profile_; } // FIXME: vkCreateImage does not need ext. session creation probably needs ext const VkVideoProfileKHR& ProfileWithExt() const { return profile_with_ext_; } }; } // namespace vk
[ "noreply@github.com" ]
noreply@github.com
626c58435420bbe6477ce0e0ec468819cd8184d3
04a540847c1333c987a1957fd8d31197c594f6bb
/BOJ/12100_2_1.cpp
42a952a2d910327f25b74185eb93221b76bd1445
[]
no_license
k8440009/Algorithm
fd148269b264b580876c7426e19dbe2425ddc1ab
a48eba0ac5c9f2e10f3c509ce9d349c8a1dc3f0c
refs/heads/master
2023-04-02T16:06:10.260768
2023-04-02T11:04:32
2023-04-02T11:04:32
200,506,643
0
0
null
null
null
null
UTF-8
C++
false
false
3,408
cpp
// 2048 (easy) 2회차 // https://www.acmicpc.net/problem/12100 /* 4 2 2 2 2 0 0 0 0 0 0 0 0 0 0 0 0 */ #include <iostream> #include <queue> using namespace std; const int MAX = 20 + 2; int N, answer; int board[MAX][MAX]; void print_board(int src[MAX][MAX]) { cout << '\n'; for (int r = 0; r < N; r++) { for (int c = 0; c < N; c++) { cout << src[r][c] << ' '; } cout << '\n'; } } int find_max(int src[MAX][MAX]) { int max_data = 0; for (int r = 0; r < N; r++) for (int c = 0; c < N; c++) max_data = max(max_data, src[r][c]); return max_data; } void board_copy(int desc[MAX][MAX], int src[MAX][MAX]) { for (int r = 0; r < N; r++) for (int c = 0; c < N; c++) desc[r][c] = src[r][c]; } void move(int src[MAX][MAX], int dir) { int tmp[MAX][MAX]; int visited[MAX][MAX]; fill_n(tmp[0], MAX * MAX, 0); fill_n(visited[0], MAX * MAX, 0); if (dir == 0) { for (int c = 0; c < N; c++) { int r = 0, idx = 0; vector <int> data; while (r < N) { if (src[r][c] > 0) data.push_back(src[r][c]); r++; } r = 0; while (r < N && data.size() != idx) { if (tmp[r][c] == 0) { tmp[r][c] = data[idx]; idx++; } else { if (tmp[r][c] == data[idx] && !visited[r][c]) { tmp[r][c] *= 2; visited[r][c] = 1; idx++; } else r++; } } } } else if (dir == 1) { for (int c = 0; c < N; c++) { int r = N - 1, idx = 0; vector <int> data; while (r >= 0) { if (src[r][c] > 0) data.push_back(src[r][c]); r--; } r = N - 1; while (r >= 0 && data.size() != idx) { if (tmp[r][c] == 0) { tmp[r][c] = data[idx]; idx++; } else { if (tmp[r][c] == data[idx] && !visited[r][c]) { tmp[r][c] *= 2; visited[r][c] = 1; idx++; } else r--; } } } } else if (dir == 2) { for (int r = 0; r < N; r++) { int c = 0, idx = 0; vector <int> data; while (c < N) { if (src[r][c] > 0) data.push_back(src[r][c]); c++; } c = 0; while (c < N && data.size() != idx) { if (tmp[r][c] == 0) { tmp[r][c] = data[idx]; idx++; } else { if (tmp[r][c] == data[idx] && !visited[r][c]) { tmp[r][c] *= 2; visited[r][c] = 1; idx++; } else c++; } } } } else if (dir == 3) { for (int r = 0; r < N; r++) { int c = N - 1, idx = 0; vector <int> data; while (c >= 0) { if (src[r][c] > 0) data.push_back(src[r][c]); c--; } c = N - 1; while (c >= 0 && data.size() != idx) { if (tmp[r][c] == 0) { tmp[r][c] = data[idx]; idx++; } else { if (tmp[r][c] == data[idx] && !visited[r][c]) { tmp[r][c] *= 2; visited[r][c] = 1; idx++; } else c--; } } } } board_copy(src, tmp); } void dfs(int cur[MAX][MAX], int cnt) { if (cnt == 5) { answer = max(answer, find_max(cur)); //print_board(cur); return ; } for (int dir = 0; dir < 4; dir++) { int next[MAX][MAX]; board_copy(next, cur); move(next, dir); dfs(next, cnt + 1); board_copy(next, cur); } } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> N; for (int r = 0; r < N; r++) for (int c = 0; c < N; c++) cin >> board[r][c]; dfs(board, 0); cout << answer; }
[ "sungslee@student.42seoul.kr" ]
sungslee@student.42seoul.kr
9268e3277f53edb22efb921d47489e76c38de113
d4a4778a22065bdca785ead59b04ec6f6f11f9e6
/quant/src/stock_info.cpp
e7ad04da83120f7f4f38f7cda3aa3d538d83e2ae
[]
no_license
zjpanghao/quant-choices
d85a05b8122d50523284939490b942d054fe0003
51c58882e243b3199bde490b7011bff99e3c73f0
refs/heads/master
2021-01-15T17:50:08.038987
2017-10-25T09:10:21
2017-10-25T09:10:21
99,760,907
0
0
null
2017-10-25T09:10:22
2017-08-09T03:23:29
C++
UTF-8
C++
false
false
1,296
cpp
#include "stock_info.h" namespace stock_info { std::mutex StockLatestInfo::mutex_; StockLatestInfo* StockLatestInfo::GetInstance() { static StockLatestInfo info; return &info; } bool StockLatestInfo::UpdateCssInfo(const std::map<std::string, CssInfo> &css_map) { LOG(INFO) << "UpdateCssInfo: " << css_map.size(); std::lock_guard<std::mutex> lock_guard(mutex_); auto css_it = css_map.begin(); while (css_it != css_map.end()) { auto css_info = css_it->second; std::string code = css_it->first; auto it = stock_map_.find(code); if (it != stock_map_.end()) { StockInfo &info = it->second; info.UpdateCssInfo(css_info); } else { StockInfo info(code); info.set_css_info(css_info); stock_map_[code] = info; } css_it++; } return true; } bool StockLatestInfo::UpdateCsqInfo(std::string code, const CsqInfo &info, StockInfo *stock_info) { std::lock_guard<std::mutex> lock_guard(mutex_); auto it = stock_map_.find(code); if (it == stock_map_.end()) { StockInfo new_info(code); new_info.set_csq_info(info); stock_map_[code] = new_info; } else { StockInfo &csq_info = it->second; csq_info.UpdateCsqInfo(info); } *stock_info = stock_map_[code]; return true; } } // namespace stock_info
[ "panghao@slave5.(none)" ]
panghao@slave5.(none)
9eadb0032a4cc3df3766e705673e84d5eb9e2712
5f81b8e48e6bf5d751e320486187df10f5892b07
/circle.cpp
b7928936a65532f263d1f1a476ebfe4721a2b0a7
[]
no_license
trpham/Geometric-Shape-Classes
9acc00b1ca0787954b1a85b7fbfdb5e0545e41fa
1c1128d5d1d61cd12a647db7adae3f3c2a0c9cab
refs/heads/master
2021-01-19T06:05:59.690484
2015-07-02T04:34:12
2015-07-02T04:34:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,155
cpp
/** * Program name: Circle.cpp * Discussion: Cirlce Class Implementation * Written By: Truong Pham * Date: 2014/12/11 */ #include "circle.h" Circle::Circle() : center(Point(Fraction(0, 1), Fraction(0, 1))), radius(Fraction(0, 1)) { } Circle::Circle(Circle& cir) : center(cir.center), radius(cir.radius) { } Circle::Circle(Point& pt, Fraction& fr) : center(pt), radius(fr) { } Circle::~Circle() { } Fraction Circle::computeArea() { return Fraction(157, 50)* radius * radius; } Fraction Circle::computeVolume() { return Fraction(); } void Circle::print() const{ cout << "\n Center: "; cout << center; cout << "\n Radius: "; cout << radius << endl; } ostream& operator<<(ostream& os, const Circle& cir) { cir.print(); return os; } istream& operator>>(istream& in, Circle& cir) { Point p; Fraction r; cout << "\n Center: "; cin >> p; cout << "\n Radius: "; cin >> r; while (r < Fraction()) { cout << "\n Invalid input. Radius has to be positive: "; cout << "\n Radius: "; cin >> r; }; cir = Circle(p, r); return in; }
[ "phamcse@gmail.com" ]
phamcse@gmail.com
38dd93a98abed591a8d426d38a62c2164f7b2fa0
1000804c885ccf3cee9cb2733a4fc22d9a3a5100
/Week_04/45. Jump Game II.cpp
959603f60ac4d265b71bd3b07a6d0869d2e8d604
[]
no_license
winter-ldm/algorithm012
48eddedc8458c80c20e5abde0f039c000f01615e
b028350213ecc8f863d57ee5e127288c876a8a4d
refs/heads/master
2022-12-13T11:34:52.835953
2020-09-13T09:09:29
2020-09-13T09:09:29
280,853,445
1
0
null
2020-07-19T11:41:59
2020-07-19T11:41:58
null
UTF-8
C++
false
false
731
cpp
/** * 从能走的范围里面选出一次能跨过过大的步数,然后又从该位置找出能跨过的最大步数,当前面跨过的步数+当前的最大步数能跨到最后一个位置即为所求 **/ class Solution { public: int jump(vector<int>& nums) { int step = 0, start = 0, end = 0, flag = 0, n = nums.size() - 1; while (end < n) { step++; int endflag = end + 1; for (int i = start; i <= end; i++) { if (i + nums[i] >= n) { return step; } endflag = max(endflag, i + nums[i]); } start = end + 1; end = endflag; } return step; } };
[ "2402048517@qq.com" ]
2402048517@qq.com
a7ad4d6da7111453e84ab848a81c1b8972eba57d
a4324c8deb4e0a403e32bb511d16dbce6e376c6b
/c++程序设计进阶/week1/位运算.cpp
1d37a7def2b67127c0fdad3545c9db7de9c3660f
[]
no_license
Ge-yuan-jun/coursera-peking-university
2a0f860b246f0fcc09b646a027e14e7da5bb9472
ae4f2e5bb57d5ee03be9388807f3a78165d3d60c
refs/heads/master
2021-02-27T13:43:43.417165
2017-03-14T06:29:34
2017-03-14T06:29:34
40,311,833
0
0
null
null
null
null
UTF-8
C++
false
false
228
cpp
#include <stdio.h> int main () { int n1 = 15; short n2 = -15; unsigned short n3 = 0xffe0; char c = 15; n1 = n1 >> 2; n2 >>= 3; n3 >>= 4; c >>= 3; printf("n1=%d,n2=%x,n3=%x,c=%x",n1,n2,n3,c); }
[ "daydaygyj@gmail.com" ]
daydaygyj@gmail.com
f44d353b1c786d79a03c7567c17ce13661b7437d
9644bf4e8daa8a38e7b23288ea04667ffe3c4b7e
/Main/SharpMemoryLcd.cpp
a85d86dcb33b202ec9fcf98f3bfd2ea7de58a857
[ "MIT" ]
permissive
Ideely/Metering-Project
cb5671138c97c9c0c8347c0e35d5c9766b246885
63e96721f0f4587e117e938400b36fbf9ae52bdb
refs/heads/master
2019-01-22T10:17:05.115075
2015-03-02T20:41:23
2015-03-02T20:41:23
30,617,771
0
1
null
2015-02-20T03:25:59
2015-02-10T22:22:53
C++
UTF-8
C++
false
false
8,185
cpp
#include "SharpMemoryLcd.h" #include <avr/pgmspace.h> static const int DISP = 2; static const int EXTC = 3; static const int EXTM = 4; //this can just be pulled high on your PCB if you need the pin static const int SI = 11; static const int SCS = 12; static const int SCLK = 13; #define ARRAYSIZE 1152 const unsigned char ARDUINOBMP[ARRAYSIZE] PROGMEM = { 0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,31,128,255,255,255,255,3,240,255,63, 252,255,3,0,252,255,255,127,0,0,255,63, 252,255,0,0,224,255,255,31,0,0,252,63, 252,63,0,0,192,255,255,7,0,0,248,63, 252,15,0,0,0,255,255,1,0,0,224,63, 252,7,0,0,0,254,255,0,0,0,192,63, 252,3,0,0,0,248,127,0,0,0,128,63, 252,1,192,63,0,240,63,0,248,7,0,63, 252,0,248,255,1,224,31,0,254,63,0,62, 252,0,252,255,7,192,15,128,255,127,0,60, 124,0,255,255,15,192,7,224,255,255,1,60, 124,128,255,255,31,128,3,240,255,255,3,56, 60,192,255,255,127,0,1,248,255,255,7,56, 60,192,255,255,255,0,0,252,255,255,15,48, 28,224,255,255,255,0,0,254,31,255,15,48, 28,224,255,255,255,1,0,255,31,255,31,48, 28,240,255,255,255,3,128,255,31,255,31,32, 28,240,255,255,255,7,128,255,31,255,63,32, 12,240,255,255,255,7,192,255,15,254,63,32, 12,248,15,0,254,15,224,255,0,224,63,32, 12,248,15,0,254,15,224,255,0,224,63,32, 12,248,15,0,254,15,224,255,0,224,63,32, 12,248,255,255,255,15,192,255,15,254,63,32, 12,240,255,255,255,7,192,255,31,255,63,32, 28,240,255,255,255,3,128,255,31,255,31,32, 28,240,255,255,255,3,0,255,31,255,31,48, 28,224,255,255,255,1,0,255,31,255,31,48, 28,224,255,255,255,0,0,254,255,255,15,48, 60,192,255,255,127,0,0,252,255,255,7,56, 60,128,255,255,63,0,3,248,255,255,3,56, 124,0,255,255,31,128,3,240,255,255,1,60, 124,0,254,255,7,192,7,192,255,255,0,60, 252,0,248,255,3,224,15,0,255,127,0,62, 252,1,224,127,0,240,31,0,252,15,0,63, 252,3,0,6,0,248,63,0,192,0,0,63, 252,7,0,0,0,252,127,0,0,0,192,63, 252,15,0,0,0,254,255,1,0,0,224,63, 252,31,0,0,128,255,255,3,0,0,240,63, 252,127,0,0,224,255,255,15,0,0,248,63, 252,255,1,0,248,255,255,63,0,0,255,63, 252,255,7,0,254,255,255,255,1,192,255,63, 252,255,255,240,255,255,255,255,31,254,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 252,255,255,255,255,255,255,255,255,255,255,63, 0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0 }; SHARPMEMORYLCD::SHARPMEMORYLCD() { pinMode(DISP, OUTPUT); pinMode(EXTC, OUTPUT); pinMode(EXTM, OUTPUT); //this can be ignored and you can just pull the pin high on your PCB pinMode(SI, OUTPUT); pinMode(SCS, OUTPUT); pinMode(SCLK, OUTPUT); TCCR2B = TCCR2B & 0b11111000 | 0x07; //this sets the EXTC timer on pin 3. you need to change this to move pins constructor(96, 96); LcdClearBuffer(); } SHARPMEMORYLCD::~SHARPMEMORYLCD(){/*nothing to destruct*/} void SHARPMEMORYLCD::LcdInitialize() { digitalWrite(EXTM,HIGH); digitalWrite(DISP,HIGH); delayMicroseconds(50); } void SHARPMEMORYLCD::LcdClearBuffer() { for(int x = 0;x < ARRAYSIZE;x++) { _buffer[x] = 255; } _invert = 0; } void SHARPMEMORYLCD::LcdAllClearMode() { int i; digitalWrite(SCS,HIGH); LcdSetMode(LOW, HIGH); for(i = 0; i < 14; i++){ //Send 14 bits of dummy data digitalWrite(SI,LOW); delayMicroseconds(3); LcdPost(-2); } digitalWrite(SCS,LOW); LcdClearBuffer(); } void SHARPMEMORYLCD::LcdSetMode(int M0, int M2) { int i; digitalWrite(SI,M0); LcdPost(); digitalWrite(SI,HIGH); LcdPost(); digitalWrite(SI,M2); LcdPost(); for(i = 0; i < 5; i++){ //Send 5 bits of dummy data digitalWrite(SI,LOW); LcdPost(); } } void SHARPMEMORYLCD::LcdSendPixels(int num, int state) { int i; for(i = 0; i < num; i++){ digitalWrite(SI,state); LcdPost(0); } } void SHARPMEMORYLCD::LcdSetLineAddress(int line) { int i; unsigned char tmp; for (i = 0; i < 8; i++){ tmp = (line & 1); if (tmp == 1){ digitalWrite(SI,HIGH); LcdPost(0); } else { digitalWrite(SI,LOW); LcdPost(0); } line = line >> 1; } } void SHARPMEMORYLCD::LcdPrintImage(void) { LcdPrintImage(0,ARRAYSIZE); } void SHARPMEMORYLCD::LcdPrintImage(int bitmap, int arraySize) { int i,b; unsigned char LineCount; char temp; LineCount = 1; digitalWrite(SCS,HIGH); LcdSetMode(HIGH,LOW); LcdSetLineAddress(LineCount); for(i = 0; i < arraySize; i++){ if(bitmap == 0) temp = pgm_read_byte(&ARDUINOBMP[i]); else if(bitmap == -1) temp = _buffer[i]; if(_invert == 1) { temp = ~temp; } LcdSendByte(temp); if((i+1) % 12 == 0){ LcdSendPixels(8,0); LineCount++; if(LineCount < 97) LcdSetLineAddress(LineCount); } } delayMicroseconds(1); digitalWrite(SCS,LOW); } void SHARPMEMORYLCD::LcdPost() { LcdPost(1); } void SHARPMEMORYLCD::LcdPost(int delayTime) { digitalWrite(SCLK,HIGH); if(delayTime > 0) { delay(delayTime); } if(delayTime < 0) { delayMicroseconds(delayTime); } digitalWrite(SCLK,LOW); } void SHARPMEMORYLCD::LcdStartEXTC() { analogWrite(EXTC,127); } void SHARPMEMORYLCD::LcdStopEXTC() { analogWrite(EXTC,0); } void SHARPMEMORYLCD::LcdSendByte(char byteToSend) { for(int b = 0; b < 8; b++){ if(byteToSend & 1){ digitalWrite(SI,HIGH); delayMicroseconds(1); LcdPost(0); } else { digitalWrite(SI,LOW); delayMicroseconds(1); LcdPost(0); } byteToSend = byteToSend >> 1; } } void SHARPMEMORYLCD::LcdPrintBuffer() { LcdPrintImage(-1,ARRAYSIZE); } void SHARPMEMORYLCD::invert(uint8_t i) { _invert = i; } void SHARPMEMORYLCD::drawPixel(int16_t x, int16_t y, uint16_t color) { int xloc = ((y*12))+x/8; int shift = (x % 8); if (color) _buffer[xloc] |= (1 << shift); else _buffer[xloc] &= ~(1 << shift); }
[ "larkincrain@gmail.com" ]
larkincrain@gmail.com
e328d0a6dbc2adb2615e101128865e2ea2efcfb5
f7961da64ae861207a8682b72d10530fb7fde536
/sensor_rx_tx.ino
f5c6148b7619fa83b6eba325b2cc0fdd8f79cd82
[]
no_license
joinarun/lora_water_level
fef24e7e4843c8e32da627325e72b3e044e2f235
377731d57bf378e6a679a3d92c79007aee6b7314
refs/heads/main
2023-06-30T16:26:28.677368
2021-07-23T19:56:31
2021-07-23T19:56:31
378,715,676
0
0
null
null
null
null
UTF-8
C++
false
false
3,258
ino
#include <SPI.h> // include libraries #include <LoRa.h> const int csPin = 7; // LoRa radio chip select const int resetPin = 6; // LoRa radio reset const int irqPin = 1; // change for your board; must be a hardware interrupt pin String outgoing; // outgoing message byte msgCount = 0; // count of outgoing messages byte localAddress = 0xBB; // address of this device byte destination = 0xFF; // destination to send to long lastSendTime = 0; // last send time int interval = 2000; // interval between sends void setup() { Serial.begin(9600); // initialize serial while (!Serial); Serial.println("LoRa Duplex"); // override the default CS, reset, and IRQ pins (optional) LoRa.setPins(csPin, resetPin, irqPin);// set CS, reset, IRQ pin if (!LoRa.begin(433E6)) { // initialize ratio at 915 MHz Serial.println("LoRa init failed. Check your connections."); while (true); // if failed, do nothing } Serial.println("LoRa init succeeded."); } void loop() { // parse for a packet, and call onReceive with the result: onReceive(LoRa.parsePacket()); } void sendMessage(String outgoing) { LoRa.beginPacket(); // start packet LoRa.write(destination); // add destination address LoRa.write(localAddress); // add sender address LoRa.write(msgCount); // add message ID LoRa.write(outgoing.length()); // add payload length LoRa.print(outgoing); // add payload LoRa.endPacket(); // finish packet and send it msgCount++; // increment message ID } void onReceive(int packetSize) { if (packetSize == 0) return; // if there's no packet, return // read packet header bytes: int recipient = LoRa.read(); // recipient address byte sender = LoRa.read(); // sender address byte incomingMsgId = LoRa.read(); // incoming msg ID byte incomingLength = LoRa.read(); // incoming msg length String incoming = ""; while (LoRa.available()) { incoming += (char)LoRa.read(); } if (incomingLength != incoming.length()) { // check length for error Serial.println("error: message length does not match length"); return; // skip rest of function } // if the recipient isn't this device or broadcast, if (recipient != localAddress && recipient != 0xFF) { Serial.println("This message is not for me."); return; // skip rest of function } // if message is for this device, or broadcast, print details: Serial.println("Received from: 0x" + String(sender, HEX)); Serial.println("Sent to: 0x" + String(recipient, HEX)); Serial.println("Message ID: " + String(incomingMsgId)); Serial.println("Message length: " + String(incomingLength)); Serial.println("Message: " + incoming); Serial.println("RSSI: " + String(LoRa.packetRssi())); Serial.println("Snr: " + String(LoRa.packetSnr())); String message = "The sensor value is: 98 cm"; sendMessage(message); Serial.println("Sending : " + message); Serial.println(); }
[ "noreply@github.com" ]
noreply@github.com
cdc9a48f18a2ab346a430eefe50b1e5079de15dd
04b1803adb6653ecb7cb827c4f4aa616afacf629
/device/bluetooth/test/test_bluetooth_advertisement_observer.h
d981a2ccbe09b68135c2e795494431df05f0d7fb
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
1,356
h
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef DEVICE_BLUETOOTH_TEST_TEST_BLUETOOTH_ADVERTISEMENT_OBSERVER_H_ #define DEVICE_BLUETOOTH_TEST_TEST_BLUETOOTH_ADVERTISEMENT_OBSERVER_H_ #include <utility> #include "base/macros.h" #include "base/memory/scoped_refptr.h" #include "device/bluetooth/bluetooth_advertisement.h" namespace device { // Test implementation of BluetoothAdvertisement::Observer counting method calls // and caching last reported values. class TestBluetoothAdvertisementObserver : public BluetoothAdvertisement::Observer { public: explicit TestBluetoothAdvertisementObserver( scoped_refptr<BluetoothAdvertisement> advertisement); ~TestBluetoothAdvertisementObserver() override; // BluetoothAdvertisement::Observer: void AdvertisementReleased(BluetoothAdvertisement* advertisement) override; bool released() const { return released_; } size_t released_count() const { return released_count_; } private: bool released_ = false; size_t released_count_ = 0; scoped_refptr<BluetoothAdvertisement> advertisement_; DISALLOW_COPY_AND_ASSIGN(TestBluetoothAdvertisementObserver); }; } // namespace device #endif // DEVICE_BLUETOOTH_TEST_TEST_BLUETOOTH_ADVERTISEMENT_OBSERVER_H_
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
94173717fe7045440906edc577f2ba045aab761a
8e127cd373176709b122e135cd240d1572639e29
/CG/C++/Trabalho2/Ex03/main.cpp
a47cb1e4521f11515dfc0f36093f106bf215dd6e
[]
no_license
maiconwazo/furb6_g1
3f14746520dafb74209a7d0c3fe9fff7637c98c0
a6fb02e44d72eef31ea5372db4cdb4daccdd9b6e
refs/heads/master
2023-08-03T08:42:27.863938
2021-09-10T18:47:14
2021-09-10T18:47:14
99,973,320
0
0
null
null
null
null
UTF-8
C++
false
false
2,051
cpp
#define _USE_MATH_DEFINES #include "..\Dependencies\glew\glew.h" #include "..\Dependencies\freeglut\freeglut.h" #include <math.h> #include <cmath> #include <iostream> double RetornaX(double angulo, double raio) { return (raio * cos(M_PI * angulo / 180.0)); } double RetornaY(double angulo, double raio) { return (raio * sin(M_PI * angulo / 180.0)); } void SRU() { glColor3f(1.0f, 0.0f, 0.0f); glLineWidth(1.0f); glBegin(GL_LINES); glVertex2f(-200.0f, 0.0f); glVertex2f(200.0f, 0.0f); glEnd(); glColor3f(0.0f, 1.0f, 0.0f); glBegin(GL_LINES); glVertex2f(0.0f, -200.0f); glVertex2f(0.0f, 200.0f); glEnd(); } void renderScene(void) { int cont = 0; int rad = 0; glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClearColor(0.86f, 0.86f, 0.86f, 0.86f); gluOrtho2D(-400.0f, 400.0f, -400.0f, 400.0f); SRU(); glColor3f(0.0f, 1.0f, 1.0f); glLineWidth(1.0f); glBegin(GL_LINE_STRIP); //triangulo azul glVertex2d(-100, 100); glVertex2d(100, 100); glVertex2d(0, -100); glVertex2d(-100, 100); glEnd(); glColor3f(0.0f, 0.0f, 0.0f); glLineWidth(2.0f); glBegin(GL_LINE_LOOP); //circulo nordeste for (int i = 0; i < 180; i++) { glVertex2d(RetornaX(i * 2, 100) + 100, RetornaY(i * 2, 100) + 100); } glEnd(); glBegin(GL_LINE_LOOP); //circulo noroeste for (int i = 0; i < 180; i++) { glVertex2d(RetornaX(i * 2, 100) - 100, RetornaY(i * 2, 100) + 100); } glEnd(); glBegin(GL_LINE_LOOP); //circulo sul for (int i = 0; i < 180; i++) { glVertex2d(RetornaX(i * 2, 100), RetornaY(i * 2, 100) - 100); } glEnd(); glFlush(); } void reshape(int x, int y) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glViewport(0, 0, x, y); } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitWindowPosition(700, 300); glutInitWindowSize(600, 600); glutCreateWindow("OpenGL First Window"); glutDisplayFunc(renderScene); glutReshapeFunc(reshape); glutMainLoop(); return 0; }
[ "maiconsantos2501@gmail.com" ]
maiconsantos2501@gmail.com
5ed28e5dce7fe1bc46a182ffebd2d978579fb48a
b6d40ef857c574404cada4f372f873d539ab604d
/Source/ToonTanks/Pawns/PawnTurret.cpp
b5cdfa58ea807215ba5f8e1946433b9b7ca05103
[]
no_license
aeche95/ToonTanks
cb7fa85d371bb2c6663e085a8494bb90039856a2
f1d4576fdd7e0f29531e95d3916cf2add7a66f81
refs/heads/master
2023-02-20T17:16:01.649831
2021-01-28T16:08:57
2021-01-28T16:08:57
333,811,022
0
0
null
null
null
null
UTF-8
C++
false
false
1,154
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "PawnTurret.h" #include "Kismet/GameplayStatics.h" #include "PawnTank.h" // Called when the game starts or when spawned void APawnTurret::BeginPlay() { Super::BeginPlay(); GetWorldTimerManager().SetTimer(FireRateTimerHandle,this,&APawnTurret::CheckFireCondition,FireRate,true); PlayerPawn = Cast<APawnTank>(UGameplayStatics::GetPlayerPawn(this,0)); } // Called every frame void APawnTurret::Tick(float DeltaTime) { Super::Tick(DeltaTime); if(!PlayerPawn || ReturnDistanceToPlayer()>FireRange) { return; } RotateTurret(PlayerPawn->GetActorLocation()); } void APawnTurret::CheckFireCondition() { if(!PlayerPawn || !PlayerPawn->GetIsPlayerAlive()) { return; } if(ReturnDistanceToPlayer() <= FireRange) { Fire(); } } float APawnTurret::ReturnDistanceToPlayer() { if(!PlayerPawn) { return 0.f; } return FVector::Dist(PlayerPawn->GetActorLocation(),GetActorLocation()); } void APawnTurret::HandleDestruction() { Super::HandleDestruction(); Destroy(); }
[ "aecheverri.1995@gmail.com" ]
aecheverri.1995@gmail.com
eb184bbbed623745ebdc050db453eab0ecd33072
c9b8a2e06f0f33281a6f1dcf4fc6819f42259f75
/Export/windows/cpp/obj/include/openfl/_internal/renderer/canvas/CanvasGraphics.h
db6233a2e5ec8c4b89e4c8acbd8f0f75da96eafb
[]
no_license
AppOlogies/mutant-helper
7b4732b1ad2979a221f83eef24b7c73f90c6b8b9
2be5653846ee529e5a3d4d02112b98c30ba33bde
refs/heads/master
2016-09-01T11:26:15.417217
2015-11-03T16:44:24
2015-11-03T16:44:24
43,067,958
0
0
null
null
null
null
UTF-8
C++
false
false
3,930
h
#ifndef INCLUDED_openfl__internal_renderer_canvas_CanvasGraphics #define INCLUDED_openfl__internal_renderer_canvas_CanvasGraphics #ifndef HXCPP_H #include <hxcpp.h> #endif HX_DECLARE_CLASS3(openfl,_internal,renderer,RenderSession) HX_DECLARE_CLASS4(openfl,_internal,renderer,canvas,CanvasGraphics) HX_DECLARE_CLASS2(openfl,display,BitmapData) HX_DECLARE_CLASS2(openfl,display,DrawCommand) HX_DECLARE_CLASS2(openfl,display,GradientType) HX_DECLARE_CLASS2(openfl,display,Graphics) HX_DECLARE_CLASS2(openfl,display,IBitmapDrawable) HX_DECLARE_CLASS2(openfl,display,InterpolationMethod) HX_DECLARE_CLASS2(openfl,display,SpreadMethod) HX_DECLARE_CLASS2(openfl,geom,Matrix) HX_DECLARE_CLASS2(openfl,geom,Rectangle) namespace openfl{ namespace _internal{ namespace renderer{ namespace canvas{ class HXCPP_CLASS_ATTRIBUTES CanvasGraphics_obj : public hx::Object{ public: typedef hx::Object super; typedef CanvasGraphics_obj OBJ_; CanvasGraphics_obj(); Void __construct(); public: inline void *operator new( size_t inSize, bool inContainer=false,const char *inName="openfl._internal.renderer.canvas.CanvasGraphics") { return hx::Object::operator new(inSize,inContainer,inName); } static hx::ObjectPtr< CanvasGraphics_obj > __new(); static Dynamic __CreateEmpty(); static Dynamic __Create(hx::DynamicArray inArgs); //~CanvasGraphics_obj(); HX_DO_RTTI_ALL; static bool __GetStatic(const ::String &inString, Dynamic &outValue, hx::PropertyAccess inCallProp); static void __register(); ::String __ToString() const { return HX_HCSTRING("CanvasGraphics","\xe3","\x35","\xd6","\x92"); } static void __boot(); static Float SIN45; static Float TAN22; static ::openfl::display::BitmapData bitmapFill; static ::openfl::display::BitmapData bitmapStroke; static bool bitmapRepeat; static ::openfl::geom::Rectangle bounds; static Array< ::Dynamic > fillCommands; static ::openfl::display::Graphics graphics; static bool hasFill; static bool hasStroke; static ::openfl::geom::Matrix inversePendingMatrix; static ::openfl::geom::Matrix pendingMatrix; static Array< ::Dynamic > strokeCommands; static Dynamic createBitmapFill( ::openfl::display::BitmapData bitmap,bool bitmapRepeat); static Dynamic createBitmapFill_dyn(); static Void createTempPatternCanvas( ::openfl::display::BitmapData bitmap,bool repeat,int width,int height); static Dynamic createTempPatternCanvas_dyn(); static Void endFill( ); static Dynamic endFill_dyn(); static Void endStroke( ); static Dynamic endStroke_dyn(); static Void closePath( ); static Dynamic closePath_dyn(); static Void drawRoundRect( Float x,Float y,Float width,Float height,Float rx,Float ry); static Dynamic drawRoundRect_dyn(); static bool isCCW( Float x1,Float y1,Float x2,Float y2,Float x3,Float y3); static Dynamic isCCW_dyn(); static Dynamic normalizeUVT( Array< Float > uvt,hx::Null< bool > skipT); static Dynamic normalizeUVT_dyn(); static Void playCommands( Array< ::Dynamic > commands,hx::Null< bool > stroke); static Dynamic playCommands_dyn(); static Void createGradientPattern( ::openfl::display::GradientType type,cpp::ArrayBase colors,cpp::ArrayBase alphas,cpp::ArrayBase ratios,::openfl::geom::Matrix matrix,::openfl::display::SpreadMethod spreadMethod,::openfl::display::InterpolationMethod interpolationMethod,Dynamic focalPointRatio); static Dynamic createGradientPattern_dyn(); static Void render( ::openfl::display::Graphics graphics,::openfl::_internal::renderer::RenderSession renderSession); static Dynamic render_dyn(); static Void renderMask( ::openfl::display::Graphics graphics,::openfl::_internal::renderer::RenderSession renderSession); static Dynamic renderMask_dyn(); }; } // end namespace openfl } // end namespace _internal } // end namespace renderer } // end namespace canvas #endif /* INCLUDED_openfl__internal_renderer_canvas_CanvasGraphics */
[ "magnusjohansson82@gmail.com" ]
magnusjohansson82@gmail.com
28688edeb868bd7f1f52cb5ea40575186f874c65
1f7e2b9d209a04542d0a04524a129a74215eae25
/PAD2_Praktikum3_lars/travelagency.h
5522b159520c80812deb0263c08141ed787e9b1b
[]
no_license
panexe/h_da_PAD2_Malcherek
346540ea4500768352efa197029b6cd5b528c735
49830bc756b8ce2eb5659b182d2776c259d7e31b
refs/heads/master
2020-05-04T15:41:13.810127
2019-06-15T13:19:03
2019-06-15T13:19:03
179,252,080
0
0
null
null
null
null
UTF-8
C++
false
false
746
h
#ifndef TRAVELAGENCY_H #define TRAVELAGENCY_H #include <vector> #include "booking.h" #include "travel.h" #include "customer.h" class TravelAgency { std::vector<Booking*> allBookings; std::vector<Travel*> allTravels; std::vector<Customer*> allCustomers; int getHighestId(); public: TravelAgency(); ~TravelAgency(); std::string readFile(); Booking* findBooking(long id); Travel* findTravel(long id); Customer* findCustomer(long id); Booking *getBooking(unsigned int index); int getBookingsSize(); int createBooking(char type, double price, std::string start, std::string end, long travelID, std::vector<std::string> bookingDetails); void printNumerals(); }; #endif // TRAVELAGENCY_H
[ "larslpt@gmail.com" ]
larslpt@gmail.com
44e3a306677cdc960d309e49547cde860e0f3b27
609d6fc5e87838cfa0f9ac574d0791ba775ae107
/src/petri.hpp
4990ac35aa440117026bdf393ab9b0861a2c8156
[]
no_license
ftZHOU/petri-network
c056cdcb6ad10ee5bdf0d39589d10be9e0937df8
b5c3b813b6bace1f3607ce6ab8f09fa41f8f0242
refs/heads/master
2021-08-07T13:53:57.116190
2017-11-08T08:16:40
2017-11-08T08:16:40
109,946,607
0
0
null
null
null
null
UTF-8
C++
false
false
43
hpp
#pragma once #include <petriNetwork.hpp>
[ "ftzhou@outlook.com" ]
ftzhou@outlook.com
37b5eec3aed4b81507e107a58096af768c03edd6
c48435fa9ea66653c5fbc021533265b5dca04769
/src/cpp/AlnGraphBoost.cpp
e0537bb41850dde53a8511b0e0696e5b970ee047
[]
no_license
jgurtowski/pbdagcon_python
544b647fb23d0fdd1766090f9fcca0bc405c4406
5c1ff1a26ddedac142855593b5d2a1fdbd82f5a2
refs/heads/master
2016-08-05T14:48:13.061829
2015-08-21T12:29:42
2015-08-21T12:29:42
41,154,670
3
1
null
null
null
null
UTF-8
C++
false
false
15,439
cpp
#include <cstdint> #include <cfloat> #include <cassert> #include <string> #include <queue> #include <map> #include <vector> #include <boost/format.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/graphviz.hpp> #include <boost/utility/value_init.hpp> #include "Alignment.hpp" #include "AlnGraphBoost.hpp" AlnGraphBoost::AlnGraphBoost(const std::string& backbone) { // initialize the graph structure with the backbone length + enter/exit // vertex size_t blen = backbone.length(); _g = G(blen+1); for (size_t i = 0; i < blen+1; i++) boost::add_edge(i, i+1, _g); VtxIter curr, last; tie(curr, last) = boost::vertices(_g); _enterVtx = *curr++; _g[_enterVtx].base = '^'; _g[_enterVtx].backbone = true; for (size_t i = 0; i < blen; i++, ++curr) { VtxDesc v = *curr; _g[v].base = backbone[i]; _g[v].backbone = true; _g[v].weight = 1; _bbMap[v] = v; } _exitVtx = *curr; _g[_exitVtx].base = '$'; _g[_exitVtx].backbone = true; } AlnGraphBoost::AlnGraphBoost(const size_t blen) { _g = G(blen+1); for (size_t i = 0; i < blen+1; i++) boost::add_edge(i, i+1, _g); VtxIter curr, last; tie(curr, last) = boost::vertices(_g); _enterVtx = *curr++; _g[_enterVtx].base = '^'; _g[_enterVtx].backbone = true; for (size_t i = 0; i < blen; i++, ++curr) { VtxDesc v = *curr; _g[v].backbone = true; _g[v].weight = 1; _g[v].deleted = false; _g[v].base = 'N'; _bbMap[v] = v; } _exitVtx = *curr; _g[_exitVtx].base = '$'; _g[_exitVtx].backbone = true; } void AlnGraphBoost::addAln(dagcon::Alignment& aln) { IndexMap index = boost::get(boost::vertex_index, _g); // tracks the position on the backbone uint32_t bbPos = aln.start; VtxDesc prevVtx = _enterVtx; for (size_t i = 0; i < aln.qstr.length(); i++) { char queryBase = aln.qstr[i], targetBase = aln.tstr[i]; VtxDesc currVtx = index[bbPos]; // match if (queryBase == targetBase) { _g[_bbMap[currVtx]].coverage++; // NOTE: for empty backbones _g[_bbMap[currVtx]].base = targetBase; _g[currVtx].weight++; addEdge(prevVtx, currVtx); bbPos++; prevVtx = currVtx; // query deletion } else if (queryBase == '-' && targetBase != '-') { _g[_bbMap[currVtx]].coverage++; // NOTE: for empty backbones _g[_bbMap[currVtx]].base = targetBase; bbPos++; // query insertion } else if (queryBase != '-' && targetBase == '-') { // create new node and edge VtxDesc newVtx = boost::add_vertex(_g); _g[newVtx].base = queryBase; _g[newVtx].weight++; _g[newVtx].backbone = false; _g[newVtx].deleted = false; _bbMap[newVtx] = bbPos; addEdge(prevVtx, newVtx); prevVtx = newVtx; } } addEdge(prevVtx, _exitVtx); } void AlnGraphBoost::addEdge(VtxDesc u, VtxDesc v) { // Check if edge exists with prev node. If it does, increment edge counter, // otherwise add a new edge. InEdgeIter ii, ie; bool edgeExists = false; for (tie(ii, ie) = boost::in_edges(v, _g); ii != ie; ++ii) { EdgeDesc e = *ii; if (boost::source(e , _g) == u) { // increment edge count _g[e].count++; edgeExists = true; } } if (! edgeExists) { // add new edge std::pair<EdgeDesc, bool> p = boost::add_edge(u, v, _g); _g[p.first].count++; } } void AlnGraphBoost::mergeNodes() { std::queue<VtxDesc> seedNodes; seedNodes.push(_enterVtx); while(true) { if (seedNodes.size() == 0) break; VtxDesc u = seedNodes.front(); seedNodes.pop(); mergeInNodes(u); mergeOutNodes(u); OutEdgeIter oi, oe; for (tie(oi, oe) = boost::out_edges(u, _g); oi != oe; ++oi) { EdgeDesc e = *oi; _g[e].visited = true; VtxDesc v = boost::target(e, _g); InEdgeIter ii, ie; int notVisited = 0; for (tie(ii, ie) = boost::in_edges(v, _g); ii != ie; ++ii) { if (_g[*ii].visited == false) notVisited++; } // move onto the boost::target node after we visit all incoming edges for // the boost::target node if (notVisited == 0) seedNodes.push(v); } } } void AlnGraphBoost::mergeInNodes(VtxDesc n) { std::map<char, std::vector<VtxDesc>> nodeGroups; InEdgeIter ii, ie; // Group neighboring nodes by base for(tie(ii, ie) = boost::in_edges(n, _g); ii != ie; ++ii) { VtxDesc inNode = boost::source(*ii, _g); if (out_degree(inNode, _g) == 1) { nodeGroups[_g[inNode].base].push_back(inNode); } } // iterate over node groups, merge an accumulate information for(auto kvp = nodeGroups.cbegin(); kvp != nodeGroups.end(); ++kvp) { std::vector<VtxDesc> nodes = (*kvp).second; if (nodes.size() <= 1) continue; std::vector<VtxDesc>::const_iterator ni = nodes.cbegin(); VtxDesc an = *ni++; OutEdgeIter anoi, anoe; tie(anoi, anoe) = boost::out_edges(an, _g); // Accumulate out edge information for (; ni != nodes.cend(); ++ni) { OutEdgeIter oi, oe; tie(oi, oe) = boost::out_edges(*ni, _g); _g[*anoi].count += _g[*oi].count; _g[an].weight += _g[*ni].weight; } // Accumulate in edge information, merges nodes ni = nodes.cbegin(); ++ni; for (; ni != nodes.cend(); ++ni) { InEdgeIter ii, ie; VtxDesc n = *ni; for (tie(ii, ie) = boost::in_edges(n, _g); ii != ie; ++ii) { VtxDesc n1 = boost::source(*ii, _g); EdgeDesc e; bool exists; tie(e, exists) = edge(n1, an, _g); if (exists) { _g[e].count += _g[*ii].count; } else { std::pair<EdgeDesc, bool> p = boost::add_edge(n1, an, _g); _g[p.first].count = _g[*ii].count; _g[p.first].visited = _g[*ii].visited; } } markForReaper(n); } mergeInNodes(an); } } void AlnGraphBoost::mergeOutNodes(VtxDesc n) { std::map<char, std::vector<VtxDesc>> nodeGroups; OutEdgeIter oi, oe; for(tie(oi, oe) = boost::out_edges(n, _g); oi != oe; ++oi) { VtxDesc outNode = boost::target(*oi, _g); if (in_degree(outNode, _g) == 1) { nodeGroups[_g[outNode].base].push_back(outNode); } } for(auto kvp = nodeGroups.cbegin(); kvp != nodeGroups.end(); ++kvp) { std::vector<VtxDesc> nodes = (*kvp).second; if (nodes.size() <= 1) continue; std::vector<VtxDesc>::const_iterator ni = nodes.cbegin(); VtxDesc an = *ni++; InEdgeIter anii, anie; tie(anii, anie) = boost::in_edges(an, _g); // Accumulate inner edge information for (; ni != nodes.cend(); ++ni) { InEdgeIter ii, ie; tie(ii, ie) = boost::in_edges(*ni, _g); _g[*anii].count += _g[*ii].count; _g[an].weight += _g[*ni].weight; } // Accumulate and merge outer edge information ni = nodes.cbegin(); ++ni; for (; ni != nodes.cend(); ++ni) { OutEdgeIter oi, oe; VtxDesc n = *ni; for (tie(oi, oe) = boost::out_edges(n, _g); oi != oe; ++oi) { VtxDesc n2 = boost::target(*oi, _g); EdgeDesc e; bool exists; tie(e, exists) = edge(an, n2, _g); if (exists) { _g[e].count += _g[*oi].count; } else { std::pair<EdgeDesc, bool> p = boost::add_edge(an, n2, _g); _g[p.first].count = _g[*oi].count; _g[p.first].visited = _g[*oi].visited; } } markForReaper(n); } } } void AlnGraphBoost::markForReaper(VtxDesc n) { _g[n].deleted = true; clear_vertex(n, _g); _reaperBag.push_back(n); } void AlnGraphBoost::reapNodes() { int reapCount = 0; std::sort(_reaperBag.begin(), _reaperBag.end()); std::vector<VtxDesc>::iterator curr = _reaperBag.begin(); for (; curr != _reaperBag.end(); ++curr) { assert(_g[*curr].backbone==false); remove_vertex(*curr-reapCount++, _g); } } const std::string AlnGraphBoost::consensus(int minWeight) { // get the best scoring path std::vector<AlnNode> path = bestPath(); // consensus sequence std::string cns; // track the longest consensus path meeting minimum weight int offs = 0, bestOffs = 0, length = 0, idx = 0; bool metWeight = false; std::vector<AlnNode>::iterator curr = path.begin(); for (; curr != path.end(); ++curr) { AlnNode n = *curr; if (n.base == _g[_enterVtx].base || n.base == _g[_exitVtx].base) continue; cns += n.base; // initial beginning of minimum weight section if (!metWeight && n.weight >= minWeight) { offs = idx; metWeight = true; } else if (metWeight && n.weight < minWeight) { // concluded minimum weight section, update if longest seen so far if ((idx - offs) > length) { bestOffs = offs; length = idx - offs; } metWeight = false; } idx++; } // include end of sequence if (metWeight && (idx - offs) > length) { bestOffs = offs; length = idx - offs; } return cns.substr(bestOffs, length); } void AlnGraphBoost::consensus(std::vector<CnsResult>& seqs, int minWeight, size_t minLen) { seqs.clear(); // get the best scoring path std::vector<AlnNode> path = bestPath(); // consensus sequence std::string cns; // track the longest consensus path meeting minimum weight int offs = 0, idx = 0; bool metWeight = false; std::vector<AlnNode>::iterator curr = path.begin(); for (; curr != path.end(); ++curr) { AlnNode n = *curr; if (n.base == _g[_enterVtx].base || n.base == _g[_exitVtx].base) continue; cns += n.base; // initial beginning of minimum weight section if (!metWeight && n.weight >= minWeight) { offs = idx; metWeight = true; } else if (metWeight && n.weight < minWeight) { // concluded minimum weight section, add sequence to supplied vector metWeight = false; CnsResult result; result.range[0] = offs; result.range[1] = idx; size_t length = idx - offs; result.seq = cns.substr(offs, length); if (length >= minLen) seqs.push_back(result); } idx++; } // include end of sequence if (metWeight) { size_t length = idx - offs; CnsResult result; result.range[0] = offs; result.range[1] = idx; result.seq = cns.substr(offs, length); if (length >= minLen) seqs.push_back(result); } } const std::vector<AlnNode> AlnGraphBoost::bestPath() { EdgeIter ei, ee; for (tie(ei, ee) = edges(_g); ei != ee; ++ei) _g[*ei].visited = false; std::map<VtxDesc, EdgeDesc> bestNodeScoreEdge; std::map<VtxDesc, float> nodeScore; std::queue<VtxDesc> seedNodes; // start at the end and make our way backwards seedNodes.push(_exitVtx); nodeScore[_exitVtx] = 0.0f; while (true) { if (seedNodes.size() == 0) break; VtxDesc n = seedNodes.front(); seedNodes.pop(); bool bestEdgeFound = false; float bestScore = -FLT_MAX; EdgeDesc bestEdgeD = boost::initialized_value; OutEdgeIter oi, oe; for(tie(oi, oe) = boost::out_edges(n, _g); oi != oe; ++oi) { EdgeDesc outEdgeD = *oi; VtxDesc outNodeD = boost::target(outEdgeD, _g); AlnNode outNode = _g[outNodeD]; float newScore, score = nodeScore[outNodeD]; if (outNode.backbone && outNode.weight == 1) { newScore = score - 10.0f; } else { AlnNode bbNode = _g[_bbMap[outNodeD]]; newScore = _g[outEdgeD].count - bbNode.coverage*0.5f + score; } if (newScore > bestScore) { bestScore = newScore; bestEdgeD = outEdgeD; bestEdgeFound = true; } } if (bestEdgeFound) { nodeScore[n]= bestScore; bestNodeScoreEdge[n] = bestEdgeD; } InEdgeIter ii, ie; for (tie(ii, ie) = boost::in_edges(n, _g); ii != ie; ++ii) { EdgeDesc inEdge = *ii; _g[inEdge].visited = true; VtxDesc inNode = boost::source(inEdge, _g); int notVisited = 0; OutEdgeIter oi, oe; for (tie(oi, oe) = boost::out_edges(inNode, _g); oi != oe; ++oi) { if (_g[*oi].visited == false) notVisited++; } // move onto the target node after we visit all incoming edges for // the target node if (notVisited == 0) seedNodes.push(inNode); } } // construct the final best path VtxDesc prev = _enterVtx, next; std::vector<AlnNode> bpath; while (true) { bpath.push_back(_g[prev]); if (bestNodeScoreEdge.count(prev) == 0) { break; } else { EdgeDesc bestOutEdge = bestNodeScoreEdge[prev]; _g[prev].bestOutEdge = bestOutEdge; next = boost::target(bestOutEdge, _g); _g[next].bestInEdge = bestOutEdge; prev = next; } } return bpath; } void AlnGraphBoost::printGraph() { reapNodes(); boost::write_graphviz(std::cout, _g, make_label_writer(get(&AlnNode::base, _g)), make_label_writer(get(&AlnEdge::count, _g))); } bool AlnGraphBoost::danglingNodes() { log4cpp::Category& logger = log4cpp::Category::getInstance("AlnGraph"); boost::format msg("Found dangling node. No %s edges: %d"); VtxIter curr, last; tie(curr, last) = boost::vertices(_g); bool found = false; for (;curr != last; ++curr) { if (_g[*curr].deleted) continue; if (_g[*curr].base == _g[_enterVtx].base || _g[*curr].base == _g[_exitVtx].base) continue; int indeg = out_degree(*curr, _g); int outdeg = in_degree(*curr, _g); if (outdeg > 0 && indeg > 0) continue; msg % (outdeg == 0 ? "outgoing" : "incoming"); msg % *curr; logger.errorStream() << msg.str(); found = true; } return found; } AlnGraphBoost::~AlnGraphBoost(){}
[ "a@b" ]
a@b