hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
โŒ€
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
โŒ€
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
โŒ€
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
โŒ€
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
โŒ€
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
โŒ€
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
โŒ€
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
โŒ€
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
โŒ€
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
b46d486ba1961e9b0efa39bc2b25efa8b26cf3c8
27,018
cpp
C++
thorlcr/activities/join/thjoinslave.cpp
miguelvazq/HPCC-Platform
22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5
[ "Apache-2.0" ]
null
null
null
thorlcr/activities/join/thjoinslave.cpp
miguelvazq/HPCC-Platform
22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5
[ "Apache-2.0" ]
null
null
null
thorlcr/activities/join/thjoinslave.cpp
miguelvazq/HPCC-Platform
22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5
[ "Apache-2.0" ]
null
null
null
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2012 HPCC Systemsยฎ. 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. ############################################################################## */ #include "thjoinslave.ipp" #include "jio.hpp" #include "jiface.hpp" #include "thorstep.ipp" #include "tsorts.hpp" #include "tsorta.hpp" #include "thsortu.hpp" #include "thorport.hpp" #include "thormisc.hpp" #include "thbufdef.hpp" #include "limits.h" #include "commonext.hpp" #include "thactivityutil.ipp" #include "thexception.hpp" #include "tsortm.hpp" #define BUFFERSIZE 0x10000 #define NUMSLAVEPORTS 2 // actually should be num MP tags class JoinSlaveActivity : public CSlaveActivity, implements ILookAheadStopNotify { typedef CSlaveActivity PARENT; unsigned secondaryInputIndex = 0; unsigned primaryInputIndex = 0; IEngineRowStream *rightInputStream = nullptr; IEngineRowStream *primaryInputStream = nullptr; IEngineRowStream *secondaryInputStream = nullptr; Owned<IThorDataLink> leftInput, rightInput; Owned<IThorDataLink> secondaryInput, primaryInput; Owned<IThorSorter> sorter; unsigned portbase = 0; mptag_t mpTagRPC = TAG_NULL; ICompare *primarySecondaryCompare = nullptr; ICompare *primarySecondaryUpperCompare = nullptr; // if non-null then between join Owned<IRowStream> leftStream, rightStream; Owned<IException> secondaryStartException; Owned<IThorRowLoader> iLoaderL; Owned<IBarrier> barrier; SocketEndpoint server; Owned<IJoinHelper> joinhelper; rowcount_t lhsProgressCount = 0, rhsProgressCount = 0; CriticalSection joinHelperCrit; CRuntimeStatisticCollection spillStats; IHThorJoinBaseArg *helper; IHThorJoinArg *helperjn; IHThorDenormalizeArg *helperdn; ICompare *leftCompare; ICompare *rightCompare; ISortKeySerializer *leftKeySerializer; ISortKeySerializer *rightKeySerializer; bool rightpartition; bool islocal; bool hintunsortedoutput = false; bool hintparallelmatch = false; bool noSortPartitionSide() { if (ALWAYS_SORT_PRIMARY) return false; return (rightpartition?helper->isRightAlreadySorted():helper->isLeftAlreadySorted()); } bool noSortOtherSide() { return (rightpartition?helper->isLeftAlreadySorted():helper->isRightAlreadySorted()); } bool isUnstable() { // actually don't think currently supported by join but maybe will be sometime return false; } class cRowStreamPlus1Adaptor: implements IRowStream, public CSimpleInterface { OwnedConstThorRow firstrow; Linked<IRowStream> base; public: IMPLEMENT_IINTERFACE_USING(CSimpleInterface); cRowStreamPlus1Adaptor(IRowStream *_base,const void *_firstrow) : base(_base) { firstrow.set(_firstrow); } const void *nextRow() { if (firstrow) return firstrow.getClear(); return base->ungroupedNextRow(); } void stop() { firstrow.clear(); base->stop(); } }; struct CompareReverse : public ICompare { CompareReverse() { compare = NULL; } ICompare *compare; int docompare(const void *a,const void *b) const { return -compare->docompare(b,a); } } compareReverse, compareReverseUpper; public: JoinSlaveActivity(CGraphElementBase *_container, bool local) : CSlaveActivity(_container), spillStats(spillStatistics) { islocal = local; switch (container.getKind()) { case TAKdenormalize: case TAKdenormalizegroup: { helperjn = nullptr; helperdn = (IHThorDenormalizeArg *)container.queryHelper(); helper = helperdn; break; } case TAKjoin: { helperjn = (IHThorJoinArg *)container.queryHelper(); helperdn = nullptr; helper = helperjn; break; } default: throwUnexpected(); } leftCompare = helper->queryCompareLeft(); rightCompare = helper->queryCompareRight(); leftKeySerializer = helper->querySerializeLeft(); rightKeySerializer = helper->querySerializeRight(); rightpartition = (container.getKind()==TAKjoin)&&((helper->getJoinFlags()&JFpartitionright)!=0); if (islocal) setRequireInitData(false); hintunsortedoutput = getOptBool(THOROPT_UNSORTED_OUTPUT, (JFreorderable & helper->getJoinFlags()) != 0); hintparallelmatch = getOptBool(THOROPT_PARALLEL_MATCH, hintunsortedoutput); // i.e. unsorted, implies use parallel by default, otherwise no point appendOutputLinked(this); } ~JoinSlaveActivity() { if (portbase) freePort(portbase,NUMSLAVEPORTS); } virtual void init(MemoryBuffer &data, MemoryBuffer &slaveData) override { if (islocal) iLoaderL.setown(createThorRowLoader(*this, ::queryRowInterfaces(queryInput(0)), leftCompare, stableSort_earlyAlloc, rc_mixed, SPILL_PRIORITY_JOIN)); else { mpTagRPC = container.queryJobChannel().deserializeMPTag(data); mptag_t barrierTag = container.queryJobChannel().deserializeMPTag(data); barrier.setown(container.queryJobChannel().createBarrier(barrierTag)); portbase = allocPort(NUMSLAVEPORTS); ActPrintLog("SortJoinSlaveActivity::init portbase = %d, mpTagRPC=%d",portbase,(int)mpTagRPC); server.setLocalHost(portbase); sorter.setown(CreateThorSorter(this, server,&container.queryJob().queryIDiskUsage(),&queryJobChannel().queryJobComm(),mpTagRPC)); server.serialize(slaveData); } } virtual void setInputStream(unsigned index, CThorInput &_input, bool consumerOrdered) override { PARENT::setInputStream(index, _input, consumerOrdered); if ((rightpartition && (0 == index)) || (!rightpartition && (1 == index))) { secondaryInputIndex = index; secondaryInputStream = queryInputStream(secondaryInputIndex); if (!isFastThrough(_input.itdl)) { IStartableEngineRowStream *lookAhead = createRowStreamLookAhead(this, secondaryInputStream, queryRowInterfaces(_input.itdl), JOIN_SMART_BUFFER_SIZE, isSmartBufferSpillNeeded(_input.itdl->queryFromActivity()), false, RCUNBOUND, this, &container.queryJob().queryIDiskUsage()); setLookAhead(secondaryInputIndex, lookAhead), secondaryInputStream = lookAhead; } } else { primaryInputIndex = index; primaryInputStream = queryInputStream(primaryInputIndex); } if (1 == index) rightInputStream = queryInputStream(1); } virtual void onInputFinished(rowcount_t count) override { ActPrintLog("JOIN: %s input finished, %" RCPF "d rows read", rightpartition?"LHS":"RHS", count); } void doDataLinkStart() { dataLinkStart(); CriticalBlock b(joinHelperCrit); switch(container.getKind()) { case TAKjoin: { joinhelper.setown(createJoinHelper(*this, helperjn, this, hintparallelmatch, hintunsortedoutput)); break; } case TAKdenormalize: case TAKdenormalizegroup: { joinhelper.setown(createDenormalizeHelper(*this, helperdn, this)); break; } } } void startSecondaryInput() { try { startInput(secondaryInputIndex); } catch (IException *e) { secondaryStartException.setown(e); } } virtual void start() override { ActivityTimer s(totalCycles, timeActivities); Linked<IThorRowInterfaces> primaryRowIf, secondaryRowIf; StringAttr primaryInputStr, secondaryInputStr; if (rightpartition) { primaryInput.set(queryInput(1)); secondaryInput.set(queryInput(0)); primaryInputStr.set("R"); secondaryInputStr.set("L"); } else { primaryInput.set(queryInput(0)); secondaryInput.set(queryInput(1)); primaryInputStr.set("L"); secondaryInputStr.set("R"); } ActPrintLog("JOIN partition: %s", primaryInputStr.get()); ActPrintLog("JOIN: Starting %s then %s", secondaryInputStr.get(), primaryInputStr.get()); CAsyncCallStart asyncSecondaryStart(std::bind(&JoinSlaveActivity::startSecondaryInput, this)); try { startInput(primaryInputIndex); } catch (IException *e) { fireException(e); barrier->cancel(); asyncSecondaryStart.wait(); stopOtherInput(); throw; } asyncSecondaryStart.wait(); if (secondaryStartException) { IException *e=secondaryStartException.getClear(); fireException(e); barrier->cancel(); stopPartitionInput(); throw e; } if (rightpartition) { leftInput.set(secondaryInput); rightInput.set(primaryInput); } else { leftInput.set(primaryInput); rightInput.set(secondaryInput); } doDataLinkStart(); if (islocal) dolocaljoin(); else { if (!doglobaljoin()) { Sleep(1000); // let original error through throw MakeActivityException(this, TE_BarrierAborted, "JOIN: Barrier Aborted"); } } if (!leftStream.get()||!rightStream.get()) throw MakeActivityException(this, TE_FailedToStartJoinStreams, "Failed to start join streams"); joinhelper->init(leftStream, rightStream, ::queryRowAllocator(queryInput(0)),::queryRowAllocator(queryInput(1)),::queryRowMetaData(queryInput(0))); } void stopLeftInput() { stopInput(0, "(L)"); } void stopRightInput() { stopInput(1, "(R)"); } void stopPartitionInput() { if (rightpartition) stopRightInput(); else stopLeftInput(); } void stopOtherInput() { if (rightpartition) stopLeftInput(); else stopRightInput(); } virtual void abort() override { CSlaveActivity::abort(); if (joinhelper) joinhelper->stop(); } virtual void stop() override { stopLeftInput(); stopRightInput(); /* need to if input started, because activity might never have been started, if conditional * activities downstream stopped their inactive inputs. * stop()'s are chained like this, so that upstream splitters can be stopped as quickly as possible * in order to reduce buffering. */ if (hasStarted()) { lhsProgressCount = joinhelper->getLhsProgress(); rhsProgressCount = joinhelper->getRhsProgress(); { CriticalBlock b(joinHelperCrit); joinhelper.clear(); } ActPrintLog("SortJoinSlaveActivity::stop"); rightStream.clear(); if (!islocal) { unsigned bn=noSortPartitionSide()?2:4; ActPrintLog("JOIN waiting barrier.%d",bn); barrier->wait(false); ActPrintLog("JOIN barrier.%d raised",bn); sorter->stopMerge(); } leftStream.clear(); dataLinkStop(); leftInput.clear(); rightInput.clear(); } } virtual void reset() override { PARENT::reset(); if (sorter) return; // JCSMORE loop - shouldn't have to recreate sorter between loop iterations if (!islocal && TAG_NULL != mpTagRPC) sorter.setown(CreateThorSorter(this, server,&container.queryJob().queryIDiskUsage(),&queryJobChannel().queryJobComm(),mpTagRPC)); } void kill() { sorter.clear(); leftInput.clear(); rightInput.clear(); CSlaveActivity::kill(); } CATCH_NEXTROW() { ActivityTimer t(totalCycles, timeActivities); if(joinhelper) { OwnedConstThorRow row = joinhelper->nextRow(); if (row) { dataLinkIncrement(); return row.getClear(); } } return NULL; } virtual bool isGrouped() const override { return false; } virtual void getMetaInfo(ThorDataLinkMetaInfo &info) override { initMetaInfo(info); info.unknownRowsOutput = true; info.canBufferInput = true; } void dolocaljoin() { bool isemptylhs = false; IRowStream *leftInputStream = inputStream; if (helper->isLeftAlreadyLocallySorted()) { ThorDataLinkMetaInfo info; leftInput->getMetaInfo(info); if (info.totalRowsMax==0) isemptylhs = true; if (rightpartition) leftStream.set(leftInputStream); // already ungrouped else leftStream.setown(createUngroupStream(leftInputStream)); } else { leftStream.setown(iLoaderL->load(leftInputStream, abortSoon)); isemptylhs = 0 == iLoaderL->numRows(); stopLeftInput(); mergeStats(spillStats, iLoaderL); } if (isemptylhs&&((helper->getJoinFlags()&JFrightouter)==0)) { ActPrintLog("ignoring RHS as LHS empty"); rightStream.setown(createNullRowStream()); stopRightInput(); } else if (helper->isRightAlreadyLocallySorted()) { if (rightpartition) rightStream.set(createUngroupStream(rightInputStream)); else rightStream.set(rightInputStream); // already ungrouped } else { Owned<IThorRowLoader> iLoaderR = createThorRowLoader(*this, ::queryRowInterfaces(rightInput), rightCompare, stableSort_earlyAlloc, rc_mixed, SPILL_PRIORITY_JOIN); rightStream.setown(iLoaderR->load(rightInputStream, abortSoon)); stopRightInput(); mergeStats(spillStats, iLoaderR); } } bool doglobaljoin() { rightpartition = (container.getKind()==TAKjoin)&&((helper->getJoinFlags()&JFpartitionright)!=0); Linked<IThorRowInterfaces> primaryRowIf, secondaryRowIf; ICompare *primaryCompare, *secondaryCompare; ISortKeySerializer *primaryKeySerializer; Owned<IRowStream> secondaryStream, primaryStream; if (rightpartition) { primaryCompare = rightCompare; primaryKeySerializer = rightKeySerializer; secondaryCompare = leftCompare; } else { primaryCompare = leftCompare; primaryKeySerializer = leftKeySerializer; secondaryCompare = rightCompare; } primaryRowIf.set(queryRowInterfaces(primaryInput)); secondaryRowIf.set(queryRowInterfaces(secondaryInput)); primarySecondaryCompare = NULL; if (helper->getJoinFlags()&JFslidingmatch) { if (primaryKeySerializer) // JCSMORE shouldn't be generated primaryKeySerializer = NULL; primarySecondaryCompare = helper->queryCompareLeftRightLower(); primarySecondaryUpperCompare = helper->queryCompareLeftRightUpper(); if (rightpartition) { compareReverse.compare = primarySecondaryCompare; compareReverseUpper.compare = primarySecondaryUpperCompare; primarySecondaryCompare = &compareReverse; primarySecondaryUpperCompare = &compareReverseUpper; } } else { primarySecondaryUpperCompare = NULL; if (rightpartition) { if (rightKeySerializer) primarySecondaryCompare = helper->queryCompareRightKeyLeftRow(); else { compareReverse.compare = helper->queryCompareLeftRight(); primarySecondaryCompare = &compareReverse; } } else { if (leftKeySerializer) primarySecondaryCompare = helper->queryCompareLeftKeyRightRow(); else primarySecondaryCompare = helper->queryCompareLeftRight(); } } dbgassertex(primarySecondaryCompare); OwnedConstThorRow partitionRow; rowcount_t totalrows; bool usePrimaryPartition = true; if (noSortPartitionSide()) { partitionRow.setown(primaryInputStream->ungroupedNextRow()); primaryStream.setown(new cRowStreamPlus1Adaptor(primaryInputStream, partitionRow)); } else { sorter->Gather(primaryRowIf, primaryInputStream, primaryCompare, NULL, NULL, primaryKeySerializer, NULL, NULL, false, isUnstable(), abortSoon, NULL); stopPartitionInput(); if (abortSoon) { barrier->cancel(); return false; } ActPrintLog("JOIN waiting barrier.1"); if (!barrier->wait(false)) return false; ActPrintLog("JOIN barrier.1 raised"); // primaryWriter will keep as much in memory as possible. Owned<IRowWriterMultiReader> primaryWriter = createOverflowableBuffer(*this, primaryRowIf, ers_forbidden); primaryStream.setown(sorter->startMerge(totalrows)); copyRowStream(primaryStream, primaryWriter); primaryStream.setown(primaryWriter->getReader()); // NB: rhsWriter no longer needed after this point ActPrintLog("JOIN waiting barrier.2"); if (!barrier->wait(false)) return false; ActPrintLog("JOIN barrier.2 raised"); sorter->stopMerge(); if (0 == sorter->getGlobalCount()) usePrimaryPartition = false; } // NB: on secondary sort, the primaryKeySerializer is used if (usePrimaryPartition) sorter->Gather(secondaryRowIf, secondaryInputStream, secondaryCompare, primarySecondaryCompare, primarySecondaryUpperCompare, primaryKeySerializer, primaryCompare, partitionRow, noSortOtherSide(), isUnstable(), abortSoon, primaryRowIf); // primaryKeySerializer *is* correct else sorter->Gather(secondaryRowIf, secondaryInputStream, secondaryCompare, nullptr, nullptr, nullptr, nullptr, partitionRow, noSortOtherSide(), isUnstable(), abortSoon, nullptr); mergeStats(spillStats, sorter); //MORE: Stats from spilling the primaryStream?? partitionRow.clear(); stopOtherInput(); if (abortSoon) { barrier->cancel(); return false; } ActPrintLog("JOIN waiting barrier.3"); if (!barrier->wait(false)) return false; ActPrintLog("JOIN barrier.3 raised"); secondaryStream.setown(sorter->startMerge(totalrows)); if (rightpartition) { leftStream.setown(secondaryStream.getClear()); rightStream.setown(primaryStream.getClear()); } else { leftStream.setown(primaryStream.getClear()); rightStream.setown(secondaryStream.getClear()); } return true; } virtual void serializeStats(MemoryBuffer &mb) override { CSlaveActivity::serializeStats(mb); CriticalBlock b(joinHelperCrit); if (!joinhelper) { mb.append(lhsProgressCount); mb.append(rhsProgressCount); } else { mb.append(joinhelper->getLhsProgress()); mb.append(joinhelper->getRhsProgress()); } spillStats.serialize(mb); } }; ////////////////////// class CMergeJoinSlaveBaseActivity : public CThorNarySlaveActivity, public CThorSteppable { typedef CThorNarySlaveActivity PARENT; IHThorNWayMergeJoinArg *helper; Owned<IEngineRowAllocator> inputAllocator, outputAllocator; protected: CMergeJoinProcessor &processor; void afterProcessing(); void beforeProcessing(); public: IMPLEMENT_IINTERFACE_USING(PARENT); CMergeJoinSlaveBaseActivity(CGraphElementBase *_container, CMergeJoinProcessor &_processor) : CThorNarySlaveActivity(_container), CThorSteppable(this), processor(_processor) { helper = (IHThorNWayMergeJoinArg *)queryHelper(); setRequireInitData(false); inputAllocator.setown(getRowAllocator(helper->queryInputMeta())); outputAllocator.setown(getRowAllocator(helper->queryOutputMeta())); appendOutputLinked(this); } virtual void start() override { CThorNarySlaveActivity::start(); ForEachItemIn(i1, expandedInputs) { Owned<CThorSteppedInput> stepInput = new CThorSteppedInput(expandedInputs.item(i1), expandedStreams.item(i1)); processor.addInput(stepInput); } processor.beforeProcessing(inputAllocator, outputAllocator); } virtual void stop() override { processor.afterProcessing(); CThorNarySlaveActivity::stop(); dataLinkStop(); } CATCH_NEXTROW() { OwnedConstThorRow ret = processor.nextRow(); if (ret) { dataLinkIncrement(); return ret.getClear(); } return NULL; } virtual const void *nextRowGE(const void *seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra &stepExtra) { try { return nextRowGENoCatch(seek, numFields, wasCompleteMatch, stepExtra); } CATCH_NEXTROWX_CATCH; } virtual const void *nextRowGENoCatch(const void *seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra &stepExtra) { ActivityTimer t(totalCycles, timeActivities); bool matched = true; OwnedConstThorRow next = processor.nextGE(seek, numFields, matched, stepExtra); if (next) dataLinkIncrement(); return next.getClear(); } virtual bool isGrouped() const override { return false; } virtual void getMetaInfo(ThorDataLinkMetaInfo &info) override { initMetaInfo(info); info.unknownRowsOutput = true; info.canBufferInput = true; } virtual bool gatherConjunctions(ISteppedConjunctionCollector &collector) { return processor.gatherConjunctions(collector); } virtual void resetEOF() { processor.queryResetEOF(); } // steppable virtual void setInputStream(unsigned index, CThorInput &input, bool consumerOrdered) override { CThorNarySlaveActivity::setInputStream(index, input, consumerOrdered); CThorSteppable::setInputStream(index, input, consumerOrdered); } virtual IInputSteppingMeta *querySteppingMeta() { return CThorSteppable::inputStepping; } }; class CAndMergeJoinSlaveActivity : public CMergeJoinSlaveBaseActivity { protected: CAndMergeJoinProcessor andProcessor; public: CAndMergeJoinSlaveActivity(CGraphElementBase *container) : CMergeJoinSlaveBaseActivity(container, andProcessor), andProcessor(* ((IHThorNWayMergeJoinArg*)container->queryHelper())) { } }; class CAndLeftMergeJoinSlaveActivity : public CMergeJoinSlaveBaseActivity { protected: CAndLeftMergeJoinProcessor andLeftProcessor; public: CAndLeftMergeJoinSlaveActivity(CGraphElementBase *container) : CMergeJoinSlaveBaseActivity(container, andLeftProcessor), andLeftProcessor(* ((IHThorNWayMergeJoinArg*)container->queryHelper())) { } }; class CMofNMergeJoinSlaveActivity : public CMergeJoinSlaveBaseActivity { CMofNMergeJoinProcessor mofNProcessor; public: CMofNMergeJoinSlaveActivity(CGraphElementBase *container) : CMergeJoinSlaveBaseActivity(container, mofNProcessor), mofNProcessor(* ((IHThorNWayMergeJoinArg*)container->queryHelper())) { } }; class CProximityJoinSlaveActivity : public CMergeJoinSlaveBaseActivity { CProximityJoinProcessor proximityProcessor; public: CProximityJoinSlaveActivity(CGraphElementBase *container) : CMergeJoinSlaveBaseActivity(container, proximityProcessor), proximityProcessor(* ((IHThorNWayMergeJoinArg*)container->queryHelper())) { } }; CActivityBase *createLocalJoinSlave(CGraphElementBase *container) { return new JoinSlaveActivity(container, true); } CActivityBase *createJoinSlave(CGraphElementBase *container) { return new JoinSlaveActivity(container, false); } CActivityBase *createDenormalizeSlave(CGraphElementBase *container) { return new JoinSlaveActivity(container, false); } CActivityBase *createLocalDenormalizeSlave(CGraphElementBase *container) { return new JoinSlaveActivity(container, true); } CActivityBase *createNWayMergeJoinActivity(CGraphElementBase *container) { IHThorNWayMergeJoinArg *helper = (IHThorNWayMergeJoinArg *)container->queryHelper(); unsigned flags = helper->getJoinFlags(); if (flags & IHThorNWayMergeJoinArg::MJFhasrange) return new CProximityJoinSlaveActivity(container); switch (flags & IHThorNWayMergeJoinArg::MJFkindmask) { case IHThorNWayMergeJoinArg::MJFinner: return new CAndMergeJoinSlaveActivity(container); case IHThorNWayMergeJoinArg::MJFleftonly: case IHThorNWayMergeJoinArg::MJFleftouter: return new CAndLeftMergeJoinSlaveActivity(container); case IHThorNWayMergeJoinArg::MJFmofn: return new CMofNMergeJoinSlaveActivity(container); } UNIMPLEMENTED; }
33.984906
285
0.624547
miguelvazq
b47224875444aef713e05640c3e90b14dbf30588
325
hpp
C++
Engine/Code/Engine/Renderer/CubeMap.hpp
tonyatpeking/SmuSpecialTopic
b61d44e4efacb3c504847deb4d00234601bca49c
[ "MIT" ]
null
null
null
Engine/Code/Engine/Renderer/CubeMap.hpp
tonyatpeking/SmuSpecialTopic
b61d44e4efacb3c504847deb4d00234601bca49c
[ "MIT" ]
null
null
null
Engine/Code/Engine/Renderer/CubeMap.hpp
tonyatpeking/SmuSpecialTopic
b61d44e4efacb3c504847deb4d00234601bca49c
[ "MIT" ]
null
null
null
#pragma once #include "Engine/Core/Types.hpp" #include "Texture.hpp" #include "Engine/Renderer/RendererEnums.hpp" class CubeMap : public Texture { public: virtual ~CubeMap(); CubeMap( const String& imageFilePath ); CubeMap( Image* image ); virtual void MakeFromImage( Image* image ) override; private: };
18.055556
56
0.710769
tonyatpeking
b4749f6cc2b75193a33105d5d5a7e3dc1656f470
2,666
cc
C++
cc/subtle/test_util.cc
rohansingh/tink
c2338bef4663870d3855fb0236ab0092d976434d
[ "Apache-2.0" ]
1
2022-03-15T03:21:44.000Z
2022-03-15T03:21:44.000Z
cc/subtle/test_util.cc
frankfanslc/tink
fee9b771017baeaa65f13f82c8a10b3a1119d44d
[ "Apache-2.0" ]
null
null
null
cc/subtle/test_util.cc
frankfanslc/tink
fee9b771017baeaa65f13f82c8a10b3a1119d44d
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Google Inc. // // 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. // /////////////////////////////////////////////////////////////////////////////// #include "tink/subtle/test_util.h" #include <algorithm> #include <string> #include "absl/status/status.h" namespace crypto { namespace tink { namespace subtle { namespace test { const int DummyStreamSegmentEncrypter::kSegmentTagSize; const char DummyStreamSegmentEncrypter::kLastSegment; const char DummyStreamSegmentEncrypter::kNotLastSegment; util::Status WriteToStream(OutputStream* output_stream, absl::string_view contents, bool close_stream) { void* buffer; int pos = 0; int remaining = contents.length(); int available_space = 0; int available_bytes = 0; while (remaining > 0) { auto next_result = output_stream->Next(&buffer); if (!next_result.ok()) return next_result.status(); available_space = next_result.ValueOrDie(); available_bytes = std::min(available_space, remaining); memcpy(buffer, contents.data() + pos, available_bytes); remaining -= available_bytes; pos += available_bytes; } if (available_space > available_bytes) { output_stream->BackUp(available_space - available_bytes); } return close_stream ? output_stream->Close() : util::OkStatus(); } util::Status ReadFromStream(InputStream* input_stream, std::string* output) { if (input_stream == nullptr || output == nullptr) { return util::Status(absl::StatusCode::kInternal, "Illegal read from a stream"); } const void* buffer; output->clear(); while (true) { auto next_result = input_stream->Next(&buffer); if (next_result.status().code() == absl::StatusCode::kOutOfRange) { // End of stream. return util::OkStatus(); } if (!next_result.ok()) return next_result.status(); auto read_bytes = next_result.ValueOrDie(); if (read_bytes > 0) { output->append( std::string(reinterpret_cast<const char*>(buffer), read_bytes)); } } return util::OkStatus(); } } // namespace test } // namespace subtle } // namespace tink } // namespace crypto
32.512195
79
0.676669
rohansingh
b4759c2eff117a654f09c1b7cb029cf17ff7b37f
390
cpp
C++
01-Recover/LT0704.cpp
odeinjul/Solution_New
12593def5ae867e8193847184792b7fbe00aeff0
[ "MIT" ]
null
null
null
01-Recover/LT0704.cpp
odeinjul/Solution_New
12593def5ae867e8193847184792b7fbe00aeff0
[ "MIT" ]
null
null
null
01-Recover/LT0704.cpp
odeinjul/Solution_New
12593def5ae867e8193847184792b7fbe00aeff0
[ "MIT" ]
null
null
null
class Solution { public: int search(vector<int>& nums, int target) { //int help(int l, int r,int p){ int p = 0, l = 0, r = nums.size()-1; while(l<=r){ p = (l + r) >> 1; if(nums[p] == target) return p; if(target < nums[p]) r = p - 1; else l = p + 1; } return -1; } };
27.857143
48
0.376923
odeinjul
b479cff6f95fbced7b68c68cef8c8aca776d843b
1,870
hpp
C++
native/external-libraries/boost/boost/container/detail/allocation_type.hpp
l3dlp-sandbox/airkinect-2-core
49aecbd3c3fd9584434089dd2d9eef93567036e7
[ "Apache-2.0" ]
47
2015-01-01T14:37:36.000Z
2021-04-25T07:38:07.000Z
native/external-libraries/boost/boost/container/detail/allocation_type.hpp
l3dlp-sandbox/airkinect-2-core
49aecbd3c3fd9584434089dd2d9eef93567036e7
[ "Apache-2.0" ]
6
2016-01-11T05:20:05.000Z
2021-02-06T11:37:24.000Z
native/external-libraries/boost/boost/container/detail/allocation_type.hpp
l3dlp-sandbox/airkinect-2-core
49aecbd3c3fd9584434089dd2d9eef93567036e7
[ "Apache-2.0" ]
17
2015-01-05T15:10:43.000Z
2021-06-22T04:59:16.000Z
/////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2005-2011. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/container for documentation. // /////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_CONTAINERS_ALLOCATION_TYPE_HPP #define BOOST_CONTAINERS_ALLOCATION_TYPE_HPP #if (defined _MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif #include "config_begin.hpp" #include <boost/container/detail/workaround.hpp> namespace boost { namespace container { /// @cond enum allocation_type_v { // constants for allocation commands allocate_new_v = 0x01, expand_fwd_v = 0x02, expand_bwd_v = 0x04, // expand_both = expand_fwd | expand_bwd, // expand_or_new = allocate_new | expand_both, shrink_in_place_v = 0x08, nothrow_allocation_v = 0x10, zero_memory_v = 0x20, try_shrink_in_place_v = 0x40 }; typedef int allocation_type; /// @endcond static const allocation_type allocate_new = (allocation_type)allocate_new_v; static const allocation_type expand_fwd = (allocation_type)expand_fwd_v; static const allocation_type expand_bwd = (allocation_type)expand_bwd_v; static const allocation_type shrink_in_place = (allocation_type)shrink_in_place_v; static const allocation_type try_shrink_in_place= (allocation_type)try_shrink_in_place_v; static const allocation_type nothrow_allocation = (allocation_type)nothrow_allocation_v; static const allocation_type zero_memory = (allocation_type)zero_memory_v; } //namespace container { } //namespace boost { #include <boost/container/detail/config_end.hpp> #endif //BOOST_CONTAINERS_ALLOCATION_TYPE_HPP
34
89
0.701604
l3dlp-sandbox
b47a6639744fa202eb6d99b66be0d4ec6d411571
2,560
cc
C++
zircon/system/dev/board/nelson/nelson-light.cc
sunshinewithmoonlight/fuchsia-2003
02b23026dc7fecbad063210d5d45fa1b17feeb8b
[ "BSD-3-Clause" ]
null
null
null
zircon/system/dev/board/nelson/nelson-light.cc
sunshinewithmoonlight/fuchsia-2003
02b23026dc7fecbad063210d5d45fa1b17feeb8b
[ "BSD-3-Clause" ]
null
null
null
zircon/system/dev/board/nelson/nelson-light.cc
sunshinewithmoonlight/fuchsia-2003
02b23026dc7fecbad063210d5d45fa1b17feeb8b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Fuchsia 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 <ddk/binding.h> #include <ddk/debug.h> #include <ddk/device.h> #include <ddk/metadata.h> #include <ddk/platform-defs.h> #include <ddk/protocol/platform/bus.h> #include <ddktl/metadata/light-sensor.h> #include <soc/aml-s905d2/s905d2-gpio.h> #include "nelson-gpios.h" #include "nelson.h" namespace nelson { // Composite binding rules for focaltech touch driver. static const zx_bind_inst_t root_match[] = { BI_MATCH(), }; const zx_bind_inst_t i2c_match[] = { BI_ABORT_IF(NE, BIND_PROTOCOL, ZX_PROTOCOL_I2C), BI_ABORT_IF(NE, BIND_I2C_BUS_ID, NELSON_I2C_A0_0), BI_MATCH_IF(EQ, BIND_I2C_ADDRESS, I2C_AMBIENTLIGHT_ADDR), }; static const zx_bind_inst_t gpio_match[] = { BI_ABORT_IF(NE, BIND_PROTOCOL, ZX_PROTOCOL_GPIO), BI_MATCH_IF(EQ, BIND_GPIO_PIN, GPIO_LIGHT_INTERRUPT), }; static const device_component_part_t i2c_component[] = { {countof(root_match), root_match}, {countof(i2c_match), i2c_match}, }; static const device_component_part_t gpio_component[] = { {countof(root_match), root_match}, {countof(gpio_match), gpio_match}, }; static const device_component_t components[] = { {countof(i2c_component), i2c_component}, {countof(gpio_component), gpio_component}, }; zx_status_t Nelson::LightInit() { metadata::LightSensorParams params = {}; // TODO(kpt): Insert the right parameters here. params.lux_constant_coefficient = 0; params.lux_linear_coefficient = .29f; params.integration_time_ms = 615; device_metadata_t metadata[] = { { .type = DEVICE_METADATA_PRIVATE, .data = &params, .length = sizeof(params), }, }; constexpr zx_device_prop_t props[] = { {BIND_PLATFORM_DEV_VID, 0, PDEV_VID_AMS}, {BIND_PLATFORM_DEV_PID, 0, PDEV_PID_AMS_TCS3400}, {BIND_PLATFORM_DEV_DID, 0, PDEV_DID_AMS_LIGHT}, }; const composite_device_desc_t comp_desc = { .props = props, .props_count = countof(props), .components = components, .components_count = countof(components), .coresident_device_index = UINT32_MAX, .metadata_list = metadata, .metadata_count = countof(metadata), }; zx_status_t status = DdkAddComposite("tcs3400-light", &comp_desc); if (status != ZX_OK) { zxlogf(ERROR, "%s(tcs-3400): DdkAddComposite failed: %d\n", __func__, status); return status; } return ZX_OK; } } // namespace nelson
28.764045
82
0.707422
sunshinewithmoonlight
b47ec73dfcfed4b4f66bcdc0f0b6e34d7b59d8c9
5,692
cpp
C++
RayEngine/Source/DX11/DX11RenderTargetView.cpp
Mumsfilibaba/RayEngine
68496966c1d7b91bc8fbdd305226ece9b9f596b2
[ "Apache-2.0" ]
null
null
null
RayEngine/Source/DX11/DX11RenderTargetView.cpp
Mumsfilibaba/RayEngine
68496966c1d7b91bc8fbdd305226ece9b9f596b2
[ "Apache-2.0" ]
null
null
null
RayEngine/Source/DX11/DX11RenderTargetView.cpp
Mumsfilibaba/RayEngine
68496966c1d7b91bc8fbdd305226ece9b9f596b2
[ "Apache-2.0" ]
null
null
null
/*//////////////////////////////////////////////////////////// Copyright 2018 Alexander Dahlin 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 THIS SOFTWARE IS PROVIDED "AS IS". MEANING NO WARRANTY OR SUPPORT IS PROVIDED OF ANY KIND. In event of any damages, direct or indirect that can be traced back to the use of this software, shall no contributor be held liable. This includes computer failure and or malfunction of any kind. ////////////////////////////////////////////////////////////*/ #include <RayEngine.h> #if defined(RE_PLATFORM_WINDOWS) #include <DX11/DX11Device.h> #include <DX11/DX11Buffer.h> #include <DX11/DX11Texture.h> #include <DX11/DX11RenderTargetView.h> namespace RayEngine { namespace Graphics { ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DX11RenderTargetView::DX11RenderTargetView(IDevice* pDevice, const RenderTargetViewDesc* pDesc) : m_Device(nullptr), m_View(nullptr), m_References(0) { AddRef(); m_Device = reinterpret_cast<DX11Device*>(pDevice); Create(pDesc); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DX11RenderTargetView::~DX11RenderTargetView() { D3DRelease_S(m_View); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DX11RenderTargetView::GetDesc(RenderTargetViewDesc* pDesc) const { *pDesc = m_Desc; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CounterType DX11RenderTargetView::AddRef() { return ++m_References; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CounterType DX11RenderTargetView::Release() { CounterType counter = --m_References; if (counter < 1) delete this; return counter; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DX11RenderTargetView::Create(const RenderTargetViewDesc* pDesc) { D3D11_RENDER_TARGET_VIEW_DESC desc = {}; desc.Format = ReToDXFormat(pDesc->Format); ID3D11Resource* pD3D11Resource = nullptr; if (pDesc->ViewDimension == VIEWDIMENSION_BUFFER) { desc.ViewDimension = D3D11_RTV_DIMENSION_BUFFER; desc.Buffer.FirstElement = pDesc->Buffer.StartElement; desc.Buffer.NumElements = pDesc->Buffer.ElementCount; pD3D11Resource = reinterpret_cast<const DX11Buffer*>(pDesc->pResource)->GetD3D11Buffer(); } else if (pDesc->ViewDimension == VIEWDIMENSION_TEXTURE1D) { desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE1D; desc.Texture1D.MipSlice = pDesc->Texture1D.MipSlice; pD3D11Resource = reinterpret_cast<const DX11Texture*>(pDesc->pResource)->GetD3D11Texture1D(); } else if (pDesc->ViewDimension == VIEWDIMENSION_TEXTURE1D_ARRAY) { desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE1DARRAY; desc.Texture1DArray.MipSlice = pDesc->Texture1DArray.MipSlice; desc.Texture1DArray.ArraySize = pDesc->Texture1DArray.ArraySize; desc.Texture1DArray.FirstArraySlice = pDesc->Texture1DArray.FirstArraySlice; pD3D11Resource = reinterpret_cast<const DX11Texture*>(pDesc->pResource)->GetD3D11Texture1D(); } else if (pDesc->ViewDimension == VIEWDIMENSION_TEXTURE2D) { desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; desc.Texture2D.MipSlice = pDesc->Texture2D.MipSlice; pD3D11Resource = reinterpret_cast<const DX11Texture*>(pDesc->pResource)->GetD3D11Texture2D(); } else if (pDesc->ViewDimension == VIEWDIMENSION_TEXTURE2DMS) { desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMS; pD3D11Resource = reinterpret_cast<const DX11Texture*>(pDesc->pResource)->GetD3D11Texture2D(); } else if (pDesc->ViewDimension == VIEWDIMENSION_TEXTURE2D_ARRAY) { desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY; desc.Texture2DArray.MipSlice = pDesc->Texture2DArray.MipSlice; desc.Texture2DArray.ArraySize = pDesc->Texture2DArray.ArraySize; desc.Texture2DArray.FirstArraySlice = pDesc->Texture2DArray.FirstArraySlice; pD3D11Resource = reinterpret_cast<const DX11Texture*>(pDesc->pResource)->GetD3D11Texture2D(); } else if (pDesc->ViewDimension == VIEWDIMENSION_TEXTURE2DMS_ARRAY) { desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY; desc.Texture2DMSArray.ArraySize = pDesc->Texture2DMSArray.ArraySize; desc.Texture2DMSArray.FirstArraySlice = pDesc->Texture2DMSArray.FirstArraySlice; pD3D11Resource = reinterpret_cast<const DX11Texture*>(pDesc->pResource)->GetD3D11Texture2D(); } else if (pDesc->ViewDimension == VIEWDIMENSION_TEXTURE3D) { desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE3D; desc.Texture3D.MipSlice = pDesc->Texture3D.MipSlice; desc.Texture3D.FirstWSlice = pDesc->Texture3D.FirstDepthSlice; desc.Texture3D.WSize = pDesc->Texture3D.DepthSliceCount; pD3D11Resource = reinterpret_cast<const DX11Texture*>(pDesc->pResource)->GetD3D11Texture3D(); } ID3D11Device* pD3D11Device = m_Device->GetD3D11Device(); HRESULT hr = pD3D11Device->CreateRenderTargetView(pD3D11Resource, &desc, &m_View); if (FAILED(hr)) { LOG_ERROR("D3D11: Could not create RenderTargetView. " + DXErrorString(hr)); } else { m_Desc = *pDesc; } } } } #endif
34.49697
124
0.635453
Mumsfilibaba
b47f637825b873d09d6e49e2efdc7ec8a045feb8
895
cpp
C++
149.็›ด็บฟไธŠๆœ€ๅคš็š„็‚นๆ•ฐ/maxPoints.cpp
YichengZhong/Top-Interview-Questions
124828d321f482a0eaa30012b3706267487bfd24
[ "MIT" ]
1
2019-10-21T14:40:39.000Z
2019-10-21T14:40:39.000Z
149.็›ด็บฟไธŠๆœ€ๅคš็š„็‚นๆ•ฐ/maxPoints.cpp
YichengZhong/Top-Interview-Questions
124828d321f482a0eaa30012b3706267487bfd24
[ "MIT" ]
null
null
null
149.็›ด็บฟไธŠๆœ€ๅคš็š„็‚นๆ•ฐ/maxPoints.cpp
YichengZhong/Top-Interview-Questions
124828d321f482a0eaa30012b3706267487bfd24
[ "MIT" ]
1
2020-11-04T07:33:34.000Z
2020-11-04T07:33:34.000Z
class Solution { public: int maxPoints(vector<vector<int>>& points) { int len = points.size(); // ็‚น็š„ๆ•ฐ้‡ไธๅคŸ if(len < 3) { return len; } int maxNum = 2; // ้ๅކๆฏไธคไธช็‚น for(int i = 0; i < len; i ++) { unordered_map<double, int> count; for(int j = 0; j < len; j ++) { if(i != j) { long long dx = points[i][0] - points[j][0]; long long dy = points[i][1] - points[j][1]; double gradient = dy * 1.0 / dx; if(count.count(gradient)) { count[gradient] ++; } else { count[gradient] = 2; } maxNum = max(maxNum, count[gradient]); } } } return maxNum; } };
29.833333
63
0.363128
YichengZhong
b47fb1a6bbe5ba7c273e2cd6eb64d31b13731e28
867
hpp
C++
ltl2fsm/base/exception/Invalid_Ltl_Syntax.hpp
arafato/ltl2fsm
58d96c40fe0890c2bcc90593469668e6369c0f1b
[ "MIT" ]
2
2016-11-23T14:31:55.000Z
2018-05-10T01:11:54.000Z
ltl2fsm/base/exception/Invalid_Ltl_Syntax.hpp
arafato/ltl2fsm
58d96c40fe0890c2bcc90593469668e6369c0f1b
[ "MIT" ]
null
null
null
ltl2fsm/base/exception/Invalid_Ltl_Syntax.hpp
arafato/ltl2fsm
58d96c40fe0890c2bcc90593469668e6369c0f1b
[ "MIT" ]
null
null
null
/** * @file ltl2fsm/base/exception/Invalid_Ltl_Syntax.hpp * * $Id$ * * @author Oliver Arafat * * @brief @ref * * @note DOCUMENTED * * @test * * @todo */ #ifndef LTL2FSM__BASE__EXCEPTION__INVALID_LTL_SYNTAX__HPP #define LTL2FSM__BASE__EXCEPTION__INVALID_LTL_SYNTAX__HPP #include <ltl2fsm/base/exception/Exception.hpp> //#include <string> LTL2FSM__BEGIN__NAMESPACE__LTL2FSM; class Invalid_Ltl_Syntax : public Exception { //////////////////////////////////////////////////////////////////////////////// /** * @name Construction / Destruction * @{ */ public: Invalid_Ltl_Syntax(Source_Location const & source_location, ::std::string const & what); virtual ~Invalid_Ltl_Syntax() throw(); // @} public: virtual char const * class_name() const; }; LTL2FSM__END__NAMESPACE__LTL2FSM; #endif
16.358491
84
0.619377
arafato
b48107a4215c8871bc333d313b3b53da709e85bf
582
cpp
C++
src/nietacka/ReadBuffer.cpp
PiotrJander/sik-achtung-die-kurve
a44af3b20e5baccd18d388a0a29f412a2c5e5902
[ "MIT" ]
null
null
null
src/nietacka/ReadBuffer.cpp
PiotrJander/sik-achtung-die-kurve
a44af3b20e5baccd18d388a0a29f412a2c5e5902
[ "MIT" ]
null
null
null
src/nietacka/ReadBuffer.cpp
PiotrJander/sik-achtung-die-kurve
a44af3b20e5baccd18d388a0a29f412a2c5e5902
[ "MIT" ]
null
null
null
// // Created by Piotr Jander on 29/08/2017. // #include "ReadBuffer.h" ReadBuffer::ReadBuffer(int length) : vector(length) {} ReadBuffer::ReadBuffer(const DynamicBuffer &dynamic) : vector(dynamic.getBuffer()) {} std::string ReadBuffer::readString(int length) { length = std::min(length, static_cast<const int &>(vector.size() - readLocation)); std::string ret(&vector[readLocation], 0, static_cast<unsigned long>(length)); readLocation += ret.size() + 1; return ret; } ReadBufferException::ReadBufferException(const std::string &desc) : runtime_error(desc) {}
25.304348
87
0.713058
PiotrJander
b481e6cdc7f6bb050bfff4acd0e29f0b70de2c47
11,851
cpp
C++
Userland/Services/SystemServer/Service.cpp
johanventer/serenity
cb8e4be3b5d9ce2225f4347efdaaf08423405b65
[ "BSD-2-Clause" ]
null
null
null
Userland/Services/SystemServer/Service.cpp
johanventer/serenity
cb8e4be3b5d9ce2225f4347efdaaf08423405b65
[ "BSD-2-Clause" ]
null
null
null
Userland/Services/SystemServer/Service.cpp
johanventer/serenity
cb8e4be3b5d9ce2225f4347efdaaf08423405b65
[ "BSD-2-Clause" ]
1
2021-06-10T00:18:29.000Z
2021-06-10T00:18:29.000Z
/* * Copyright (c) 2019-2020, Sergey Bugaev <bugaevc@serenityos.org> * 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 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. */ #include "Service.h" #include <AK/HashMap.h> #include <AK/JsonArray.h> #include <AK/JsonObject.h> #include <LibCore/ConfigFile.h> #include <LibCore/File.h> #include <LibCore/Socket.h> #include <grp.h> #include <libgen.h> #include <pwd.h> #include <sched.h> #include <stdio.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <unistd.h> static HashMap<pid_t, Service*> s_service_map; Service* Service::find_by_pid(pid_t pid) { auto it = s_service_map.find(pid); if (it == s_service_map.end()) return nullptr; return (*it).value; } void Service::setup_socket() { ASSERT(!m_socket_path.is_null()); ASSERT(m_socket_fd == -1); auto ok = Core::File::ensure_parent_directories(m_socket_path); ASSERT(ok); // Note: we use SOCK_CLOEXEC here to make sure we don't leak every socket to // all the clients. We'll make the one we do need to pass down !CLOEXEC later // after forking off the process. m_socket_fd = socket(AF_LOCAL, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); if (m_socket_fd < 0) { perror("socket"); ASSERT_NOT_REACHED(); } if (m_account.has_value()) { auto& account = m_account.value(); if (fchown(m_socket_fd, account.uid(), account.gid()) < 0) { perror("fchown"); ASSERT_NOT_REACHED(); } } if (fchmod(m_socket_fd, m_socket_permissions) < 0) { perror("fchmod"); ASSERT_NOT_REACHED(); } auto socket_address = Core::SocketAddress::local(m_socket_path); auto un_optional = socket_address.to_sockaddr_un(); if (!un_optional.has_value()) { dbg() << "Socket name " << m_socket_path << " is too long. BUG! This should have failed earlier!"; ASSERT_NOT_REACHED(); } auto un = un_optional.value(); int rc = bind(m_socket_fd, (const sockaddr*)&un, sizeof(un)); if (rc < 0) { perror("bind"); ASSERT_NOT_REACHED(); } rc = listen(m_socket_fd, 16); if (rc < 0) { perror("listen"); ASSERT_NOT_REACHED(); } } void Service::setup_notifier() { ASSERT(m_lazy); ASSERT(m_socket_fd >= 0); ASSERT(!m_socket_notifier); m_socket_notifier = Core::Notifier::construct(m_socket_fd, Core::Notifier::Event::Read, this); m_socket_notifier->on_ready_to_read = [this] { handle_socket_connection(); }; } void Service::handle_socket_connection() { #ifdef SERVICE_DEBUG dbg() << "Ready to read on behalf of " << name(); #endif if (m_accept_socket_connections) { int accepted_fd = accept(m_socket_fd, nullptr, nullptr); if (accepted_fd < 0) { perror("accept"); return; } spawn(accepted_fd); close(accepted_fd); } else { remove_child(*m_socket_notifier); m_socket_notifier = nullptr; spawn(m_socket_fd); } } void Service::activate() { ASSERT(m_pid < 0); if (m_lazy) setup_notifier(); else spawn(m_socket_fd); } void Service::spawn(int socket_fd) { #ifdef SERVICE_DEBUG dbg() << "Spawning " << name(); #endif m_run_timer.start(); pid_t pid = fork(); if (pid < 0) { perror("fork"); dbg() << "Failed to spawn " << name() << ". Sucks, dude :("; } else if (pid == 0) { // We are the child. if (!m_working_directory.is_null()) { if (chdir(m_working_directory.characters()) < 0) { perror("chdir"); ASSERT_NOT_REACHED(); } } struct sched_param p; p.sched_priority = m_priority; int rc = sched_setparam(0, &p); if (rc < 0) { perror("sched_setparam"); ASSERT_NOT_REACHED(); } if (!m_stdio_file_path.is_null()) { close(STDIN_FILENO); int fd = open(m_stdio_file_path.characters(), O_RDWR, 0); ASSERT(fd <= 0); if (fd < 0) { perror("open"); ASSERT_NOT_REACHED(); } dup2(STDIN_FILENO, STDOUT_FILENO); dup2(STDIN_FILENO, STDERR_FILENO); if (isatty(STDIN_FILENO)) { ioctl(STDIN_FILENO, TIOCSCTTY); } } else { if (isatty(STDIN_FILENO)) { ioctl(STDIN_FILENO, TIOCNOTTY); } close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); int fd = open("/dev/null", O_RDWR); ASSERT(fd == STDIN_FILENO); dup2(STDIN_FILENO, STDOUT_FILENO); dup2(STDIN_FILENO, STDERR_FILENO); } if (socket_fd >= 0) { ASSERT(!m_socket_path.is_null()); ASSERT(socket_fd > 3); dup2(socket_fd, 3); // The new descriptor is !CLOEXEC here. setenv("SOCKET_TAKEOVER", "1", true); } if (m_account.has_value()) { auto& account = m_account.value(); if (setgid(account.gid()) < 0 || setgroups(account.extra_gids().size(), account.extra_gids().data()) < 0 || setuid(account.uid()) < 0) { dbgln("Failed to drop privileges (GID={}, UID={})\n", account.gid(), account.uid()); exit(1); } setenv("HOME", account.home_directory().characters(), true); } for (String& env : m_environment) putenv(const_cast<char*>(env.characters())); char* argv[m_extra_arguments.size() + 2]; argv[0] = const_cast<char*>(m_executable_path.characters()); for (size_t i = 0; i < m_extra_arguments.size(); i++) argv[i + 1] = const_cast<char*>(m_extra_arguments[i].characters()); argv[m_extra_arguments.size() + 1] = nullptr; rc = execv(argv[0], argv); perror("exec"); ASSERT_NOT_REACHED(); } else if (!m_multi_instance) { // We are the parent. m_pid = pid; s_service_map.set(pid, this); } } void Service::did_exit(int exit_code) { ASSERT(m_pid > 0); ASSERT(!m_multi_instance); dbg() << "Service " << name() << " has exited with exit code " << exit_code; s_service_map.remove(m_pid); m_pid = -1; if (!m_keep_alive) return; int run_time_in_msec = m_run_timer.elapsed(); bool exited_successfully = exit_code == 0; if (!exited_successfully && run_time_in_msec < 1000) { switch (m_restart_attempts) { case 0: dbgln("Trying again"); break; case 1: dbgln("Third time's a charm?"); break; default: dbg() << "Giving up on " << name() << ". Good luck!"; return; } m_restart_attempts++; } activate(); } Service::Service(const Core::ConfigFile& config, const StringView& name) : Core::Object(nullptr) { ASSERT(config.has_group(name)); set_name(name); m_executable_path = config.read_entry(name, "Executable", String::formatted("/bin/{}", this->name())); m_extra_arguments = config.read_entry(name, "Arguments", "").split(' '); m_stdio_file_path = config.read_entry(name, "StdIO"); String prio = config.read_entry(name, "Priority"); if (prio == "low") m_priority = 10; else if (prio == "normal" || prio.is_null()) m_priority = 30; else if (prio == "high") m_priority = 50; else ASSERT_NOT_REACHED(); m_keep_alive = config.read_bool_entry(name, "KeepAlive"); m_lazy = config.read_bool_entry(name, "Lazy"); m_user = config.read_entry(name, "User"); if (!m_user.is_null()) { auto result = Core::Account::from_name(m_user.characters()); if (result.is_error()) warnln("Failed to resolve user {}: {}", m_user, result.error()); else m_account = result.value(); } m_working_directory = config.read_entry(name, "WorkingDirectory"); m_environment = config.read_entry(name, "Environment").split(' '); m_boot_modes = config.read_entry(name, "BootModes", "graphical").split(','); m_multi_instance = config.read_bool_entry(name, "MultiInstance"); m_accept_socket_connections = config.read_bool_entry(name, "AcceptSocketConnections"); m_socket_path = config.read_entry(name, "Socket"); // Lazy requires Socket. ASSERT(!m_lazy || !m_socket_path.is_null()); // AcceptSocketConnections always requires Socket, Lazy, and MultiInstance. ASSERT(!m_accept_socket_connections || (!m_socket_path.is_null() && m_lazy && m_multi_instance)); // MultiInstance doesn't work with KeepAlive. ASSERT(!m_multi_instance || !m_keep_alive); // Socket path (plus NUL) must fit into the structs sent to the Kernel. ASSERT(m_socket_path.length() < UNIX_PATH_MAX); if (!m_socket_path.is_null() && is_enabled()) { auto socket_permissions_string = config.read_entry(name, "SocketPermissions", "0600"); m_socket_permissions = strtol(socket_permissions_string.characters(), nullptr, 8) & 04777; setup_socket(); } } void Service::save_to(JsonObject& json) { Core::Object::save_to(json); json.set("executable_path", m_executable_path); // FIXME: This crashes Inspector. /* JsonArray extra_args; for (String& arg : m_extra_arguments) extra_args.append(arg); json.set("extra_arguments", move(extra_args)); JsonArray boot_modes; for (String& mode : m_boot_modes) boot_modes.append(mode); json.set("boot_modes", boot_modes); JsonArray environment; for (String& env : m_environment) boot_modes.append(env); json.set("environment", environment); */ json.set("stdio_file_path", m_stdio_file_path); json.set("priority", m_priority); json.set("keep_alive", m_keep_alive); json.set("socket_path", m_socket_path); json.set("socket_permissions", m_socket_permissions); json.set("lazy", m_lazy); json.set("user", m_user); json.set("multi_instance", m_multi_instance); json.set("accept_socket_connections", m_accept_socket_connections); if (m_pid > 0) json.set("pid", m_pid); else json.set("pid", nullptr); json.set("restart_attempts", m_restart_attempts); json.set("working_directory", m_working_directory); } bool Service::is_enabled() const { extern String g_boot_mode; return m_boot_modes.contains_slow(g_boot_mode); }
31.435013
148
0.620876
johanventer
b48518c39c6bd392692e82d604dd85c816e73673
10,226
cpp
C++
src/net/tcp/tcp.cpp
pidEins/IncludeOS
b92339164a2ba61f03ca9a940b1e9a0907c08bea
[ "Apache-2.0" ]
2
2017-04-28T17:29:25.000Z
2017-05-03T07:36:22.000Z
src/net/tcp/tcp.cpp
lefticus/IncludeOS
b92339164a2ba61f03ca9a940b1e9a0907c08bea
[ "Apache-2.0" ]
null
null
null
src/net/tcp/tcp.cpp
lefticus/IncludeOS
b92339164a2ba61f03ca9a940b1e9a0907c08bea
[ "Apache-2.0" ]
2
2017-05-01T18:16:28.000Z
2019-11-15T19:48:01.000Z
// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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. #define DEBUG #define DEBUG2 #include <net/tcp/tcp.hpp> #include <net/tcp/packet.hpp> #include <statman> using namespace std; using namespace net; using namespace net::tcp; TCP::TCP(IPStack& inet) : bytes_rx_{Statman::get().create(Stat::UINT64, inet.ifname() + ".tcp.bytes_rx").get_uint64()}, bytes_tx_{Statman::get().create(Stat::UINT64, inet.ifname() + ".tcp.bytes_tx").get_uint64()}, packets_rx_{Statman::get().create(Stat::UINT64, inet.ifname() + ".tcp.packets_rx").get_uint64()}, packets_tx_{Statman::get().create(Stat::UINT64, inet.ifname() + ".tcp.packets_tx").get_uint64()}, incoming_connections_{Statman::get().create(Stat::UINT64, inet.ifname() + ".tcp.incoming_connections").get_uint64()}, outgoing_connections_{Statman::get().create(Stat::UINT64, inet.ifname() + ".tcp.outgoing_connections").get_uint64()}, connection_attempts_{Statman::get().create(Stat::UINT64, inet.ifname() + ".tcp.connection_attempts").get_uint64()}, packets_dropped_{Statman::get().create(Stat::UINT32, inet.ifname() + ".tcp.packets_dropped").get_uint32()}, inet_(inet), listeners_(), connections_(), writeq(), MAX_SEG_LIFETIME(30s) { inet.on_transmit_queue_available(transmit_avail_delg::from<TCP,&TCP::process_writeq>(this)); } /* Note: There is different approaches to how to handle listeners & connections. Need to discuss and decide for the best one. Best solution(?): Preallocate a pool with listening connections. When threshold is reach, remove/add new ones, similar to TCP window. Current solution: Simple. */ Listener& TCP::bind(port_t port) { // Already a listening socket. Listeners::const_iterator it = listeners_.find(port); if(it != listeners_.cend()) { throw TCPException{"Port is already taken."}; } auto& listener = listeners_.emplace(port, std::make_unique<tcp::Listener>(*this, port) ).first->second; debug("<TCP::bind> Bound to port %i \n", port); return *listener; /*auto& listener = (listeners_.emplace(std::piecewise_construct, std::forward_as_tuple(port), std::forward_as_tuple(*this, port)) ).first->second; debug("<TCP::bind> Bound to port %i \n", port); return listener;*/ } /* Active open a new connection to the given remote. @WARNING: Callback is added when returned (TCP::connect(...).onSuccess(...)), and open() is called before callback is added. */ Connection_ptr TCP::connect(Socket remote) { auto port = next_free_port(); auto connection = add_connection(port, remote); connection->open(true); return connection; } /* Active open a new connection to the given remote. */ void TCP::connect(Socket remote, Connection::ConnectCallback callback) { auto port = next_free_port(); auto connection = add_connection(port, remote); connection->on_connect(callback).open(true); } seq_t TCP::generate_iss() { // Do something to get a iss. return rand(); } /* TODO: Check if there is any ports free. */ port_t TCP::next_free_port() { current_ephemeral_ = (current_ephemeral_ == 0) ? current_ephemeral_ + 1025 : current_ephemeral_ + 1; // Avoid giving a port that is bound to a service. while(listeners_.find(current_ephemeral_) != listeners_.end()) current_ephemeral_++; return current_ephemeral_; } /* Expensive look up if port is in use. */ bool TCP::port_in_use(const port_t port) const { if(listeners_.find(port) != listeners_.end()) return true; for(auto conn : connections_) { if(conn.first.first == port) return true; } return false; } uint16_t TCP::checksum(tcp::Packet_ptr packet) { short tcp_length = packet->tcp_length(); Pseudo_header pseudo_hdr; pseudo_hdr.saddr.whole = packet->src().whole; pseudo_hdr.daddr.whole = packet->dst().whole; pseudo_hdr.zero = 0; pseudo_hdr.proto = IP4::IP4_TCP; pseudo_hdr.tcp_length = htons(tcp_length); union Sum{ uint32_t whole; uint16_t part[2]; } sum; sum.whole = 0; // Compute sum of pseudo header for (uint16_t* it = (uint16_t*)&pseudo_hdr; it < (uint16_t*)&pseudo_hdr + sizeof(pseudo_hdr)/2; it++) sum.whole += *it; // Compute sum of header and data Header* tcp_hdr = &packet->tcp_header(); for (uint16_t* it = (uint16_t*)tcp_hdr; it < (uint16_t*)tcp_hdr + tcp_length/2; it++) sum.whole+= *it; // The odd-numbered case bool odd = (tcp_length & 1); sum.whole += (odd) ? ((uint8_t*)tcp_hdr)[tcp_length - 1] << 16 : 0; sum.whole = (uint32_t)sum.part[0] + sum.part[1]; sum.part[0] += sum.part[1]; return ~sum.whole; } void TCP::bottom(net::Packet_ptr packet_ptr) { // Stat increment packets received packets_rx_++; // Translate into a TCP::Packet. This will be used inside the TCP-scope. auto packet = std::static_pointer_cast<net::tcp::Packet>(packet_ptr); debug("<TCP::bottom> TCP Packet received - Source: %s, Destination: %s \n", packet->source().to_string().c_str(), packet->destination().to_string().c_str()); // Stat increment bytes received bytes_rx_ += packet->tcp_data_length(); // Validate checksum if (UNLIKELY(checksum(packet) != 0)) { debug("<TCP::bottom> TCP Packet Checksum != 0 \n"); drop(packet); return; } Connection::Tuple tuple { packet->dst_port(), packet->source() }; // Try to find the receiver auto conn_it = connections_.find(tuple); // Connection found if (conn_it != connections_.end()) { debug("<TCP::bottom> Connection found: %s \n", conn_it->second->to_string().c_str()); conn_it->second->segment_arrived(packet); return; } // No open connection found, find listener on port Listeners::iterator listener_it = listeners_.find(packet->dst_port()); debug("<TCP::bottom> No connection found - looking for listener..\n"); // Listener found => Create listening Connection if (LIKELY(listener_it != listeners_.end())) { auto& listener = listener_it->second; debug("<TCP::bottom> Listener found: %s\n", listener->to_string().c_str()); listener->segment_arrived(packet); debug2("<TCP::bottom> Listener done with packet\n"); return; } drop(packet); } void TCP::process_writeq(size_t packets) { debug("<TCP::process_writeq> size=%u p=%u\n", writeq.size(), packets); // foreach connection who wants to write while(packets and !writeq.empty()) { debug("<TCP::process_writeq> Processing writeq size=%u, p=%u\n", writeq.size(), packets); auto conn = writeq.front(); writeq.pop_back(); conn->offer(packets); conn->set_queued(false); } } size_t TCP::send(Connection_ptr conn, const char* buffer, size_t n) { size_t written{0}; auto packets = inet_.transmit_queue_available(); debug2("<TCP::send> Send request for %u bytes\n", n); if(packets > 0) { written += conn->send(buffer, n, packets); } // if connection still can send (means there wasn't enough packets) // only requeue if not already queued if(!packets and conn->can_send() and !conn->is_queued()) { debug("<TCP::send> %s queued\n", conn->to_string().c_str()); writeq.push_back(conn); conn->set_queued(true); } return written; } /* Show all connections for TCP as a string. Format: [Protocol][Recv][Send][Local][Remote][State] TODO: Make sure Recv, Send, In, Out is correct and add them to output. Also, alignment? */ string TCP::to_string() const { // Write all connections in a cute list. stringstream ss; ss << "LISTENERS:\n" << "Port\t" << "Queued\n"; for(auto& listen_it : listeners_) { auto& l = listen_it.second; ss << l->port() << "\t" << l->syn_queue_size() << "\n"; } ss << "\nCONNECTIONS:\n" << "Proto\tRecv\tSend\tIn\tOut\tLocal\t\t\tRemote\t\t\tState\n"; for(auto& con_it : connections_) { auto& c = *(con_it.second); ss << "tcp4\t" << " " << "\t" << " " << "\t" << " " << "\t" << " " << "\t" << c.local().to_string() << "\t\t" << c.remote().to_string() << "\t\t" << c.state().to_string() << "\n"; } return ss.str(); } Connection_ptr TCP::add_connection(port_t local_port, Socket remote) { // Stat increment number of outgoing connections outgoing_connections_++; auto& conn = (connections_.emplace( Connection::Tuple{ local_port, remote }, std::make_shared<Connection>(*this, local_port, remote)) ).first->second; conn->_on_cleanup(CleanupCallback::from<TCP, &TCP::close_connection>(this)); return conn; } void TCP::add_connection(tcp::Connection_ptr conn) { // Stat increment number of incoming connections incoming_connections_++; debug("<TCP::add_connection> Connection added %s \n", conn->to_string().c_str()); conn->_on_cleanup(CleanupCallback::from<TCP, &TCP::close_connection>(this)); connections_.emplace(conn->tuple(), conn); } void TCP::close_connection(tcp::Connection_ptr conn) { debug("<TCP::close_connection> Closing connection: %s \n", conn->to_string().c_str()); connections_.erase(conn->tuple()); } void TCP::drop(tcp::Packet_ptr) { // Stat increment packets dropped packets_dropped_++; debug("<TCP::drop> Packet dropped\n"); //debug("<TCP::drop> Packet was dropped - no recipient: %s \n", packet->destination().to_string().c_str()); } void TCP::transmit(tcp::Packet_ptr packet) { // Generate checksum. packet->set_checksum(TCP::checksum(packet)); //if(packet->has_data()) // printf("<TCP::transmit> S: %u\n", packet->seq()); // Stat increment bytes transmitted and packets transmitted bytes_tx_ += packet->tcp_data_length(); packets_tx_++; _network_layer_out(packet); }
31.659443
119
0.680618
pidEins
b486ea92ff2f4067a50a501654a2aa68ef489993
414
hpp
C++
LPI/aula18/include/ClientePF.hpp
dayvisonmsilva/LPI
0e3186e03b0ed438795f513dd968911c6845f5e4
[ "Apache-2.0" ]
null
null
null
LPI/aula18/include/ClientePF.hpp
dayvisonmsilva/LPI
0e3186e03b0ed438795f513dd968911c6845f5e4
[ "Apache-2.0" ]
null
null
null
LPI/aula18/include/ClientePF.hpp
dayvisonmsilva/LPI
0e3186e03b0ed438795f513dd968911c6845f5e4
[ "Apache-2.0" ]
null
null
null
#ifndef CLIENTEPF_HPP #define CLIENTEPF_HPP #include <string> #include "Cliente.hpp" using namespace std; class ClientePF : public Cliente { private: string cpf; public: static int quantidadeClientes; ClientePF(string nome, string cpf); ClientePF(); ~ClientePF(); void setCpf(string cpf); string getCpf(); }; #endif // !CLIENTEPF_HPP
16.56
43
0.618357
dayvisonmsilva
b488e3d8c8fdb5e7c32ea5afd93f39db30ce72a2
190
hpp
C++
include/mruby_integration/models/image.hpp
HellRok/Taylor
aa9d901b4db77395a0bde896500016353adcd73b
[ "MIT" ]
40
2021-05-25T04:21:49.000Z
2022-02-19T05:05:45.000Z
include/mruby_integration/models/image.hpp
HellRok/Taylor
aa9d901b4db77395a0bde896500016353adcd73b
[ "MIT" ]
4
2021-09-17T06:52:35.000Z
2021-12-29T23:07:18.000Z
include/mruby_integration/models/image.hpp
HellRok/Taylor
aa9d901b4db77395a0bde896500016353adcd73b
[ "MIT" ]
1
2021-12-23T00:59:27.000Z
2021-12-23T00:59:27.000Z
#pragma once #include "mruby.h" #include "raylib.h" extern RClass *Image_class; void setup_Image(mrb_state*, mrb_value, Image*, int, int, int, int); void append_models_Image(mrb_state*);
19
68
0.747368
HellRok
b48e0d82157e825eca2231f877300493cc8a02e9
29,906
cpp
C++
src/cues/TStageMovieCue.cpp
mvfranz/UltraDV
fbe0e8a3ee079d5dcd7e6e5bf99687aa79d351c5
[ "Unlicense" ]
null
null
null
src/cues/TStageMovieCue.cpp
mvfranz/UltraDV
fbe0e8a3ee079d5dcd7e6e5bf99687aa79d351c5
[ "Unlicense" ]
null
null
null
src/cues/TStageMovieCue.cpp
mvfranz/UltraDV
fbe0e8a3ee079d5dcd7e6e5bf99687aa79d351c5
[ "Unlicense" ]
1
2021-08-19T20:20:37.000Z
2021-08-19T20:20:37.000Z
//--------------------------------------------------------------------- // // File: TStageMovieCue.cpp // // Author: Gene Z. Ragan // // Date: 06.12.98 // // Desc: Visual representation of a movie cue on the stage // // Copyright ยฉ1998 mediapede Software // //--------------------------------------------------------------------- // Includes #include "BuildApp.h" #include <app/Application.h> #include <support/Debug.h> #include "AppConstants.h" #include "AppAlerts.h" #include "AppMessages.h" #include "MuseumApp.h" #include "TStageView.h" #include "TStageMovieCue.h" #include "TCueSheetWindow.h" #include "TCueSheetView.h" #include "TCueChannel.h" #include "TTransition.h" #include "TStageCueMenu.h" // Constants const short kBorder = 6; //--------------------------------------------------------------------- // Constructor //--------------------------------------------------------------------- // // TStageMovieCue::TStageMovieCue(BRect bounds, char* name, TCueView* theCue) : TStageCue(bounds, name, theCue) { // Do default initialization Init(); } //--------------------------------------------------------------------- // Constructor //--------------------------------------------------------------------- // // TStageMovieCue::TStageMovieCue(BMessage* theMessage) : TStageCue(theMessage) { // Do default initialization Init(); } //--------------------------------------------------------------------- // Destructor //--------------------------------------------------------------------- // // TStageMovieCue::~TStageMovieCue() { // Stop and clean up transitions if (fTransition) { delete fTransition; fTransition = NULL; } } //--------------------------------------------------------------------- // Init //--------------------------------------------------------------------- // // void TStageMovieCue::Init() { // Set up resize zone rects SetResizeZones(); fTransition = NULL; } #pragma mark - #pragma mark === Archiving Functions === //--------------------------------------------------------------------- // Instantiate //--------------------------------------------------------------------- // // BArchivable* TStageMovieCue::Instantiate(BMessage* archive) { if ( validate_instantiation(archive, "TStageMovieCue") ) return new TStageMovieCue(archive); return NULL; } //--------------------------------------------------------------------- // Archive //--------------------------------------------------------------------- // // status_t TStageMovieCue::Archive(BMessage* data, bool deep) const { status_t myErr; Looper()->Lock(); // Start by calling inherited archive myErr = TStageCue::Archive(data, deep); if (myErr == B_OK) { // Add ourselves to the archive data->AddString("class", "TStageMovieCue"); } Looper()->Unlock(); return myErr; } #pragma mark - #pragma mark === Drawing Routines === //--------------------------------------------------------------------- // Draw //--------------------------------------------------------------------- // // void TStageMovieCue::Draw(BRect updateRect) { if ( (fBitmap) && IsCueHidden() == true &&!IsHidden() ) { rgb_color saveColor = HighColor(); // Draw bitmap DrawBitmap(fOffscreen, B_ORIGIN); // Data selection and resizing rect DrawSelectionRect(); SetHighColor(saveColor); } } //--------------------------------------------------------------------- // DrawData //--------------------------------------------------------------------- // // Draw cues internal data // void TStageMovieCue::DrawData(BRect updateRect, long theTime) { // Do not draw if cue or channel is muted if ( fChannelCue->GetChannel()->GetMute() ) return; if ( fBitmap && IsCueHidden() == false && IsHidden() == true) { BRect area = fChannelCue->GetCroppedArea(); // Set up environment BRegion clipRegion, saveRegion; Parent()->GetClippingRegion(&saveRegion); clipRegion.Set(fChannelCue->GetCroppedArea()); Parent()->ConstrainClippingRegion( &clipRegion ); // Draw bitmap BPoint thePt(area.left, area.top); Parent()->DrawBitmap(fOffscreen, thePt); // Restore Parent()->ConstrainClippingRegion(&saveRegion); } } //--------------------------------------------------------------------- // CompositeData //--------------------------------------------------------------------- // // Draw cues internal data into composite view // void TStageMovieCue::CompositeData(BRect updateRect, BView* offscreen) { // Do not draw if cue or channel is muted // if ( fChannelCue->GetChannel()->GetMute() ) // return; // if ( fBitmap && IsCueHidden() == false && IsHidden() == true) { BRect area = fChannelCue->GetCroppedArea(); // Set up environment BRegion clipRegion, saveRegion; offscreen->GetClippingRegion(&saveRegion); clipRegion.Set(fChannelCue->GetCroppedArea()); offscreen->ConstrainClippingRegion( &clipRegion ); // Draw bitmap BPoint thePt(area.left, area.top); offscreen->DrawBitmap(fOffscreen, thePt); // Restore offscreen->ConstrainClippingRegion(&saveRegion); } } #pragma mark - #pragma mark === Mouse Handling === //--------------------------------------------------------------------- // MouseDown //--------------------------------------------------------------------- // // Handle mouse down events // void TStageMovieCue::MouseDown(BPoint where) { ChunkHeader ckHeader; VideoChunk vidChunk; const int32 frameSize = 320*240*2; BBitmap* displayBitmap = new BBitmap(BRect(0, 0, 319, 239), B_RGB15, false, false); // Test: play movie BFile* theFile = fChannelCue->GetFile(); // Load headers theFile->Seek(0, SEEK_SET); theFile->Read(&ckHeader, sizeof(ChunkHeader)); theFile->Read(&vidChunk, sizeof(VideoChunk)); // Load frames and display for (int32 frame = 0; frame < vidChunk.numFrames; frame++) { ssize_t numRead = theFile->Read(displayBitmap->Bits(), frameSize); Looper()->Lock(); DrawBitmap(displayBitmap); Sync(); Looper()->Unlock(); } /* // Do nothing if we are playing if ( static_cast<MuseumApp *>(be_app)->GetCueSheet()->IsPlaying() ) return; // Do nothing if view is hidden if (IsHidden()) return; // Check for double click TStageCue::MouseDown(where); // Determine which button has been clicked uint32 buttons = 0; BMessage *message = Window()->CurrentMessage(); message->FindInt32("buttons", (long *)&buttons); switch(buttons) { case B_PRIMARY_MOUSE_BUTTON: // Wait a short while before dragging snooze(60 * 1000); // Find location of click. If it is the main body of the picture, they are moving the picture. // Otherwise, they are resizing or cropping the image if ( PointInResizeZones(where) ) { ResizeOrCrop(where); } // They are dragging the picture... else { DragPicture(where); } // Update the picture rects fChannelCue->SetArea( Frame() ); fChannelCue->SetCroppedArea( Frame() ); break; // Show stage cue menu case B_SECONDARY_MOUSE_BUTTON: OpenStageCueMenu(where); break; } */ } //--------------------------------------------------------------------- // MouseUp //--------------------------------------------------------------------- // // Handle mouse up events // void TStageMovieCue::MouseUp(BPoint where) { // Do nothing if view is hidden if (IsHidden()) return; } //--------------------------------------------------------------------- // MouseMoved //--------------------------------------------------------------------- // // Handle mouse moved events // void TStageMovieCue::MouseMoved( BPoint where, uint32 code, const BMessage* a_message ) { // Do nothing if view is hidden if (IsHidden()) return; // Set proper cursor for resize zones if ( fTopLeftResize.Contains(where) ) be_app->SetCursor( &((MuseumApp*)be_app)->fResizeDiagRightCursor); else if ( fTopMiddleResize.Contains(where) ) be_app->SetCursor( &((MuseumApp*)be_app)->fSizeVertCursor); else if ( fTopRightResize.Contains(where) ) be_app->SetCursor( &((MuseumApp*)be_app)->fResizeDiagLeftCursor); else if ( fRightMiddleResize.Contains(where) ) be_app->SetCursor( &((MuseumApp*)be_app)->fSizeHorzCursor); else if ( fRightMiddleResize.Contains(where) ) be_app->SetCursor( &((MuseumApp*)be_app)->fSizeHorzCursor); else if ( fBottomRightResize.Contains(where) ) be_app->SetCursor( &((MuseumApp*)be_app)->fResizeDiagRightCursor); else if ( fBottomMiddleResize.Contains(where) ) be_app->SetCursor( &((MuseumApp*)be_app)->fSizeVertCursor); else if ( fBottomLeftResize.Contains(where) ) be_app->SetCursor( &((MuseumApp*)be_app)->fResizeDiagLeftCursor); else if ( fLeftMiddleResize.Contains(where) ) be_app->SetCursor( &((MuseumApp*)be_app)->fSizeHorzCursor); else be_app->SetCursor(B_HAND_CURSOR); } //--------------------------------------------------------------------- // FrameResized //--------------------------------------------------------------------- // // Handle resize of frame // void TStageMovieCue::FrameResized(float new_width, float new_height) { // Resize sizing zones SetResizeZones(); } #pragma mark - #pragma mark === Bitmap Handling === //--------------------------------------------------------------------- // SetBitmap //--------------------------------------------------------------------- // // void TStageMovieCue::SetBitmap(BBitmap* bitmap) { if (bitmap) { fBitmap = bitmap; // Create offscreen bitmap and view fOffscreen = new BBitmap( fBitmap->Bounds(), fBitmap->ColorSpace(), true, false); fOffscreenView = new BView( fBitmap->Bounds(), "OffscreenView", B_FOLLOW_NONE, NULL); fOffscreen->AddChild(fOffscreenView); fOffscreenView->Looper()->Lock(); fOffscreenView->DrawBitmap(fBitmap); fOffscreenView->Sync(); fOffscreenView->Looper()->Unlock(); } } #pragma mark - #pragma mark === Message Handling === //--------------------------------------------------------------------- // MessageReceived //--------------------------------------------------------------------- // // void TStageMovieCue::MessageReceived(BMessage* message) { double theTime; switch (message->what) { // Get updated bitmap case UPDATE_TIMELINE_MSG: { // Inform channel cue fChannelCue->MessageReceived(message); theTime = message->FindDouble("TheTime"); SetVisibility(theTime); } break; default: TStageCue::MessageReceived(message); break; } } #pragma mark - #pragma mark === Cue Visibility === //--------------------------------------------------------------------- // SetVisibility //--------------------------------------------------------------------- // // Determines the visibility of the stage cue data. The view itself is not shown, // rather the view data is copied onto the stage view void TStageMovieCue::SetVisibility(double theTime) { double cueStartTime = fChannelCue->GetStartTime(); double cueEndTime = fChannelCue->GetStartTime() + fChannelCue->GetDuration(); // Is the current time before the cue's start time or after the cue's end time? if (theTime < cueStartTime || theTime >= cueEndTime ) { if ( IsCueHidden() == false) { fIsHidden = true; UpdatePictureCueRegion(theTime); } } // We need to show the cue if it is not already visible else{ if ( IsCueHidden() == true) { // Set it's hidden flag to false fIsHidden = false; UpdatePictureCueRegion(theTime); } } } //--------------------------------------------------------------------- // UpdatePictureCueRegion //--------------------------------------------------------------------- // // We are showing or hiding the cue. Create a region that will // be used to invalidate the stage and force a proper redraw. It // handles the invalidation of layered cues properly. // void TStageMovieCue::UpdatePictureCueRegion(double theTime) { // Determine channelID int32 cueChannelID = fChannelCue->GetChannelID(); // Get total channels int32 totalChannels = static_cast<MuseumApp*>(be_app)->GetCueSheet()->GetCueSheetView()->GetTotalChannels(); // Determine cue layer. Iterate through all higher layers and determine // the area to be invalidated. Construct a region to do this. Exlude all // other area rects in higher channels than us. We wil then break // the region down into rects and invalidate them. BRegion invalRegion; invalRegion.Include(fChannelCue->GetArea()); for(int32 index = cueChannelID+1; index <= totalChannels; index++) { TStageCue* stageCue = ((TStageView*)Parent())->GetStageCueAtTimeandChannel(theTime, index); if (stageCue) invalRegion.Exclude( stageCue->GetChannelCue()->GetArea()); } // Now call our custom invalidation routine for(int32 index = 0; index < invalRegion.CountRects(); index++) { Parent()->Invalidate( invalRegion.RectAt(index)); //((TStageView *)Parent())->StageDraw( invalRegion.RectAt(index), theTime); } } #pragma mark - #pragma mark === Cue Selection and Resizing === //--------------------------------------------------------------------- // DrawSelectionRect //--------------------------------------------------------------------- // // Draw the selection rect and resize handles // void TStageMovieCue::DrawSelectionRect() { rgb_color saveColor; saveColor = HighColor(); SetHighColor(kRed); // Draw main selection rect //BRect frame = Bounds(); //frame.InsetBy(kBorder/2, kBorder/2); //StrokeRect(frame); // Draw resizing handles // // Fill them first... SetHighColor(kWhite); FillRect(fTopLeftResize); FillRect(fTopMiddleResize); FillRect(fTopRightResize); FillRect(fRightMiddleResize); FillRect(fBottomRightResize); FillRect(fBottomMiddleResize); FillRect(fBottomLeftResize); FillRect(fLeftMiddleResize); // Now stroke... SetHighColor(kBlack); StrokeRect(fTopLeftResize); StrokeRect(fTopMiddleResize); StrokeRect(fTopRightResize); StrokeRect(fRightMiddleResize); StrokeRect(fBottomRightResize); StrokeRect(fBottomMiddleResize); StrokeRect(fBottomLeftResize); StrokeRect(fLeftMiddleResize); } //--------------------------------------------------------------------- // InvalidateSelectionRect //--------------------------------------------------------------------- // // Invalidate just the selection rect and force a redraw // void TStageMovieCue::InvalidateSelectionRect() { // Create a region containing selection rect BRegion theRegion; BRect selectRect; // Top selectRect.Set(Bounds().left, Bounds().top, Bounds().right, Bounds().top +kBorder); theRegion.Include(selectRect); // Right selectRect.Set(Bounds().right-kBorder, Bounds().top, Bounds().right, Bounds().bottom); theRegion.Include(selectRect); // Bottom selectRect.Set(Bounds().left, Bounds().bottom-kBorder, Bounds().right, Bounds().bottom); theRegion.Include(selectRect); // Left selectRect.Set(Bounds().left, Bounds().top, Bounds().left+kBorder, Bounds().bottom); theRegion.Include(selectRect); // Now invalidate for(int32 index = 0; index < theRegion.CountRects(); index++) { Invalidate( theRegion.RectAt(index)); } } #pragma mark - #pragma mark === Resizing Routines === //--------------------------------------------------------------------- // SetResizeZones //--------------------------------------------------------------------- // // Set up the rects defining the picture resize zones void TStageMovieCue::SetResizeZones() { BRect bounds = Bounds(); fTopLeftResize.Set( bounds.left, bounds.top, bounds.left+kBorder, bounds.top+kBorder); fTopMiddleResize.Set( (bounds.Width()/2) - (kBorder/2), bounds.top, (bounds.Width()/2) + (kBorder/2), bounds.top+kBorder); fTopRightResize.Set( bounds.right-kBorder, bounds.top, bounds.right, bounds.top+kBorder); fRightMiddleResize.Set( bounds.right-kBorder, (bounds.Height()/2) - (kBorder/2), bounds.right, (bounds.Height()/2) + (kBorder/2)); fBottomRightResize.Set( bounds.right-kBorder, bounds.bottom-kBorder, bounds.right, bounds.bottom); fBottomMiddleResize.Set( (bounds.Width()/2) - (kBorder/2), bounds.bottom-kBorder, (bounds.Width()/2) + (kBorder/2), bounds.bottom); fBottomLeftResize.Set( bounds.left, bounds.bottom-kBorder, bounds.left+kBorder, bounds.bottom); fLeftMiddleResize.Set( bounds.left, (bounds.Height()/2) - (kBorder/2), bounds.left+kBorder, (bounds.Height()/2) + (kBorder/2)); } //--------------------------------------------------------------------- // PointInResizeZones //--------------------------------------------------------------------- // // If the point is within one of the resize zones, return true // bool TStageMovieCue::PointInResizeZones(BPoint thePoint) { if (fTopLeftResize.Contains(thePoint)) return true; if (fTopMiddleResize.Contains(thePoint)) return true; if (fTopRightResize.Contains(thePoint)) return true; if (fRightMiddleResize.Contains(thePoint)) return true; if (fBottomRightResize.Contains(thePoint)) return true; if (fBottomMiddleResize.Contains(thePoint)) return true; if (fBottomLeftResize.Contains(thePoint)) return true; if (fLeftMiddleResize.Contains(thePoint)) return true; return false; } //--------------------------------------------------------------------- // DragPicture //--------------------------------------------------------------------- // // While the mouse is down, move the picture // void TStageMovieCue::DragPicture(BPoint thePoint) { BPoint savePt; uint32 buttons = 0; GetMouse(&thePoint, &buttons, true); ConvertToParent(&thePoint); savePt = thePoint; while (buttons) { if (thePoint != savePt) { // Convert to parents coordinate system ConvertToParent(&thePoint); MoveBy( (thePoint.x - savePt.x), (thePoint.y - savePt.y) ); // Save mouse location for next compare savePt = thePoint; } GetMouse(&thePoint, &buttons, true); } } //--------------------------------------------------------------------- // ResizeOrCrop //--------------------------------------------------------------------- // // Resize of crop the picture depending upon current tool // void TStageMovieCue::ResizeOrCrop(BPoint thePoint) { short zoneID = GetResizeZoneID(thePoint); switch(zoneID) { case kTopLeftResize: ResizeTopLeft(thePoint); break; case kTopMiddleResize: break; case kTopRightResize: break; case kRightMiddleResize: ResizeRight(thePoint); break; case kBottomRightResize: ResizeBottomRight(thePoint); break; case kBottomMiddleResize: ResizeBottom(thePoint); break; case kBottomLeftResize: break; case kLeftMiddleResize: ResizeLeft(thePoint); break; // Bad ID value default: break; } // Update resize zones SetResizeZones(); } //--------------------------------------------------------------------- // GetResizeZoneID //--------------------------------------------------------------------- // // Return resize ID from point // short TStageMovieCue::GetResizeZoneID(BPoint thePoint) { if (fTopLeftResize.Contains(thePoint)) return kTopLeftResize; if (fTopMiddleResize.Contains(thePoint)) return kTopMiddleResize; if (fTopRightResize.Contains(thePoint)) return kTopRightResize; if (fRightMiddleResize.Contains(thePoint)) return kRightMiddleResize; if (fBottomRightResize.Contains(thePoint)) return kBottomRightResize; if (fBottomMiddleResize.Contains(thePoint)) return kBottomMiddleResize; if (fBottomLeftResize.Contains(thePoint)) return kBottomLeftResize; if (fLeftMiddleResize.Contains(thePoint)) return kLeftMiddleResize; // No zone found return -1; } //--------------------------------------------------------------------- // ResizeTopLeft //--------------------------------------------------------------------- // // Resize the top left of the view. // void TStageMovieCue::ResizeTopLeft( BPoint thePoint) { } //--------------------------------------------------------------------- // ResizeTopRight //--------------------------------------------------------------------- // // Resize the top and right side of the view. // void TStageMovieCue::ResizeTopRight( BPoint thePoint) { // Resize the cue to the right will the mouse button is down BPoint savePt; uint32 buttons = 0; GetMouse(&thePoint, &buttons, true); ConvertToParent(&thePoint); savePt = thePoint; while (buttons) { if (thePoint.x != savePt.x) { float resize = thePoint.x - savePt.x; // Don't allow resize past bitmap width if ( (Bounds().Width() + resize <= fBitmap->Bounds().Width()) || (Bounds().right - resize >= kBorder*2) ) { // Redraw the selection rect and resize points InvalidateSelectionRect(); // Do resize ResizeBy( resize, 0 ); SetResizeZones(); } // Save mouse location for next compare savePt = thePoint; } GetMouse(&thePoint, &buttons, true); // Clip the point back within the proper bounds if (thePoint.x > fBitmap->Bounds().right) thePoint.x = fBitmap->Bounds().right; if (thePoint.x < fBitmap->Bounds().left + (kBorder*2) ) thePoint.x = fBitmap->Bounds().left + (kBorder*2); // Convert to parents coordinate system ConvertToParent(&thePoint); } } //--------------------------------------------------------------------- // ResizeRight //--------------------------------------------------------------------- // // Resize the right side of the view. Constrain to the width of // the bitmap. Also, don't allow right to be less than left // void TStageMovieCue::ResizeRight( BPoint thePoint) { // Resize the cue to the right will the mouse button is down BPoint savePt; uint32 buttons = 0; GetMouse(&thePoint, &buttons, true); ConvertToParent(&thePoint); savePt = thePoint; while (buttons) { if (thePoint.x != savePt.x) { float resize = thePoint.x - savePt.x; // Don't allow resize past bitmap width if ( (Bounds().Width() + resize <= fBitmap->Bounds().Width()) || (Bounds().right - resize >= kBorder*2) ) { // Redraw the selection rect and resize points InvalidateSelectionRect(); // Do resize ResizeBy( resize, 0 ); SetResizeZones(); } // Save mouse location for next compare savePt = thePoint; } GetMouse(&thePoint, &buttons, true); // Clip the point back within the proper bounds if (thePoint.x > fBitmap->Bounds().right) thePoint.x = fBitmap->Bounds().right; if (thePoint.x < fBitmap->Bounds().left + (kBorder*2) ) thePoint.x = fBitmap->Bounds().left + (kBorder*2); // Convert to parents coordinate system ConvertToParent(&thePoint); } } //--------------------------------------------------------------------- // ResizeBottomRight //--------------------------------------------------------------------- // // Resize the bottom and right side of the view. // void TStageMovieCue::ResizeBottomRight( BPoint thePoint) { // Resize the cue to the right will the mouse button is down BPoint savePt; uint32 buttons = 0; GetMouse(&thePoint, &buttons, true); ConvertToParent(&thePoint); savePt = thePoint; while (buttons) { if (thePoint != savePt) { float resizeX = thePoint.x - savePt.x; float resizeY = thePoint.y - savePt.y; // Don't allow resize past bitmap width and height if ( (Bounds().Width() + resizeX <= fBitmap->Bounds().Width()) || Bounds().Height() + resizeY <= fBitmap->Bounds().Height() ) { // Constrian to minimum bounds if ( (Bounds().right - resizeX >= kBorder*2) || Bounds().bottom - resizeY >= fBitmap->Bounds().top + kBorder*2 ) { // Redraw the selection rect and resize points InvalidateSelectionRect(); // Do resize ResizeBy( resizeX, resizeY ); SetResizeZones(); } } // Save mouse location for next compare savePt = thePoint; } GetMouse(&thePoint, &buttons, true); // Clip the point back within the proper bounds if (thePoint.x > fBitmap->Bounds().right) thePoint.x = fBitmap->Bounds().right; if (thePoint.y > fBitmap->Bounds().bottom) thePoint.y = fBitmap->Bounds().bottom; if (thePoint.x < fBitmap->Bounds().left + (kBorder*2) ) thePoint.x = fBitmap->Bounds().left + (kBorder*2); if (thePoint.y < fBitmap->Bounds().top + (kBorder*2)) thePoint.y = fBitmap->Bounds().top + (kBorder*2); // Convert to parents coordinate system ConvertToParent(&thePoint); } } //--------------------------------------------------------------------- // ResizeBottom //--------------------------------------------------------------------- // // Resize the bottom side of the view. Constrain to the height of // the bitmap. // void TStageMovieCue::ResizeBottom( BPoint thePoint) { // Resize the cue to the right will the mouse button is down BPoint savePt; uint32 buttons = 0; GetMouse(&thePoint, &buttons, true); ConvertToParent(&thePoint); savePt = thePoint; while (buttons) { if (thePoint.y != savePt.y) { float resize = thePoint.y - savePt.y; // Don't allow resize past bitmap height or mimimum height if ( Bounds().Height() + resize <= fBitmap->Bounds().Height() || Bounds().bottom - resize >= fBitmap->Bounds().top + kBorder*2 ) { // Redraw the selection rect and resize points InvalidateSelectionRect(); // Do resize ResizeBy( 0, resize ); SetResizeZones(); } // Save mouse location for next compare savePt = thePoint; } GetMouse(&thePoint, &buttons, true); // Clip the point back within the proper bounds if (thePoint.y > fBitmap->Bounds().bottom) thePoint.y = fBitmap->Bounds().bottom; if (thePoint.y < fBitmap->Bounds().top + (kBorder*2)) thePoint.y = fBitmap->Bounds().top + (kBorder*2); // Convert to parents coordinate system ConvertToParent(&thePoint); } } //--------------------------------------------------------------------- // ResizeLeft //--------------------------------------------------------------------- // // Resize the left side of the view. Constrain to the width of // the bitmap. Also, don't allow right to be less than left // void TStageMovieCue::ResizeLeft( BPoint thePoint) { // Resize the cue to the right will the mouse button is down BPoint savePt; uint32 buttons = 0; GetMouse(&thePoint, &buttons, true); ConvertToParent(&thePoint); savePt = thePoint; while (buttons) { if (thePoint != savePt) { float resize = thePoint.x - savePt.x; // Don't allow resize past bitmap width if ( Bounds().Width() <= fBitmap->Bounds().Width() ) { // Redraw the selection rect and resize points InvalidateSelectionRect(); // Do resize. Resize the view and move it to the proper location //float curRight = Bounds().right; BPoint movePt = thePoint; ConvertToParent(movePt); MoveTo( movePt.x, Frame().top ); if ( Bounds().Width() + resize > fBitmap->Bounds().Width() ) resize = Bounds().Width() - fBitmap->Bounds().Width(); ResizeBy( -resize, 0 ); SetResizeZones(); } // Save mouse location for next compare savePt = thePoint; } GetMouse(&thePoint, &buttons, true); // Clip the point back within the proper bounds // Fix bounds violation //if ( Bounds().Width() > fBitmap->Bounds().Width() ) // ResizeBy( (Bounds().Width() - fBitmap->Bounds().Width()), 0 ); // Convert to parents coordinate system ConvertToParent(&thePoint); } } #pragma mark - #pragma mark === Playback Routines === //--------------------------------------------------------------------- // Stop //--------------------------------------------------------------------- // // Playback has been stopped. Stop any transitions. // void TStageMovieCue::Stop() { if (fTransition) { delete fTransition; fTransition = NULL; } } #pragma mark - #pragma mark === Transition Routines === //--------------------------------------------------------------------- // DoTransition //--------------------------------------------------------------------- // // Fire off a transition at the time // void TStageMovieCue::DoTransition(bool transitionIn) { // Clean up last transition if neccessary if (fTransition) { delete fTransition; fTransition = NULL; } // We are now visible fIsHidden = false; // Create new one and fire it off... if (transitionIn) fTransition = new TTransition( this, (TStageView*)Parent(), fChannelCue->GetTransitionInID(), fChannelCue->GetTransitionInDuration()); else fTransition = new TTransition( this, (TStageView*)Parent(), fChannelCue->GetTransitionOutID(), fChannelCue->GetTransitionOutDuration()); // Start it fTransition->Start(); } #pragma mark - #pragma mark === Menu Routines === //--------------------------------------------------------------------- // OpenStageCueMenu //--------------------------------------------------------------------- // // Open stage cue pop up menu // void TStageMovieCue::OpenStageCueMenu(BPoint menuPt) { BMenuItem* selected; // Create the menu and mark the current transition TStageCueMenu* theMenu = new TStageCueMenu(this->fChannelCue); if (theMenu) { // Set menu location point ConvertToScreen(&menuPt); selected = theMenu->Go(menuPt); // Check and see if we have a menu message int32 drawingMode; if (selected) { if ( selected->Message()->FindInt32("DrawingMode", &drawingMode) == B_OK) { // Lock offscreen fOffscreenView->Looper()->Lock(); // Save drawing mode fChannelCue->SetDrawingMode( (drawing_mode)drawingMode ); // Only redraw if mode has changed if ( fOffscreenView->DrawingMode() != fChannelCue->GetDrawingMode() ) { // Draw the bitmap into the offscreen using the new mode. fOffscreenView->SetDrawingMode(fChannelCue->GetDrawingMode()); fOffscreenView->DrawBitmap(fBitmap); fOffscreenView->Sync(); Invalidate(); } fOffscreenView->Looper()->Unlock(); } } // Clean up delete theMenu; } }
25.194608
138
0.575503
mvfranz
b491481148198377710caa035ddc62e52bc9e815
332
hpp
C++
include/cgsw/cgsw.hpp
chikeen/CGSW
10d159a9daf8ad1af5006602454b7e82c5e561c3
[ "Apache-2.0" ]
1
2021-04-12T07:12:23.000Z
2021-04-12T07:12:23.000Z
include/cgsw/cgsw.hpp
chikeen/CGSW
10d159a9daf8ad1af5006602454b7e82c5e561c3
[ "Apache-2.0" ]
null
null
null
include/cgsw/cgsw.hpp
chikeen/CGSW
10d159a9daf8ad1af5006602454b7e82c5e561c3
[ "Apache-2.0" ]
null
null
null
// // Created by Chi Keen Tan on 16/12/2020. // #pragma once #include "encryptionparams.hpp" #include "plaintext.hpp" #include "publickey.hpp" #include "secretkey.hpp" #include "cgsw/utils/utils.hpp" #include "ciphertext.hpp" #include "decrypter.hpp" #include "encrypter.hpp" #include "evaluator.hpp" #include "keygenerator.hpp"
18.444444
41
0.737952
chikeen
b492acdac156ac193a69110ab96edcecbea2f809
518
cpp
C++
Practice3/Task4.cpp
zuza-rzemieniewska/Cpp_Practices
96cade6c757185a533ecbb5ffd26dff929df8d9a
[ "MIT" ]
null
null
null
Practice3/Task4.cpp
zuza-rzemieniewska/Cpp_Practices
96cade6c757185a533ecbb5ffd26dff929df8d9a
[ "MIT" ]
null
null
null
Practice3/Task4.cpp
zuza-rzemieniewska/Cpp_Practices
96cade6c757185a533ecbb5ffd26dff929df8d9a
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(){ float a, b, c; do{ cout << "Please enter three segments a, b and c greater than 0:" << endl; cin >> a >> b >> c; }while(a<=0 || b<=0 || c<=0); if(a+b>c && a+c>b && c+b>a) cout << "From length segments: " << a << ", " << b << ", " << c << " triangle could be build" << endl; else cout << "From length segments: " << a << ", " << b << ", " << c << " triangle couldn't be build" << endl; return 0; }
22.521739
113
0.459459
zuza-rzemieniewska
b493bf446fa06487959f5f4b90cec5ac7e9e3ecb
24,614
cpp
C++
gui/duilib/duilib/Control/ScrollBar.cpp
pqgarden/PQBase
fe64dc937c2d86cb6363b2c0a394f0a9d794b116
[ "MIT" ]
1,461
2019-04-10T09:28:18.000Z
2022-03-30T01:56:09.000Z
gui/duilib/duilib/Control/ScrollBar.cpp
pqgarden/PQBase
fe64dc937c2d86cb6363b2c0a394f0a9d794b116
[ "MIT" ]
331
2019-04-11T06:15:44.000Z
2022-03-28T01:24:07.000Z
gui/duilib/duilib/Control/ScrollBar.cpp
pqgarden/PQBase
fe64dc937c2d86cb6363b2c0a394f0a9d794b116
[ "MIT" ]
678
2019-04-10T13:27:12.000Z
2022-03-28T02:03:01.000Z
#include "stdafx.h" #include "ScrollBar.h" namespace ui { ScrollBar::ScrollBar() : m_bHorizontal(false), m_bShowButton1(true), m_bShowButton2(true), m_bAutoHide(true), m_nRange(100), m_nScrollPos(0), m_nLineSize(8), m_nThumbMinLength(30), m_nLastScrollPos(0), m_nLastScrollOffset(0), m_nScrollRepeatDelay(0), m_pOwner(nullptr), m_ptLastMouse(), m_rcButton1(0, 0, 0, 0), m_rcButton2(0, 0, 0, 0), m_rcThumb(0, 0, 0, 0), m_uButton1State(kControlStateNormal), m_uButton2State(kControlStateNormal), m_uThumbState(kControlStateNormal), m_sImageModify(), m_bkStateImage(), m_button1StateImage(), m_button2StateImage(), m_thumbStateImage(), m_railStateImage(), m_weakFlagOwner() { m_cxyFixed.cx = DEFAULT_SCROLLBAR_SIZE; m_cxyFixed.cy = 0; m_ptLastMouse.x = m_ptLastMouse.y = 0; m_bkStateImage.SetControl(this); m_thumbStateImage.SetControl(this); m_bFloat = true; SetNeedButtonUpWhenKillFocus(true); } Box* ScrollBar::GetOwner() const { return m_pOwner; } void ScrollBar::SetOwner(ScrollableBox* pOwner) { m_pOwner = pOwner; } void ScrollBar::SetEnabled(bool bEnable) { Control::SetEnabled(bEnable); if( bEnable ) { m_uButton1State = kControlStateNormal; m_uButton2State = kControlStateNormal; m_uThumbState = kControlStateNormal; } else { m_uButton1State = kControlStateDisabled; m_uButton2State = kControlStateDisabled; m_uThumbState = kControlStateDisabled; } } void ScrollBar::SetFocus() { if (m_pOwner != NULL) m_pOwner->SetFocus(); else Control::SetFocus(); } void ScrollBar::SetVisible_(bool bVisible) { if( m_bVisible == bVisible ) return; bool v = IsVisible(); m_bVisible = bVisible; if( m_bFocused ) m_bFocused = false; if (!bVisible && m_pWindow && m_pWindow->GetFocus() == this) { m_pWindow->SetFocus(NULL) ; } if( IsVisible() != v ) { ArrangeSelf(); } } bool ScrollBar::ButtonUp(EventArgs& msg) { bool ret = false; if( IsMouseFocused() ) { SetMouseFocused(false); Invalidate(); UiRect pos = GetPos(); if (::PtInRect(&pos, msg.ptMouse)) { m_uButtonState = kControlStateHot; m_nHotAlpha = 255; Activate(); ret = true; } else { m_uButtonState = kControlStateNormal; m_nHotAlpha = 0; } } UiRect ownerPos = m_pOwner->GetPos(); if (m_bAutoHide && !::PtInRect(&ownerPos, msg.ptMouse)) { SetVisible(false); } return ret; } bool ScrollBar::HasHotState() { return true; } bool ScrollBar::MouseEnter(EventArgs& msg) { bool ret = __super::MouseEnter(msg); if (ret) { m_uButton1State = kControlStateHot; m_uButton2State = kControlStateHot; m_uThumbState = kControlStateHot; } return ret; } bool ScrollBar::MouseLeave(EventArgs& msg) { bool ret = __super::MouseLeave(msg); if (ret) { m_uButton1State = kControlStateNormal; m_uButton2State = kControlStateNormal; m_uThumbState = kControlStateNormal; } return ret; } void ScrollBar::SetPos(UiRect rc) { Control::SetPos(rc); rc = m_rcItem; if (m_bHorizontal) { int cx = rc.right - rc.left; if (m_bShowButton1) cx -= m_cxyFixed.cy; if (m_bShowButton2) cx -= m_cxyFixed.cy; if (cx > m_cxyFixed.cy) { m_rcButton1.left = rc.left; m_rcButton1.top = rc.top; if (m_bShowButton1) { m_rcButton1.right = rc.left + m_cxyFixed.cy; m_rcButton1.bottom = rc.top + m_cxyFixed.cy; } else { m_rcButton1.right = m_rcButton1.left; m_rcButton1.bottom = m_rcButton1.top; } m_rcButton2.top = rc.top; m_rcButton2.right = rc.right; if (m_bShowButton2) { m_rcButton2.left = rc.right - m_cxyFixed.cy; m_rcButton2.bottom = rc.top + m_cxyFixed.cy; } else { m_rcButton2.left = m_rcButton2.right; m_rcButton2.bottom = m_rcButton2.top; } m_rcThumb.top = rc.top; m_rcThumb.bottom = rc.top + m_cxyFixed.cy; if (m_nRange > 0) { int cxThumb = cx * (rc.right - rc.left) / (m_nRange + rc.right - rc.left); if (cxThumb < m_nThumbMinLength) cxThumb = m_nThumbMinLength; m_rcThumb.left = m_nScrollPos * (cx - cxThumb) / m_nRange + m_rcButton1.right; m_rcThumb.right = m_rcThumb.left + cxThumb; if (m_rcThumb.right > m_rcButton2.left) { m_rcThumb.left = m_rcButton2.left - cxThumb; m_rcThumb.right = m_rcButton2.left; } } else { m_rcThumb.left = m_rcButton1.right; m_rcThumb.right = m_rcButton2.left; } } else { int cxButton = (rc.right - rc.left) / 2; if (cxButton > m_cxyFixed.cy) cxButton = m_cxyFixed.cy; m_rcButton1.left = rc.left; m_rcButton1.top = rc.top; if (m_bShowButton1) { m_rcButton1.right = rc.left + cxButton; m_rcButton1.bottom = rc.top + m_cxyFixed.cy; } else { m_rcButton1.right = m_rcButton1.left; m_rcButton1.bottom = m_rcButton1.top; } m_rcButton2.top = rc.top; m_rcButton2.right = rc.right; if (m_bShowButton2) { m_rcButton2.left = rc.right - cxButton; m_rcButton2.bottom = rc.top + m_cxyFixed.cy; } else { m_rcButton2.left = m_rcButton2.right; m_rcButton2.bottom = m_rcButton2.top; } ::ZeroMemory(&m_rcThumb, sizeof(m_rcThumb)); } } else { int cy = rc.bottom - rc.top; if (m_bShowButton1) cy -= m_cxyFixed.cx; if (m_bShowButton2) cy -= m_cxyFixed.cx; if (cy > m_cxyFixed.cx) { m_rcButton1.left = rc.left; m_rcButton1.top = rc.top; if (m_bShowButton1) { m_rcButton1.right = rc.left + m_cxyFixed.cx; m_rcButton1.bottom = rc.top + m_cxyFixed.cx; } else { m_rcButton1.right = m_rcButton1.left; m_rcButton1.bottom = m_rcButton1.top; } m_rcButton2.left = rc.left; m_rcButton2.bottom = rc.bottom; if (m_bShowButton2) { m_rcButton2.top = rc.bottom - m_cxyFixed.cx; m_rcButton2.right = rc.left + m_cxyFixed.cx; } else { m_rcButton2.top = m_rcButton2.bottom; m_rcButton2.right = m_rcButton2.left; } m_rcThumb.left = rc.left; m_rcThumb.right = rc.left + m_cxyFixed.cx; if (m_nRange > 0) { int cyThumb = cy * (rc.bottom - rc.top) / (m_nRange + rc.bottom - rc.top); if (cyThumb < m_nThumbMinLength) cyThumb = m_nThumbMinLength; m_rcThumb.top = m_nScrollPos * (cy - cyThumb) / m_nRange + m_rcButton1.bottom; m_rcThumb.bottom = m_rcThumb.top + cyThumb; if (m_rcThumb.bottom > m_rcButton2.top) { m_rcThumb.top = m_rcButton2.top - cyThumb; m_rcThumb.bottom = m_rcButton2.top; } } else { m_rcThumb.top = m_rcButton1.bottom; m_rcThumb.bottom = m_rcButton2.top; } } else { int cyButton = (rc.bottom - rc.top) / 2; if (cyButton > m_cxyFixed.cx) cyButton = m_cxyFixed.cx; m_rcButton1.left = rc.left; m_rcButton1.top = rc.top; if (m_bShowButton1) { m_rcButton1.right = rc.left + m_cxyFixed.cx; m_rcButton1.bottom = rc.top + cyButton; } else { m_rcButton1.right = m_rcButton1.left; m_rcButton1.bottom = m_rcButton1.top; } m_rcButton2.left = rc.left; m_rcButton2.bottom = rc.bottom; if (m_bShowButton2) { m_rcButton2.top = rc.bottom - cyButton; m_rcButton2.right = rc.left + m_cxyFixed.cx; } else { m_rcButton2.top = m_rcButton2.bottom; m_rcButton2.right = m_rcButton2.left; } ::ZeroMemory(&m_rcThumb, sizeof(m_rcThumb)); } } } void ScrollBar::HandleMessage(EventArgs& event) { ASSERT(m_pOwner); if (!IsMouseEnabled() && event.Type > kEventMouseBegin && event.Type < kEventMouseEnd) { if (m_pOwner != NULL) m_pOwner->HandleMessageTemplate(event); return; } if (event.Type == kEventInternalSetFocus) { return; } else if (event.Type == kEventInternalKillFocus) { return; } else if (event.Type == kEventMouseButtonDown || event.Type == kEventInternalDoubleClick || event.Type == kEventPointDown) { if (!IsEnabled()) return; m_nLastScrollOffset = 0; m_nScrollRepeatDelay = 0; auto callback = nbase::Bind(&ScrollBar::ScrollTimeHandle, this); TimerManager::GetInstance()->AddCancelableTimer(m_weakFlagOwner.GetWeakFlag(), callback, 50, TimerManager::REPEAT_FOREVER); if (::PtInRect(&m_rcButton1, event.ptMouse)) { m_uButton1State = kControlStatePushed; if (!m_bHorizontal) { if (m_pOwner != NULL) m_pOwner->LineUp(); else SetScrollPos(m_nScrollPos - m_nLineSize); } else { if (m_pOwner != NULL) m_pOwner->LineLeft(); else SetScrollPos(m_nScrollPos - m_nLineSize); } } else if (::PtInRect(&m_rcButton2, event.ptMouse)) { m_uButton2State = kControlStatePushed; if (!m_bHorizontal) { if (m_pOwner != NULL) m_pOwner->LineDown(); else SetScrollPos(m_nScrollPos + m_nLineSize); } else { if (m_pOwner != NULL) m_pOwner->LineRight(); else SetScrollPos(m_nScrollPos + m_nLineSize); } } else if (::PtInRect(&m_rcThumb, event.ptMouse)) { m_uThumbState = kControlStatePushed; SetMouseFocused(true); m_ptLastMouse = event.ptMouse; m_nLastScrollPos = m_nScrollPos; } else { if (!m_bHorizontal) { if (event.ptMouse.y < m_rcThumb.top) { if (m_pOwner != NULL) m_pOwner->PageUp(); else SetScrollPos(m_nScrollPos + m_rcItem.top - m_rcItem.bottom); } else if (event.ptMouse.y > m_rcThumb.bottom){ if (m_pOwner != NULL) m_pOwner->PageDown(); else SetScrollPos(m_nScrollPos - m_rcItem.top + m_rcItem.bottom); } } else { if (event.ptMouse.x < m_rcThumb.left) { if (m_pOwner != NULL) m_pOwner->PageLeft(); else SetScrollPos(m_nScrollPos + m_rcItem.left - m_rcItem.right); } else if (event.ptMouse.x > m_rcThumb.right){ if (m_pOwner != NULL) m_pOwner->PageRight(); else SetScrollPos(m_nScrollPos - m_rcItem.left + m_rcItem.right); } } } ButtonDown(event); return; } else if (event.Type == kEventMouseButtonUp || event.Type == kEventPointUp) { m_nScrollRepeatDelay = 0; m_nLastScrollOffset = 0; m_weakFlagOwner.Cancel(); if (IsMouseFocused()) { if (::PtInRect(&m_rcItem, event.ptMouse)) { m_uThumbState = kControlStateHot; } else { m_uThumbState = kControlStateNormal; } } else if (m_uButton1State == kControlStatePushed) { m_uButton1State = kControlStateNormal; Invalidate(); } else if (m_uButton2State == kControlStatePushed) { m_uButton2State = kControlStateNormal; Invalidate(); } ButtonUp(event); return; } else if (event.Type == kEventMouseEnter) { MouseEnter(event); } else if (event.Type == kEventMouseLeave) { MouseLeave(event); } else if (event.Type == kEventMouseMove || event.Type == kEventPointMove) { if (IsMouseFocused()) { if (!m_bHorizontal) { int vRange = m_rcItem.bottom - m_rcItem.top - m_rcThumb.bottom + m_rcThumb.top; if (m_bShowButton1) { vRange -= m_cxyFixed.cx; } if (m_bShowButton2) { vRange -= m_cxyFixed.cx; } if (vRange != 0) m_nLastScrollOffset = (event.ptMouse.y - m_ptLastMouse.y) * m_nRange / vRange; } else { int hRange = m_rcItem.right - m_rcItem.left - m_rcThumb.right + m_rcThumb.left; if (m_bShowButton1) { hRange -= m_cxyFixed.cy; } if (m_bShowButton2) { hRange -= m_cxyFixed.cy; } if (hRange != 0) m_nLastScrollOffset = (event.ptMouse.x - m_ptLastMouse.x) * m_nRange / hRange; } } return; } else if (event.Type == kEventInternalMenu) { return; } else if (event.Type == kEventSetCursor) { if (m_cursorType == kCursorHand) { ::SetCursor(::LoadCursor(NULL, MAKEINTRESOURCE(IDC_HAND))); return; } else if (m_cursorType == kCursorArrow){ ::SetCursor(::LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW))); return; } else { ASSERT(FALSE); } } if (m_pOwner != NULL) m_pOwner->HandleMessageTemplate(event); } void ScrollBar::SetAttribute(const std::wstring& strName, const std::wstring& strValue) { if (strName == _T("button1normalimage")) SetButton1StateImage(kControlStateNormal, strValue); else if (strName == _T("button1hotimage")) SetButton1StateImage(kControlStateHot, strValue); else if (strName == _T("button1pushedimage")) SetButton1StateImage(kControlStatePushed, strValue); else if (strName == _T("button1disabledimage")) SetButton1StateImage(kControlStateDisabled, strValue); else if (strName == _T("button2normalimage")) SetButton2StateImage(kControlStateNormal, strValue); else if (strName == _T("button2hotimage")) SetButton2StateImage(kControlStateHot, strValue); else if (strName == _T("button2pushedimage")) SetButton2StateImage(kControlStatePushed, strValue); else if (strName == _T("button2disabledimage")) SetButton2StateImage(kControlStateDisabled, strValue); else if (strName == _T("thumbnormalimage")) SetThumbStateImage(kControlStateNormal, strValue); else if (strName == _T("thumbhotimage")) SetThumbStateImage(kControlStateHot, strValue); else if (strName == _T("thumbpushedimage")) SetThumbStateImage(kControlStatePushed, strValue); else if (strName == _T("thumbdisabledimage")) SetThumbStateImage(kControlStateDisabled, strValue); else if (strName == _T("railnormalimage")) SetRailStateImage(kControlStateNormal, strValue); else if (strName == _T("railhotimage")) SetRailStateImage(kControlStateHot, strValue); else if (strName == _T("railpushedimage")) SetRailStateImage(kControlStatePushed, strValue); else if (strName == _T("raildisabledimage")) SetRailStateImage(kControlStateDisabled, strValue); else if (strName == _T("bknormalimage")) SetBkStateImage(kControlStateNormal, strValue); else if (strName == _T("bkhotimage")) SetBkStateImage(kControlStateHot, strValue); else if (strName == _T("bkpushedimage")) SetBkStateImage(kControlStatePushed, strValue); else if (strName == _T("bkdisabledimage")) SetBkStateImage(kControlStateDisabled, strValue); else if (strName == _T("hor")) SetHorizontal(strValue == _T("true")); else if (strName == _T("linesize")) SetLineSize(_ttoi(strValue.c_str())); else if (strName == _T("thumbminlength")) SetThumbMinLength(_ttoi(strValue.c_str())); else if (strName == _T("range")) SetScrollRange(_ttoi(strValue.c_str())); else if (strName == _T("value")) SetScrollPos(_ttoi(strValue.c_str())); else if (strName == _T("showbutton1")) SetShowButton1(strValue == _T("true")); else if (strName == _T("showbutton2")) SetShowButton2(strValue == _T("true")); else if (strName == _T("autohidescroll")) SetAutoHideScroll(strValue == _T("true")); else Control::SetAttribute(strName, strValue); } void ScrollBar::Paint(IRenderContext* pRender, const UiRect& rcPaint) { if (!::IntersectRect(&m_rcPaint, &rcPaint, &m_rcItem)) return; PaintBk(pRender); PaintButton1(pRender); PaintButton2(pRender); PaintThumb(pRender); PaintRail(pRender); } void ScrollBar::ClearImageCache() { __super::ClearImageCache(); m_bkStateImage.ClearCache(); m_button1StateImage.ClearCache(); m_button2StateImage.ClearCache(); m_thumbStateImage.ClearCache(); m_railStateImage.ClearCache(); } bool ScrollBar::IsHorizontal() { return m_bHorizontal; } void ScrollBar::SetHorizontal(bool bHorizontal) { if( m_bHorizontal == bHorizontal ) return; m_bHorizontal = bHorizontal; if( m_bHorizontal ) { if( m_cxyFixed.cy == 0 ) { m_cxyFixed.cx = 0; m_cxyFixed.cy = DEFAULT_SCROLLBAR_SIZE; } } else { if( m_cxyFixed.cx == 0 ) { m_cxyFixed.cx = DEFAULT_SCROLLBAR_SIZE; m_cxyFixed.cy = 0; } } if( m_pOwner != NULL ) m_pOwner->Arrange(); else ArrangeAncestor(); } int64_t ScrollBar::GetScrollRange() const { return m_nRange; } void ScrollBar::SetScrollRange(int64_t nRange) { if( m_nRange == nRange ) return; m_nRange = nRange; if( m_nRange < 0 ) m_nRange = 0; if( m_nScrollPos > m_nRange ) m_nScrollPos = m_nRange; if (m_nRange == 0) { SetVisible_(false); } else if (!m_bAutoHide && !IsVisible()) { SetVisible(true); } SetPos(m_rcItem); } int64_t ScrollBar::GetScrollPos() const { return m_nScrollPos; } void ScrollBar::SetScrollPos(int64_t nPos) { if( m_nScrollPos == nPos ) return; m_nScrollPos = nPos; if( m_nScrollPos < 0 ) m_nScrollPos = 0; if( m_nScrollPos > m_nRange ) m_nScrollPos = m_nRange; SetPos(m_rcItem); } int ScrollBar::GetLineSize() const { return m_nLineSize; } void ScrollBar::SetLineSize(int nSize) { DpiManager::GetInstance()->ScaleInt(nSize); m_nLineSize = nSize; } int ScrollBar::GetThumbMinLength() const { return m_nThumbMinLength; } void ScrollBar::SetThumbMinLength(int nThumbMinLength) { DpiManager::GetInstance()->ScaleInt(nThumbMinLength); m_nThumbMinLength = nThumbMinLength; } bool ScrollBar::IsShowButton1() { return m_bShowButton1; } void ScrollBar::SetShowButton1(bool bShow) { m_bShowButton1 = bShow; SetPos(m_rcItem); } std::wstring ScrollBar::GetButton1StateImage(ControlStateType stateType) { return m_button1StateImage[stateType].imageAttribute.simageString; } void ScrollBar::SetButton1StateImage(ControlStateType stateType, const std::wstring& pStrImage) { m_button1StateImage[stateType].SetImageString(pStrImage); Invalidate(); } bool ScrollBar::IsShowButton2() { return m_bShowButton2; } void ScrollBar::SetShowButton2(bool bShow) { m_bShowButton2 = bShow; SetPos(m_rcItem); } std::wstring ScrollBar::GetButton2StateImage(ControlStateType stateType) { return m_button2StateImage[stateType].imageAttribute.simageString; } void ScrollBar::SetButton2StateImage(ControlStateType stateType, const std::wstring& pStrImage) { m_button2StateImage[stateType].SetImageString(pStrImage); Invalidate(); } std::wstring ScrollBar::GetThumbStateImage(ControlStateType stateType) { return m_thumbStateImage[stateType].imageAttribute.simageString; } void ScrollBar::SetThumbStateImage(ControlStateType stateType, const std::wstring& pStrImage) { m_thumbStateImage[stateType].SetImageString(pStrImage); Invalidate(); } std::wstring ScrollBar::GetRailStateImage(ControlStateType stateType) { return m_railStateImage[stateType].imageAttribute.simageString; } void ScrollBar::SetRailStateImage(ControlStateType stateType, const std::wstring& pStrImage) { m_railStateImage[stateType].SetImageString(pStrImage); Invalidate(); } std::wstring ScrollBar::GetBkStateImage(ControlStateType stateType) { return m_bkStateImage[stateType].imageAttribute.simageString; } void ScrollBar::SetBkStateImage(ControlStateType stateType, const std::wstring& pStrImage) { m_bkStateImage[stateType].SetImageString(pStrImage); Invalidate(); } void ScrollBar::SetAutoHideScroll(bool hide) { if (m_bAutoHide != hide) { m_bAutoHide = hide; } } void ScrollBar::ScrollTimeHandle() { ++m_nScrollRepeatDelay; if(m_uThumbState == kControlStatePushed) { if( !m_bHorizontal ) { if( m_pOwner != NULL ) m_pOwner->SetScrollPos(CSize(m_pOwner->GetScrollPos().cx, \ m_nLastScrollPos + m_nLastScrollOffset)); else SetScrollPos(m_nLastScrollPos + m_nLastScrollOffset); } else { if( m_pOwner != NULL ) m_pOwner->SetScrollPos(CSize(m_nLastScrollPos + m_nLastScrollOffset, \ m_pOwner->GetScrollPos().cy)); else SetScrollPos(m_nLastScrollPos + m_nLastScrollOffset); } } else if( m_uButton1State == kControlStatePushed ) { if( m_nScrollRepeatDelay <= 5 ) return; if( !m_bHorizontal ) { if( m_pOwner != NULL ) m_pOwner->LineUp(); else SetScrollPos(m_nScrollPos - m_nLineSize); } else { if( m_pOwner != NULL ) m_pOwner->LineLeft(); else SetScrollPos(m_nScrollPos - m_nLineSize); } } else if( m_uButton2State == kControlStatePushed ) { if( m_nScrollRepeatDelay <= 5 ) return; if( !m_bHorizontal ) { if( m_pOwner != NULL ) m_pOwner->LineDown(); else SetScrollPos(m_nScrollPos + m_nLineSize); } else { if( m_pOwner != NULL ) m_pOwner->LineRight(); else SetScrollPos(m_nScrollPos + m_nLineSize); } } else { if( m_nScrollRepeatDelay <= 5 ) return; POINT pt = { 0 }; ::GetCursorPos(&pt); ::ScreenToClient(m_pWindow->GetHWND(), &pt); if( !m_bHorizontal ) { if( pt.y < m_rcThumb.top ) { if( m_pOwner != NULL ) m_pOwner->PageUp(); else SetScrollPos(m_nScrollPos + m_rcItem.top - m_rcItem.bottom); } else if ( pt.y > m_rcThumb.bottom ){ if( m_pOwner != NULL ) m_pOwner->PageDown(); else SetScrollPos(m_nScrollPos - m_rcItem.top + m_rcItem.bottom); } } else { if( pt.x < m_rcThumb.left ) { if( m_pOwner != NULL ) m_pOwner->PageLeft(); else SetScrollPos(m_nScrollPos + m_rcItem.left - m_rcItem.right); } else if ( pt.x > m_rcThumb.right ){ if( m_pOwner != NULL ) m_pOwner->PageRight(); else SetScrollPos(m_nScrollPos - m_rcItem.left + m_rcItem.right); } } } return; } void ScrollBar::PaintBk(IRenderContext* pRender) { m_bkStateImage.PaintStatusImage(pRender, m_uButtonState); } void ScrollBar::PaintButton1(IRenderContext* pRender) { if (!m_bShowButton1) return; m_sImageModify.clear(); m_sImageModify = StringHelper::Printf(_T("destscale='false' dest='%d,%d,%d,%d'"), m_rcButton1.left - m_rcItem.left, \ m_rcButton1.top - m_rcItem.top, m_rcButton1.right - m_rcItem.left, m_rcButton1.bottom - m_rcItem.top); if (m_uButton1State == kControlStateDisabled) { if (!DrawImage(pRender, m_button1StateImage[kControlStateDisabled], m_sImageModify)) { } else return; } else if (m_uButton1State == kControlStatePushed) { if (!DrawImage(pRender, m_button1StateImage[kControlStatePushed], m_sImageModify)) { } else return; if (!DrawImage(pRender, m_button1StateImage[kControlStateHot], m_sImageModify)) { } else return; } else if (m_uButton1State == kControlStateHot || m_uThumbState == kControlStatePushed) { if (!DrawImage(pRender, m_button1StateImage[kControlStateHot], m_sImageModify)) { } else return; } if (!DrawImage(pRender, m_button1StateImage[kControlStateNormal], m_sImageModify)) { } else return; } void ScrollBar::PaintButton2(IRenderContext* pRender) { if (!m_bShowButton2) return; m_sImageModify.clear(); m_sImageModify = StringHelper::Printf(_T("destscale='false' dest='%d,%d,%d,%d'"), m_rcButton2.left - m_rcItem.left, \ m_rcButton2.top - m_rcItem.top, m_rcButton2.right - m_rcItem.left, m_rcButton2.bottom - m_rcItem.top); if (m_uButton2State == kControlStateDisabled) { if (!DrawImage(pRender, m_button2StateImage[kControlStateDisabled], m_sImageModify)) { } else return; } else if (m_uButton2State == kControlStatePushed) { if (!DrawImage(pRender, m_button2StateImage[kControlStatePushed], m_sImageModify)) { } else return; if (!DrawImage(pRender, m_button2StateImage[kControlStateHot], m_sImageModify)) { } else return; } else if (m_uButton2State == kControlStateHot || m_uThumbState == kControlStatePushed) { if (!DrawImage(pRender, m_button2StateImage[kControlStateHot], m_sImageModify)) { } else return; } if (!DrawImage(pRender, m_button2StateImage[kControlStateNormal], m_sImageModify)) { } else return; } void ScrollBar::PaintThumb(IRenderContext* pRender) { if (m_rcThumb.left == 0 && m_rcThumb.top == 0 && m_rcThumb.right == 0 && m_rcThumb.bottom == 0) return; m_sImageModify.clear(); m_sImageModify = StringHelper::Printf(_T("destscale='false' dest='%d,%d,%d,%d'"), m_rcThumb.left - m_rcItem.left, \ m_rcThumb.top - m_rcItem.top, m_rcThumb.right - m_rcItem.left, m_rcThumb.bottom - m_rcItem.top); m_thumbStateImage.PaintStatusImage(pRender, m_uThumbState, m_sImageModify); } void ScrollBar::PaintRail(IRenderContext* pRender) { if (m_rcThumb.left == 0 && m_rcThumb.top == 0 && m_rcThumb.right == 0 && m_rcThumb.bottom == 0) return; m_sImageModify.clear(); if (!m_bHorizontal) { m_sImageModify = StringHelper::Printf(_T("destscale='false' dest='%d,%d,%d,%d'"), m_rcThumb.left - m_rcItem.left, \ (m_rcThumb.top + m_rcThumb.bottom) / 2 - m_rcItem.top - m_cxyFixed.cx / 2, \ m_rcThumb.right - m_rcItem.left, \ (m_rcThumb.top + m_rcThumb.bottom) / 2 - m_rcItem.top + m_cxyFixed.cx - m_cxyFixed.cx / 2); } else { m_sImageModify = StringHelper::Printf(_T("destscale='false' dest='%d,%d,%d,%d'"), \ (m_rcThumb.left + m_rcThumb.right) / 2 - m_rcItem.left - m_cxyFixed.cy / 2, \ m_rcThumb.top - m_rcItem.top, \ (m_rcThumb.left + m_rcThumb.right) / 2 - m_rcItem.left + m_cxyFixed.cy - m_cxyFixed.cy / 2, \ m_rcThumb.bottom - m_rcItem.top); } if (m_uThumbState == kControlStateDisabled) { if (!DrawImage(pRender, m_railStateImage[kControlStateDisabled], m_sImageModify)) { } else return; } else if (m_uThumbState == kControlStatePushed) { if (!DrawImage(pRender, m_railStateImage[kControlStatePushed], m_sImageModify)) { } else return; if (!DrawImage(pRender, m_railStateImage[kControlStateHot], m_sImageModify)) { } else return; } else if (m_uThumbState == kControlStateHot) { if (!DrawImage(pRender, m_railStateImage[kControlStateHot], m_sImageModify)) { } else return; } if (!DrawImage(pRender, m_railStateImage[kControlStateNormal], m_sImageModify)) { } else return; } }
27.56327
125
0.707362
pqgarden
b495dbcb3466041d59cb48d10ac4cec5bf1cab0a
2,700
cpp
C++
examples/chat_room/example_service.cpp
LoganBarnes/ltb-gvs
b1178e31c35aece434c7d47af955275fca9bb2a5
[ "MIT" ]
1
2020-04-04T16:57:25.000Z
2020-04-04T16:57:25.000Z
examples/chat_room/example_service.cpp
LoganBarnes/ltb-gvs
b1178e31c35aece434c7d47af955275fca9bb2a5
[ "MIT" ]
null
null
null
examples/chat_room/example_service.cpp
LoganBarnes/ltb-gvs
b1178e31c35aece434c7d47af955275fca9bb2a5
[ "MIT" ]
null
null
null
// /////////////////////////////////////////////////////////////////////////////////////// // LTB Geometry Visualization Server // Copyright (c) 2020 Logan Barnes - All Rights Reserved // // 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 "example_service.hpp" namespace ltb::example { ExampleService::ExampleService() = default; auto ExampleService::handle_action(Action const& action, util::Result* result) -> grpc::Status { result->mutable_success(); // success by default switch (action.action_case()) { case Action::kSendMessage: { auto const& new_message = action.send_message(); ChatMessage chat_message = {}; chat_message.mutable_id()->set_value(std::to_string(chat_message_ids_.size())); chat_message.set_value(new_message.message()); UserMessage user_message = {}; *user_message.mutable_client_id() = new_message.client_id(); *user_message.mutable_message_id() = chat_message.id(); chat_message_ids_.emplace_back(chat_message.id().value()); chat_message_data_.emplace(chat_message.id().value(), chat_message); user_message_data_.emplace(user_message.message_id().value(), user_message); } break; case Action::kChangeClientInfo: { result->mutable_error()->set_error_message("Action not yet supported"); } break; case Action::ACTION_NOT_SET: { result->mutable_error()->set_error_message("Action value not set properly by client"); } break; } // switch end return grpc::Status::OK; } } // namespace ltb::example
42.1875
96
0.673704
LoganBarnes
b49639dffa01b58fee555c345ad97ab301885327
2,887
cpp
C++
webkit/WebCore/storage/chromium/QuotaTracker.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
15
2016-01-05T12:43:41.000Z
2022-03-15T10:34:47.000Z
webkit/WebCore/storage/chromium/QuotaTracker.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
null
null
null
webkit/WebCore/storage/chromium/QuotaTracker.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
2
2020-11-30T18:36:01.000Z
2021-02-05T23:20:24.000Z
/* * 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 "config.h" #include "QuotaTracker.h" #include "CString.h" #include <wtf/StdLibExtras.h> namespace WebCore { QuotaTracker& QuotaTracker::instance() { DEFINE_STATIC_LOCAL(QuotaTracker, tracker, ()); return tracker; } void QuotaTracker::getDatabaseSizeAndSpaceAvailableToOrigin( const String& originIdentifier, const String& databaseName, unsigned long long* databaseSize, unsigned long long* spaceAvailable) { MutexLocker lockData(m_dataGuard); ASSERT(m_databaseSizes.contains(originIdentifier)); HashMap<String, SizeMap>::const_iterator it = m_databaseSizes.find(originIdentifier); ASSERT(it->second.contains(databaseName)); *databaseSize = it->second.get(databaseName); ASSERT(m_spaceAvailableToOrigins.contains(originIdentifier)); *spaceAvailable = m_spaceAvailableToOrigins.get(originIdentifier); } void QuotaTracker::updateDatabaseSizeAndSpaceAvailableToOrigin( const String& originIdentifier, const String& databaseName, unsigned long long databaseSize, unsigned long long spaceAvailable) { MutexLocker lockData(m_dataGuard); m_spaceAvailableToOrigins.set(originIdentifier, spaceAvailable); HashMap<String, SizeMap>::iterator it = m_databaseSizes.add(originIdentifier, SizeMap()).first; it->second.set(databaseName, databaseSize); } }
41.242857
99
0.771043
s1rcheese
b4991be7511f8ac143e2847fc043aef9bb1513e0
325
cpp
C++
src/memory.cpp
nick-valentine/Chip-8-Emulator
fff1e8f262e6ca7c1dde028da3db5e3e0dec0284
[ "MIT" ]
null
null
null
src/memory.cpp
nick-valentine/Chip-8-Emulator
fff1e8f262e6ca7c1dde028da3db5e3e0dec0284
[ "MIT" ]
null
null
null
src/memory.cpp
nick-valentine/Chip-8-Emulator
fff1e8f262e6ca7c1dde028da3db5e3e0dec0284
[ "MIT" ]
null
null
null
#include "memory.hpp" #include <cstdint> #include <cstdio> Memory::Memory(size_t size) : memory(size) {} void Memory::dump() { dump(0, memory.size()); } void Memory::dump(size_t low, size_t high) { for (size_t i = low; i < memory.size() && i < high; i++) { printf("mem[%#04x]=%#04x\n", (uint8_t)i, memory[i]); } }
23.214286
60
0.609231
nick-valentine
a330f59d2cfe1b59880fb34a6ce4a16bc73f4b7d
5,653
cpp
C++
SmartHydroponics/BMPFluidCalc.cpp
an0mali/SmartHydroponics
2c3d862174e6c6f7c00623496c33c98edc343063
[ "MIT" ]
1
2022-02-16T18:57:55.000Z
2022-02-16T18:57:55.000Z
SmartHydroponics/BMPFluidCalc.cpp
an0mali/SmartHydroponics
2c3d862174e6c6f7c00623496c33c98edc343063
[ "MIT" ]
null
null
null
SmartHydroponics/BMPFluidCalc.cpp
an0mali/SmartHydroponics
2c3d862174e6c6f7c00623496c33c98edc343063
[ "MIT" ]
null
null
null
#include "BMPFluidCalc.h" #include "ProgMemStr.h" #include "DualBMP.h" #include "PlantData.h" #include <Arduino.h> /*Liquid meter uses the pressure difference between the atmosphere and a water tower to * [precisely?] measure the amount of liquid remaining, and rate of loss, in a system over time. * This module should only interact with the sensors and get differential data, processing it into * meaningful fluid level information? */ const int hyperSamples = 8; //how many pressure samples to average out during calibration //float hyperSamples[hyperSamples]; const int emptyWait = 5;//60;// time in seconds to wait before calulating empty fluid levels const int fullWait = 5; // {mins, seconds} // These pressures should be mostly dependent on the container and should only need to be calibrated once, then reloaded. int32_t emptyPressure = 0.0; int32_t fullPressure;//4.2; float atmosChange = 0.0; float fluidLevel; int fluidLevelDiv = 0; //We're going to try to adjust pressure measurements by temp readouts in proportion to the calibraton temp, // since testing seems to show if directly proportional this could be affecting accuracy float curTemp; float calibTemp; float P0P1min; float ePressP1; float eRawPressP1; float FullPressP0; const PROGMEM char calibrateMes[] = "Enable pump, fill to LOW level. Press button to continue."; const PROGMEM char diffMes[] = "Calc. min pressure"; const PROGMEM char fillMes[] = "Fill to MAX then press button to continue."; const PROGMEM char maxPressMes[] = "Full pressure set to: "; const PROGMEM char calCompMes[] = "Calibration Completed."; const int buttonPin = 5; bool isCalib; bool newData; PlantData *pdata; BMPFluidCalc::BMPFluidCalc() { } float BMPFluidCalc::getDifferential() { //Updates sensors and reports pressure to system fluid level calculator dbmp.updateSensors(); float p0p1 = dbmp.rawP[0] - dbmp.rawP[1];//Differential pressure reading // float p0p1 = dbmp.P[0];//Differential pressure reading float aDiff = dbmp.rawP[1] - eRawPressP1; curTemp = dbmp.T[0]; // Serial.println("P0P1avg: " + String(fluidLevel) + "\tP0P1: " + String(p0p1) + "\tp1Diff: " + String(aDiff) + "\tp0Diff: " + String(pDiff0) + "\t"); fwefwfew p0p1 -= emptyPressure; // return p0p1; }; void BMPFluidCalc::inputPause() { while (true) { int buttonState = digitalRead(buttonPin); if (buttonState == LOW) { newData = false; break; }; delay(10); }; } void BMPFluidCalc::countdownTime(int minutes, int secs) { secs += minutes * 60; printData("Waiting " + String(secs) + " seconds."); for (int i = 0; i < secs; i++) { printData("-", false); delay(1000); }; } void BMPFluidCalc::init_fluidMeter(PlantData *plantdata) { //Set references, begin calibration if needed pdata = plantdata; pinMode(buttonPin, INPUT_PULLUP); calibrateFluidMeter(); } void BMPFluidCalc::calibrateFluidMeter() { calibrateMinLvl(); delay(50); isCalib = true; calibrateMaxLvl(); } void BMPFluidCalc::calibrateMinLvl() { //Fluid at mininum level and pump on before init BMP sensors String mes = ProgMemStr().getStr(calibrateMes);//Sends "Enable pump, fill to LOW..[etc] printData(mes); inputPause(); printData("!");//Tells LCD to clear screen countdownTime(0, emptyWait);//Wait emptyWait seconds for liquid to settle before beginging measurement dbmp.beginSense();//Tells BMP sensors to initialize printData("!");//clear LCD mes = ProgMemStr().getStr(diffMes); printData(mes);// Displays "Calc min pressure" //Get pressure differential readings at minimum fluid level and average them out float ePress = getHyperSample(true); emptyPressure = ePress; ePressP1 = dbmp.P[1]; eRawPressP1 = dbmp.rawP[1]; Serial.println("ePressP1: " + String(ePressP1) + " minP: " + String(ePress)); printData("!"); mes = "\nMin P is: " + String(emptyPressure) + "\n"; printData(mes); calibTemp = curTemp; } // Also begin averaging the external pressure reading during calibration float BMPFluidCalc::checkFluidLevel() { fluidLevel = getHyperSample(); }; void BMPFluidCalc::calibrateMaxLvl() { String mes = ProgMemStr().getStr(fillMes); printData(mes); inputPause(); printData("!"); countdownTime(0, fullWait);//wait min, sec for liquid to settle. Good @ 30, set to 10 for debug fullPressure = getHyperSample(true); printData("!"); mes = "Max P: " + String(fullPressure) + "\nCalibration Complete."; printData(mes); delay(1000); }; float BMPFluidCalc::getFluidLevel(bool resetAverage=false){ int pDiff0 = dbmp.P[0] - FullPressP0; int pDiff1 = dbmp.P[1] - ePressP1; float flevel = (fluidLevel) / (fullPressure); Serial.print("P0P1avg: " + String(fluidLevel) + "\tP0P1: " + String(dbmp.P[0] - dbmp.P[1]) + "\tp1Diff: " + String(pDiff1) + "\tp0Diff: " + String(pDiff0) + "\t"); return flevel; } float BMPFluidCalc::getHyperSample(bool verb=false, int samples=0) { float avgDiff = 0.0; if (samples == 0) { samples = hyperSamples; }; for (int i = 0; i < samples; i++) { float diff = getDifferential(); avgDiff += diff; if (verb == true) { printData(String(avgDiff / (i+1)) + ", ", false); }; }; avgDiff /= samples; return avgDiff; } void BMPFluidCalc::printData(String mes, bool endline=true, bool toserial=false) { //output to oled or serial, for debug/calibration. Handled by PlantData module pdata ->sendPData(mes, endline, true, toserial); }
31.581006
166
0.676632
an0mali
a330fa68bbd83754d99d95be498148c52bf6c80b
25,568
cpp
C++
trunk/src/app/srs_app_rtsp.cpp
daimaqiao/srs
f729bb9ac484a7ae452090e2583abb348385d2e9
[ "MIT" ]
2
2018-12-05T10:33:50.000Z
2019-08-25T13:31:48.000Z
trunk/src/app/srs_app_rtsp.cpp
darcy-shimmer/srs
14be74ca5ea8f1341900768984798cfdd12f759b
[ "MIT" ]
1
2019-04-28T00:50:59.000Z
2019-04-28T00:51:57.000Z
trunk/src/app/srs_app_rtsp.cpp
darcy-shimmer/srs
14be74ca5ea8f1341900768984798cfdd12f759b
[ "MIT" ]
2
2019-01-22T03:43:14.000Z
2022-01-21T06:06:32.000Z
/* The MIT License (MIT) Copyright (c) 2013-2015 SRS(ossrs) 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 <srs_app_rtsp.hpp> #include <algorithm> using namespace std; #include <srs_app_config.hpp> #include <srs_kernel_error.hpp> #include <srs_rtsp_stack.hpp> #include <srs_app_st.hpp> #include <srs_kernel_log.hpp> #include <srs_app_utility.hpp> #include <srs_core_autofree.hpp> #include <srs_kernel_stream.hpp> #include <srs_kernel_buffer.hpp> #include <srs_rtmp_stack.hpp> #include <srs_rtmp_amf0.hpp> #include <srs_rtmp_utility.hpp> #include <srs_kernel_utility.hpp> #include <srs_raw_avc.hpp> #include <srs_kernel_codec.hpp> #include <srs_app_pithy_print.hpp> #ifdef SRS_AUTO_STREAM_CASTER SrsRtpConn::SrsRtpConn(SrsRtspConn* r, int p, int sid) { rtsp = r; _port = p; stream_id = sid; // TODO: support listen at <[ip:]port> listener = new SrsUdpListener(this, "0.0.0.0", p); cache = new SrsRtpPacket(); pprint = SrsPithyPrint::create_caster(); } SrsRtpConn::~SrsRtpConn() { srs_freep(listener); srs_freep(cache); srs_freep(pprint); } int SrsRtpConn::port() { return _port; } int SrsRtpConn::listen() { return listener->listen(); } int SrsRtpConn::on_udp_packet(sockaddr_in* from, char* buf, int nb_buf) { int ret = ERROR_SUCCESS; pprint->elapse(); if (true) { SrsStream stream; if ((ret = stream.initialize(buf, nb_buf)) != ERROR_SUCCESS) { return ret; } SrsRtpPacket pkt; if ((ret = pkt.decode(&stream)) != ERROR_SUCCESS) { srs_error("rtsp: decode rtp packet failed. ret=%d", ret); return ret; } if (pkt.chunked) { if (!cache) { cache = new SrsRtpPacket(); } cache->copy(&pkt); cache->payload->append(pkt.payload->bytes(), pkt.payload->length()); if (!cache->completed && pprint->can_print()) { srs_trace("<- "SRS_CONSTS_LOG_STREAM_CASTER" rtsp: rtp chunked %dB, age=%d, vt=%d/%u, sts=%u/%#x/%#x, paylod=%dB", nb_buf, pprint->age(), cache->version, cache->payload_type, cache->sequence_number, cache->timestamp, cache->ssrc, cache->payload->length() ); return ret; } } else { srs_freep(cache); cache = new SrsRtpPacket(); cache->reap(&pkt); } } if (pprint->can_print()) { srs_trace("<- "SRS_CONSTS_LOG_STREAM_CASTER" rtsp: rtp #%d %dB, age=%d, vt=%d/%u, sts=%u/%u/%#x, paylod=%dB, chunked=%d", stream_id, nb_buf, pprint->age(), cache->version, cache->payload_type, cache->sequence_number, cache->timestamp, cache->ssrc, cache->payload->length(), cache->chunked ); } // always free it. SrsAutoFree(SrsRtpPacket, cache); if ((ret = rtsp->on_rtp_packet(cache, stream_id)) != ERROR_SUCCESS) { srs_error("rtsp: process rtp packet failed. ret=%d", ret); return ret; } return ret; } SrsRtspAudioCache::SrsRtspAudioCache() { dts = 0; audio_samples = NULL; payload = NULL; } SrsRtspAudioCache::~SrsRtspAudioCache() { srs_freep(audio_samples); srs_freep(payload); } SrsRtspJitter::SrsRtspJitter() { delta = 0; previous_timestamp = 0; pts = 0; } SrsRtspJitter::~SrsRtspJitter() { } int64_t SrsRtspJitter::timestamp() { return pts; } int SrsRtspJitter::correct(int64_t& ts) { int ret = ERROR_SUCCESS; if (previous_timestamp == 0) { previous_timestamp = ts; } delta = srs_max(0, ts - previous_timestamp); if (delta > 90000) { delta = 0; } previous_timestamp = ts; ts = pts + delta; pts = ts; return ret; } SrsRtspConn::SrsRtspConn(SrsRtspCaster* c, st_netfd_t fd, std::string o) { output_template = o; session = ""; video_rtp = NULL; audio_rtp = NULL; caster = c; stfd = fd; skt = new SrsStSocket(fd); rtsp = new SrsRtspStack(skt); trd = new SrsOneCycleThread("rtsp", this); req = NULL; io = NULL; client = NULL; stream_id = 0; vjitter = new SrsRtspJitter(); ajitter = new SrsRtspJitter(); avc = new SrsRawH264Stream(); aac = new SrsRawAacStream(); acodec = new SrsRawAacStreamCodec(); acache = new SrsRtspAudioCache(); } SrsRtspConn::~SrsRtspConn() { srs_close_stfd(stfd); srs_freep(video_rtp); srs_freep(audio_rtp); srs_freep(trd); srs_freep(skt); srs_freep(rtsp); srs_freep(client); srs_freep(io); srs_freep(req); srs_freep(vjitter); srs_freep(ajitter); srs_freep(acodec); srs_freep(acache); } int SrsRtspConn::serve() { return trd->start(); } int SrsRtspConn::do_cycle() { int ret = ERROR_SUCCESS; // retrieve ip of client. std::string ip = srs_get_peer_ip(st_netfd_fileno(stfd)); srs_trace("rtsp: serve %s", ip.c_str()); // consume all rtsp messages. for (;;) { SrsRtspRequest* req = NULL; if ((ret = rtsp->recv_message(&req)) != ERROR_SUCCESS) { if (!srs_is_client_gracefully_close(ret)) { srs_error("rtsp: recv request failed. ret=%d", ret); } return ret; } SrsAutoFree(SrsRtspRequest, req); srs_info("rtsp: got rtsp request"); if (req->is_options()) { SrsRtspOptionsResponse* res = new SrsRtspOptionsResponse(req->seq); res->session = session; if ((ret = rtsp->send_message(res)) != ERROR_SUCCESS) { if (!srs_is_client_gracefully_close(ret)) { srs_error("rtsp: send OPTIONS response failed. ret=%d", ret); } return ret; } } else if (req->is_announce()) { if (rtsp_tcUrl.empty()) { rtsp_tcUrl = req->uri; } size_t pos = string::npos; if ((pos = rtsp_tcUrl.rfind(".sdp")) != string::npos) { rtsp_tcUrl = rtsp_tcUrl.substr(0, pos); } if ((pos = rtsp_tcUrl.rfind("/")) != string::npos) { rtsp_stream = rtsp_tcUrl.substr(pos + 1); rtsp_tcUrl = rtsp_tcUrl.substr(0, pos); } srs_assert(req->sdp); video_id = ::atoi(req->sdp->video_stream_id.c_str()); audio_id = ::atoi(req->sdp->audio_stream_id.c_str()); video_codec = req->sdp->video_codec; audio_codec = req->sdp->audio_codec; audio_sample_rate = ::atoi(req->sdp->audio_sample_rate.c_str()); audio_channel = ::atoi(req->sdp->audio_channel.c_str()); h264_sps = req->sdp->video_sps; h264_pps = req->sdp->video_pps; aac_specific_config = req->sdp->audio_sh; srs_trace("rtsp: video(#%d, %s, %s/%s), audio(#%d, %s, %s/%s, %dHZ %dchannels), %s/%s", video_id, video_codec.c_str(), req->sdp->video_protocol.c_str(), req->sdp->video_transport_format.c_str(), audio_id, audio_codec.c_str(), req->sdp->audio_protocol.c_str(), req->sdp->audio_transport_format.c_str(), audio_sample_rate, audio_channel, rtsp_tcUrl.c_str(), rtsp_stream.c_str() ); SrsRtspResponse* res = new SrsRtspResponse(req->seq); res->session = session; if ((ret = rtsp->send_message(res)) != ERROR_SUCCESS) { if (!srs_is_client_gracefully_close(ret)) { srs_error("rtsp: send ANNOUNCE response failed. ret=%d", ret); } return ret; } } else if (req->is_setup()) { srs_assert(req->transport); int lpm = 0; if ((ret = caster->alloc_port(&lpm)) != ERROR_SUCCESS) { srs_error("rtsp: alloc port failed. ret=%d", ret); return ret; } SrsRtpConn* rtp = NULL; if (req->stream_id == video_id) { srs_freep(video_rtp); rtp = video_rtp = new SrsRtpConn(this, lpm, video_id); } else { srs_freep(audio_rtp); rtp = audio_rtp = new SrsRtpConn(this, lpm, audio_id); } if ((ret = rtp->listen()) != ERROR_SUCCESS) { srs_error("rtsp: rtp listen at port=%d failed. ret=%d", lpm, ret); return ret; } srs_trace("rtsp: #%d %s over %s/%s/%s %s client-port=%d-%d, server-port=%d-%d", req->stream_id, (req->stream_id == video_id)? "Video":"Audio", req->transport->transport.c_str(), req->transport->profile.c_str(), req->transport->lower_transport.c_str(), req->transport->cast_type.c_str(), req->transport->client_port_min, req->transport->client_port_max, lpm, lpm + 1 ); // create session. if (session.empty()) { session = "O9EaZ4bf"; // TODO: FIXME: generate session id. } SrsRtspSetupResponse* res = new SrsRtspSetupResponse(req->seq); res->client_port_min = req->transport->client_port_min; res->client_port_max = req->transport->client_port_max; res->local_port_min = lpm; res->local_port_max = lpm + 1; res->session = session; if ((ret = rtsp->send_message(res)) != ERROR_SUCCESS) { if (!srs_is_client_gracefully_close(ret)) { srs_error("rtsp: send SETUP response failed. ret=%d", ret); } return ret; } } else if (req->is_record()) { SrsRtspResponse* res = new SrsRtspResponse(req->seq); res->session = session; if ((ret = rtsp->send_message(res)) != ERROR_SUCCESS) { if (!srs_is_client_gracefully_close(ret)) { srs_error("rtsp: send SETUP response failed. ret=%d", ret); } return ret; } } } return ret; } int SrsRtspConn::on_rtp_packet(SrsRtpPacket* pkt, int stream_id) { int ret = ERROR_SUCCESS; // ensure rtmp connected. if ((ret = connect()) != ERROR_SUCCESS) { return ret; } if (stream_id == video_id) { // rtsp tbn is ts tbn. int64_t pts = pkt->timestamp; if ((ret = vjitter->correct(pts)) != ERROR_SUCCESS) { srs_error("rtsp: correct by jitter failed. ret=%d", ret); return ret; } // TODO: FIXME: set dts to pts, please finger out the right dts. int64_t dts = pts; return on_rtp_video(pkt, dts, pts); } else { // rtsp tbn is ts tbn. int64_t pts = pkt->timestamp; if ((ret = ajitter->correct(pts)) != ERROR_SUCCESS) { srs_error("rtsp: correct by jitter failed. ret=%d", ret); return ret; } return on_rtp_audio(pkt, pts); } return ret; } int SrsRtspConn::cycle() { // serve the rtsp client. int ret = do_cycle(); // if socket io error, set to closed. if (srs_is_client_gracefully_close(ret)) { ret = ERROR_SOCKET_CLOSED; } // success. if (ret == ERROR_SUCCESS) { srs_trace("client finished."); } // client close peer. if (ret == ERROR_SOCKET_CLOSED) { srs_warn("client disconnect peer. ret=%d", ret); } return ERROR_SUCCESS; } void SrsRtspConn::on_thread_stop() { if (video_rtp) { caster->free_port(video_rtp->port(), video_rtp->port() + 1); } if (audio_rtp) { caster->free_port(audio_rtp->port(), audio_rtp->port() + 1); } caster->remove(this); } int SrsRtspConn::on_rtp_video(SrsRtpPacket* pkt, int64_t dts, int64_t pts) { int ret = ERROR_SUCCESS; if ((ret = kickoff_audio_cache(pkt, dts)) != ERROR_SUCCESS) { return ret; } if ((ret = write_h264_ipb_frame(pkt->payload->bytes(), pkt->payload->length(), dts / 90, pts / 90)) != ERROR_SUCCESS) { return ret; } return ret; } int SrsRtspConn::on_rtp_audio(SrsRtpPacket* pkt, int64_t dts) { int ret = ERROR_SUCCESS; if ((ret = kickoff_audio_cache(pkt, dts)) != ERROR_SUCCESS) { return ret; } // cache current audio to kickoff. acache->dts = dts; acache->audio_samples = pkt->audio_samples; acache->payload = pkt->payload; pkt->audio_samples = NULL; pkt->payload = NULL; return ret; } int SrsRtspConn::kickoff_audio_cache(SrsRtpPacket* pkt, int64_t dts) { int ret = ERROR_SUCCESS; // nothing to kick off. if (!acache->payload) { return ret; } if (dts - acache->dts > 0 && acache->audio_samples->nb_sample_units > 0) { int64_t delta = (dts - acache->dts) / acache->audio_samples->nb_sample_units; for (int i = 0; i < acache->audio_samples->nb_sample_units; i++) { char* frame = acache->audio_samples->sample_units[i].bytes; int nb_frame = acache->audio_samples->sample_units[i].size; int64_t timestamp = (acache->dts + delta * i) / 90; acodec->aac_packet_type = 1; if ((ret = write_audio_raw_frame(frame, nb_frame, acodec, timestamp)) != ERROR_SUCCESS) { return ret; } } } acache->dts = 0; srs_freep(acache->audio_samples); srs_freep(acache->payload); return ret; } int SrsRtspConn::write_sequence_header() { int ret = ERROR_SUCCESS; // use the current dts. int64_t dts = vjitter->timestamp() / 90; // send video sps/pps if ((ret = write_h264_sps_pps(dts, dts)) != ERROR_SUCCESS) { return ret; } // generate audio sh by audio specific config. if (true) { std::string sh = aac_specific_config; SrsAvcAacCodec dec; if ((ret = dec.audio_aac_sequence_header_demux((char*)sh.c_str(), (int)sh.length())) != ERROR_SUCCESS) { return ret; } acodec->sound_format = SrsCodecAudioAAC; acodec->sound_type = (dec.aac_channels == 2)? SrsCodecAudioSoundTypeStereo : SrsCodecAudioSoundTypeMono; acodec->sound_size = SrsCodecAudioSampleSize16bit; acodec->aac_packet_type = 0; static int aac_sample_rates[] = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350, 0, 0, 0 }; switch (aac_sample_rates[dec.aac_sample_rate]) { case 11025: acodec->sound_rate = SrsCodecAudioSampleRate11025; break; case 22050: acodec->sound_rate = SrsCodecAudioSampleRate22050; break; case 44100: acodec->sound_rate = SrsCodecAudioSampleRate44100; break; default: break; }; if ((ret = write_audio_raw_frame((char*)sh.data(), (int)sh.length(), acodec, dts)) != ERROR_SUCCESS) { return ret; } } return ret; } int SrsRtspConn::write_h264_sps_pps(u_int32_t dts, u_int32_t pts) { int ret = ERROR_SUCCESS; // h264 raw to h264 packet. std::string sh; if ((ret = avc->mux_sequence_header(h264_sps, h264_pps, dts, pts, sh)) != ERROR_SUCCESS) { return ret; } // h264 packet to flv packet. int8_t frame_type = SrsCodecVideoAVCFrameKeyFrame; int8_t avc_packet_type = SrsCodecVideoAVCTypeSequenceHeader; char* flv = NULL; int nb_flv = 0; if ((ret = avc->mux_avc2flv(sh, frame_type, avc_packet_type, dts, pts, &flv, &nb_flv)) != ERROR_SUCCESS) { return ret; } // the timestamp in rtmp message header is dts. u_int32_t timestamp = dts; if ((ret = rtmp_write_packet(SrsCodecFlvTagVideo, timestamp, flv, nb_flv)) != ERROR_SUCCESS) { return ret; } return ret; } int SrsRtspConn::write_h264_ipb_frame(char* frame, int frame_size, u_int32_t dts, u_int32_t pts) { int ret = ERROR_SUCCESS; // 5bits, 7.3.1 NAL unit syntax, // H.264-AVC-ISO_IEC_14496-10.pdf, page 44. // 7: SPS, 8: PPS, 5: I Frame, 1: P Frame SrsAvcNaluType nal_unit_type = (SrsAvcNaluType)(frame[0] & 0x1f); // for IDR frame, the frame is keyframe. SrsCodecVideoAVCFrame frame_type = SrsCodecVideoAVCFrameInterFrame; if (nal_unit_type == SrsAvcNaluTypeIDR) { frame_type = SrsCodecVideoAVCFrameKeyFrame; } std::string ibp; if ((ret = avc->mux_ipb_frame(frame, frame_size, ibp)) != ERROR_SUCCESS) { return ret; } int8_t avc_packet_type = SrsCodecVideoAVCTypeNALU; char* flv = NULL; int nb_flv = 0; if ((ret = avc->mux_avc2flv(ibp, frame_type, avc_packet_type, dts, pts, &flv, &nb_flv)) != ERROR_SUCCESS) { return ret; } // the timestamp in rtmp message header is dts. u_int32_t timestamp = dts; return rtmp_write_packet(SrsCodecFlvTagVideo, timestamp, flv, nb_flv); } int SrsRtspConn::write_audio_raw_frame(char* frame, int frame_size, SrsRawAacStreamCodec* codec, u_int32_t dts) { int ret = ERROR_SUCCESS; char* data = NULL; int size = 0; if ((ret = aac->mux_aac2flv(frame, frame_size, codec, dts, &data, &size)) != ERROR_SUCCESS) { return ret; } return rtmp_write_packet(SrsCodecFlvTagAudio, dts, data, size); } int SrsRtspConn::rtmp_write_packet(char type, u_int32_t timestamp, char* data, int size) { int ret = ERROR_SUCCESS; SrsSharedPtrMessage* msg = NULL; if ((ret = srs_rtmp_create_msg(type, timestamp, data, size, stream_id, &msg)) != ERROR_SUCCESS) { srs_error("rtsp: create shared ptr msg failed. ret=%d", ret); return ret; } srs_assert(msg); // send out encoded msg. if ((ret = client->send_and_free_message(msg, stream_id)) != ERROR_SUCCESS) { return ret; } return ret; } // TODO: FIXME: merge all client code. int SrsRtspConn::connect() { int ret = ERROR_SUCCESS; // when ok, ignore. if (io || client) { return ret; } // parse uri if (!req) { req = new SrsRequest(); std::string schema, host, vhost, app, port, param; srs_discovery_tc_url(rtsp_tcUrl, schema, host, vhost, app, rtsp_stream, port, param); // generate output by template. std::string output = output_template; output = srs_string_replace(output, "[app]", app); output = srs_string_replace(output, "[stream]", rtsp_stream); size_t pos = string::npos; string uri = req->tcUrl = output; // tcUrl, stream if ((pos = uri.rfind("/")) != string::npos) { req->stream = uri.substr(pos + 1); req->tcUrl = uri = uri.substr(0, pos); } srs_discovery_tc_url(req->tcUrl, req->schema, req->host, req->vhost, req->app, req->stream, req->port, req->param); } // connect host. if ((ret = srs_socket_connect(req->host, ::atoi(req->port.c_str()), ST_UTIME_NO_TIMEOUT, &stfd)) != ERROR_SUCCESS) { srs_error("rtsp: connect server %s:%s failed. ret=%d", req->host.c_str(), req->port.c_str(), ret); return ret; } io = new SrsStSocket(stfd); client = new SrsRtmpClient(io); client->set_recv_timeout(SRS_CONSTS_RTMP_RECV_TIMEOUT_US); client->set_send_timeout(SRS_CONSTS_RTMP_SEND_TIMEOUT_US); // connect to vhost/app if ((ret = client->handshake()) != ERROR_SUCCESS) { srs_error("rtsp: handshake with server failed. ret=%d", ret); return ret; } if ((ret = connect_app(req->host, req->port)) != ERROR_SUCCESS) { srs_error("rtsp: connect with server failed. ret=%d", ret); return ret; } if ((ret = client->create_stream(stream_id)) != ERROR_SUCCESS) { srs_error("rtsp: connect with server failed, stream_id=%d. ret=%d", stream_id, ret); return ret; } // publish. if ((ret = client->publish(req->stream, stream_id)) != ERROR_SUCCESS) { srs_error("rtsp: publish failed, stream=%s, stream_id=%d. ret=%d", req->stream.c_str(), stream_id, ret); return ret; } return write_sequence_header(); } // TODO: FIXME: refine the connect_app. int SrsRtspConn::connect_app(string ep_server, string ep_port) { int ret = ERROR_SUCCESS; // args of request takes the srs info. if (req->args == NULL) { req->args = SrsAmf0Any::object(); } // notify server the edge identity, // @see https://github.com/ossrs/srs/issues/147 SrsAmf0Object* data = req->args; data->set("srs_sig", SrsAmf0Any::str(RTMP_SIG_SRS_KEY)); data->set("srs_server", SrsAmf0Any::str(RTMP_SIG_SRS_KEY" "RTMP_SIG_SRS_VERSION" ("RTMP_SIG_SRS_URL_SHORT")")); data->set("srs_license", SrsAmf0Any::str(RTMP_SIG_SRS_LICENSE)); data->set("srs_role", SrsAmf0Any::str(RTMP_SIG_SRS_ROLE)); data->set("srs_url", SrsAmf0Any::str(RTMP_SIG_SRS_URL)); data->set("srs_version", SrsAmf0Any::str(RTMP_SIG_SRS_VERSION)); data->set("srs_site", SrsAmf0Any::str(RTMP_SIG_SRS_WEB)); data->set("srs_email", SrsAmf0Any::str(RTMP_SIG_SRS_EMAIL)); data->set("srs_copyright", SrsAmf0Any::str(RTMP_SIG_SRS_COPYRIGHT)); data->set("srs_primary", SrsAmf0Any::str(RTMP_SIG_SRS_PRIMARY)); data->set("srs_authors", SrsAmf0Any::str(RTMP_SIG_SRS_AUTHROS)); // for edge to directly get the id of client. data->set("srs_pid", SrsAmf0Any::number(getpid())); data->set("srs_id", SrsAmf0Any::number(_srs_context->get_id())); // local ip of edge std::vector<std::string> ips = srs_get_local_ipv4_ips(); assert(_srs_config->get_stats_network() < (int)ips.size()); std::string local_ip = ips[_srs_config->get_stats_network()]; data->set("srs_server_ip", SrsAmf0Any::str(local_ip.c_str())); // generate the tcUrl std::string param = ""; std::string tc_url = srs_generate_tc_url(ep_server, req->vhost, req->app, ep_port, param); // upnode server identity will show in the connect_app of client. // @see https://github.com/ossrs/srs/issues/160 // the debug_srs_upnode is config in vhost and default to true. bool debug_srs_upnode = _srs_config->get_debug_srs_upnode(req->vhost); if ((ret = client->connect_app(req->app, tc_url, req, debug_srs_upnode)) != ERROR_SUCCESS) { srs_error("rtsp: connect with server failed, tcUrl=%s, dsu=%d. ret=%d", tc_url.c_str(), debug_srs_upnode, ret); return ret; } return ret; } SrsRtspCaster::SrsRtspCaster(SrsConfDirective* c) { // TODO: FIXME: support reload. output = _srs_config->get_stream_caster_output(c); local_port_min = _srs_config->get_stream_caster_rtp_port_min(c); local_port_max = _srs_config->get_stream_caster_rtp_port_max(c); } SrsRtspCaster::~SrsRtspCaster() { std::vector<SrsRtspConn*>::iterator it; for (it = clients.begin(); it != clients.end(); ++it) { SrsRtspConn* conn = *it; srs_freep(conn); } clients.clear(); used_ports.clear(); } int SrsRtspCaster::alloc_port(int* pport) { int ret = ERROR_SUCCESS; // use a pair of port. for (int i = local_port_min; i < local_port_max - 1; i += 2) { if (!used_ports[i]) { used_ports[i] = true; used_ports[i + 1] = true; *pport = i; break; } } srs_info("rtsp: alloc port=%d-%d", *pport, *pport + 1); return ret; } void SrsRtspCaster::free_port(int lpmin, int lpmax) { for (int i = lpmin; i < lpmax; i++) { used_ports[i] = false; } srs_trace("rtsp: free rtp port=%d-%d", lpmin, lpmax); } int SrsRtspCaster::on_tcp_client(st_netfd_t stfd) { int ret = ERROR_SUCCESS; SrsRtspConn* conn = new SrsRtspConn(this, stfd, output); if ((ret = conn->serve()) != ERROR_SUCCESS) { srs_error("rtsp: serve client failed. ret=%d", ret); srs_freep(conn); return ret; } clients.push_back(conn); srs_info("rtsp: start thread to serve client."); return ret; } void SrsRtspCaster::remove(SrsRtspConn* conn) { std::vector<SrsRtspConn*>::iterator it = find(clients.begin(), clients.end(), conn); if (it != clients.end()) { clients.erase(it); } srs_info("rtsp: remove connection from caster."); srs_freep(conn); } #endif
30.438095
138
0.601259
daimaqiao
a33357029f9bd0a8d3306639cf5eeac92dfabff3
499
cc
C++
source/common/http/http1/header_formatter.cc
jaricftw/envoy
766f3fb8dbdafce402631c43c16fda46ed003462
[ "Apache-2.0" ]
1
2019-11-19T22:27:58.000Z
2019-11-19T22:27:58.000Z
source/common/http/http1/header_formatter.cc
jaricftw/envoy
766f3fb8dbdafce402631c43c16fda46ed003462
[ "Apache-2.0" ]
1
2019-01-04T08:20:24.000Z
2019-01-04T08:20:24.000Z
source/common/http/http1/header_formatter.cc
jaricftw/envoy
766f3fb8dbdafce402631c43c16fda46ed003462
[ "Apache-2.0" ]
1
2019-11-03T03:46:51.000Z
2019-11-03T03:46:51.000Z
#include "common/http/http1/header_formatter.h" namespace Envoy { namespace Http { namespace Http1 { std::string ProperCaseHeaderKeyFormatter::format(absl::string_view key) const { auto copy = std::string(key); bool should_capitalize = true; for (char& c : copy) { if (should_capitalize && isalpha(c)) { c = static_cast<char>(toupper(c)); } should_capitalize = !isalpha(c) && !isdigit(c); } return copy; } } // namespace Http1 } // namespace Http } // namespace Envoy
22.681818
79
0.677355
jaricftw
a33395f41dad86694dbc7ef36831fdf8dacb5a12
3,074
cpp
C++
src/coreclr/src/debug/createdump/threadinfomac.cpp
swaroop-sridhar/runtime
d0efddd932f6fb94c3e9436ab393fc390c7b2da9
[ "MIT" ]
11
2021-10-21T07:56:23.000Z
2022-03-31T15:08:10.000Z
src/coreclr/src/debug/createdump/threadinfomac.cpp
swaroop-sridhar/runtime
d0efddd932f6fb94c3e9436ab393fc390c7b2da9
[ "MIT" ]
1
2021-11-23T11:04:19.000Z
2021-12-21T06:41:19.000Z
src/coreclr/src/debug/createdump/threadinfomac.cpp
swaroop-sridhar/runtime
d0efddd932f6fb94c3e9436ab393fc390c7b2da9
[ "MIT" ]
2
2021-05-17T22:12:46.000Z
2021-05-19T06:21:16.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "createdump.h" ThreadInfo::ThreadInfo(CrashInfo& crashInfo, pid_t tid, mach_port_t port) : m_crashInfo(crashInfo), m_tid(tid), m_port(port) { } ThreadInfo::~ThreadInfo() { kern_return_t result = ::mach_port_deallocate(mach_task_self(), m_port); if (result != KERN_SUCCESS) { fprintf(stderr, "~ThreadInfo: mach_port_deallocate FAILED %x %s\n", result, mach_error_string(result)); } } bool ThreadInfo::Initialize() { m_ppid = 0; m_tgid = 0; x86_thread_state64_t state; mach_msg_type_number_t stateCount = x86_THREAD_STATE64_COUNT; kern_return_t result = ::thread_get_state(Port(), x86_THREAD_STATE64, (thread_state_t)&state, &stateCount); if (result != KERN_SUCCESS) { fprintf(stderr, "thread_get_state(%x) FAILED %x %s\n", m_tid, result, mach_error_string(result)); return false; } m_gpRegisters.rbp = state.__rbp; m_gpRegisters.rip = state.__rip; m_gpRegisters.cs = state.__cs; m_gpRegisters.eflags = state.__rflags; m_gpRegisters.ss = 0; m_gpRegisters.rsp = state.__rsp; m_gpRegisters.rdi = state.__rdi; m_gpRegisters.rsi = state.__rsi; m_gpRegisters.rbx = state.__rbx; m_gpRegisters.rdx = state.__rdx; m_gpRegisters.rcx = state.__rcx; m_gpRegisters.rax = state.__rax; m_gpRegisters.orig_rax = state.__rax; m_gpRegisters.r8 = state.__r8; m_gpRegisters.r9 = state.__r9; m_gpRegisters.r10 = state.__r10; m_gpRegisters.r11 = state.__r11; m_gpRegisters.r12 = state.__r12; m_gpRegisters.r13 = state.__r13; m_gpRegisters.r14 = state.__r14; m_gpRegisters.r15 = state.__r15; m_gpRegisters.fs = state.__fs; m_gpRegisters.gs = state.__gs; m_gpRegisters.ds = 0; m_gpRegisters.es = 0; m_gpRegisters.gs_base = 0; m_gpRegisters.fs_base = 0; x86_float_state64_t fpstate; stateCount = x86_FLOAT_STATE64_COUNT; result = ::thread_get_state(Port(), x86_FLOAT_STATE64, (thread_state_t)&fpstate, &stateCount); if (result != KERN_SUCCESS) { fprintf(stderr, "thread_get_state(%x) FAILED %x %s\n", m_tid, result, mach_error_string(result)); return false; } m_fpRegisters.cwd = *((unsigned short *)&fpstate.__fpu_fcw); m_fpRegisters.swd = *((unsigned short *)&fpstate.__fpu_fsw); m_fpRegisters.ftw = fpstate.__fpu_ftw; m_fpRegisters.fop = fpstate.__fpu_fop; FPREG_ErrorOffset(m_fpRegisters) = fpstate.__fpu_ip; FPREG_ErrorSelector(m_fpRegisters) = fpstate.__fpu_cs; FPREG_DataOffset(m_fpRegisters) = fpstate.__fpu_dp; FPREG_DataSelector(m_fpRegisters) = fpstate.__fpu_ds; m_fpRegisters.mxcsr = fpstate.__fpu_mxcsr; m_fpRegisters.mxcr_mask = fpstate.__fpu_mxcsrmask; memcpy(m_fpRegisters.st_space, &fpstate.__fpu_stmm0, sizeof(m_fpRegisters.st_space)); memcpy(m_fpRegisters.xmm_space, &fpstate.__fpu_xmm0, sizeof(m_fpRegisters.xmm_space)); return true; }
32.702128
111
0.709824
swaroop-sridhar
a3367252977c3b0d471760e8ba33c873a4f1d02d
1,368
hpp
C++
sources/vggrab/grabber.hpp
SimonsRoad/seq2map
cc8cd20842b3c6db01f73d2e6ecf543189e56891
[ "BSD-3-Clause" ]
null
null
null
sources/vggrab/grabber.hpp
SimonsRoad/seq2map
cc8cd20842b3c6db01f73d2e6ecf543189e56891
[ "BSD-3-Clause" ]
null
null
null
sources/vggrab/grabber.hpp
SimonsRoad/seq2map
cc8cd20842b3c6db01f73d2e6ecf543189e56891
[ "BSD-3-Clause" ]
1
2018-11-01T13:11:39.000Z
2018-11-01T13:11:39.000Z
#ifndef GRABBER_HPP #define GRABBER_HPP #include "syncbuf.hpp" class ImageGrabber : public BufferWriter, public Indexed { public: typedef boost::shared_ptr<ImageGrabber> Ptr; typedef std::vector<Ptr> Ptrs; ImageGrabber(const SyncBuffer::Ptr& buffer) : BufferWriter(buffer) {} virtual ~ImageGrabber() {} virtual std::string ToString() const = 0; virtual cv::Mat GetImage(); inline cv::Size GetImageSize() const { return m_image.size(); } protected: virtual bool GetImageInfo(cv::Size& imageSize, int& type) const = 0; inline virtual TimedImage& Pick(BufferData& data) const { return data.images[GetIndex()]; } virtual bool Grab(cv::Mat& im) = 0; virtual bool IsOkay() const = 0; virtual bool GrabNextData(); virtual size_t Write(BufferData& data); private: boost::mutex m_mtx; cv::Mat m_image; }; class ImageGrabberBuilder { public: typedef boost::shared_ptr<ImageGrabberBuilder> Ptr; virtual ImageGrabber::Ptr Build(const SyncBuffer::Ptr& buffer, size_t index) = 0; virtual size_t GetDevices() const = 0; virtual Strings GetDeviceIdList() const = 0; protected: ImageGrabberBuilder() {} virtual ~ImageGrabberBuilder() {} }; class ImageGrabberBuilderFactory : public Factory<String, ImageGrabberBuilder> { public: ImageGrabberBuilderFactory(); }; #endif // GRABBER_HPP
27.36
95
0.709795
SimonsRoad
a337bb4ad63f289cac5d817e7732aebbf63b3abf
4,057
cxx
C++
src/lcd/ssd1308.cxx
Wyliodrin/upm
5aa09c5fcaafd5d6a05b63c7b7760d30c7acf33f
[ "MIT" ]
1
2015-02-06T19:23:12.000Z
2015-02-06T19:23:12.000Z
src/lcd/ssd1308.cxx
Wyliodrin/upm
5aa09c5fcaafd5d6a05b63c7b7760d30c7acf33f
[ "MIT" ]
null
null
null
src/lcd/ssd1308.cxx
Wyliodrin/upm
5aa09c5fcaafd5d6a05b63c7b7760d30c7acf33f
[ "MIT" ]
null
null
null
/* * Author: Yevgeniy Kiveisha <yevgeniy.kiveisha@intel.com> * Copyright (c) 2014 Intel Corporation. * * 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 <string> #include <unistd.h> #include "ssd1308.h" using namespace upm; SSD1308::SSD1308 (int bus_in, int addr_in) : I2CLcd (bus_in, addr_in) { i2Cmd (m_i2c_lcd_control, DISPLAY_CMD_OFF); // display off printf ("NO_GDB :: DISPLAY_CMD_OFF \n"); usleep (4500); i2Cmd (m_i2c_lcd_control, DISPLAY_CMD_ON); // display on usleep (4500); setNormalDisplay (); // set to normal display '1' is ON clear (); setAddressingMode (PAGE); } SSD1308::~SSD1308 () { } mraa_result_t SSD1308::draw (uint8_t *data, int bytes) { mraa_result_t error = MRAA_SUCCESS; setAddressingMode (HORIZONTAL); for (int idx = 0; idx < bytes; idx++) { i2cData (m_i2c_lcd_control, data[idx]); } return error; } /* * ************** * virtual area * ************** */ mraa_result_t SSD1308::write (std::string msg) { mraa_result_t error = MRAA_SUCCESS; uint8_t data[2] = {0x40, 0}; setAddressingMode (PAGE); for (std::string::size_type i = 0; i < msg.size(); ++i) { writeChar (m_i2c_lcd_control, msg[i]); } return error; } mraa_result_t SSD1308::setCursor (int row, int column) { mraa_result_t error = MRAA_SUCCESS; error = i2Cmd (m_i2c_lcd_control, BASE_PAGE_START_ADDR + row); // set page address error = i2Cmd (m_i2c_lcd_control, BASE_LOW_COLUMN_ADDR + (8 * column & 0x0F)); // set column lower address error = i2Cmd (m_i2c_lcd_control, BASE_HIGH_COLUMN_ADDR + ((8 * column >> 4) & 0x0F)); // set column higher address return error; } mraa_result_t SSD1308::clear () { mraa_result_t error = MRAA_SUCCESS; uint8_t columnIdx, rowIdx; i2Cmd (m_i2c_lcd_control, DISPLAY_CMD_OFF); // display off for(rowIdx = 0; rowIdx < 8; rowIdx++) { setCursor (rowIdx, 0); // clear all columns for(columnIdx = 0; columnIdx < 16; columnIdx++) { writeChar (m_i2c_lcd_control, ' '); } } i2Cmd (m_i2c_lcd_control, DISPLAY_CMD_ON); // display on home (); return MRAA_SUCCESS; } mraa_result_t SSD1308::home () { return setCursor (0, 0); } /* * ************** * private area * ************** */ mraa_result_t SSD1308::writeChar (mraa_i2c_context ctx, uint8_t value) { if (value < 0x20 || value > 0x7F) { value = 0x20; // space } for (uint8_t idx = 0; idx < 8; idx++) { i2cData (m_i2c_lcd_control, BasicFont[value - 32][idx]); } } mraa_result_t SSD1308::setNormalDisplay () { return i2Cmd (m_i2c_lcd_control, DISPLAY_CMD_SET_NORMAL_1308); // set to normal display '1' is ON } mraa_result_t SSD1308::setAddressingMode (displayAddressingMode mode) { i2Cmd (m_i2c_lcd_control, DISPLAY_CMD_MEM_ADDR_MODE); //set addressing mode i2Cmd (m_i2c_lcd_control, mode); //set page addressing mode }
28.978571
121
0.664284
Wyliodrin
a3384c1250b4d752caa1905fc15ad8fa48a4a9b4
8,567
cc
C++
dcmtk-master2/dcmfg/tests/t_deriv_image.cc
happymanx/Weather_FFI
a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f
[ "MIT" ]
null
null
null
dcmtk-master2/dcmfg/tests/t_deriv_image.cc
happymanx/Weather_FFI
a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f
[ "MIT" ]
null
null
null
dcmtk-master2/dcmfg/tests/t_deriv_image.cc
happymanx/Weather_FFI
a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f
[ "MIT" ]
null
null
null
/* * * Copyright (C) 2019-2020, OFFIS e.V. * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation were developed by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmfg * * Author: Michael Onken * * Purpose: Tests for Derivation Image FG class * */ #include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */ #include "dcmtk/dcmfg/fgderimg.h" #include "dcmtk/dcmfg/fginterface.h" #include "dcmtk/ofstd/oftest.h" static void init_template(OFString& fg_dump) { fg_dump = "(fffe,e000) na (Item with explicit length #=1) # 0, 1 Item\n"; fg_dump += "(0008,9124) SQ (Sequence with explicit length #=1) # 0, 1 DerivationImageSequence\n"; fg_dump += " (fffe,e000) na (Item with explicit length #=3) # 0, 1 Item\n"; fg_dump += " (0008,2111) ST [Some Description] # 16, 1 DerivationDescription\n"; fg_dump += " (0008,2112) SQ (Sequence with explicit length #=1) # 0, 1 SourceImageSequence\n"; fg_dump += " (fffe,e000) na (Item with explicit length #=5) # 0, 1 Item\n"; fg_dump += " (0008,1150) UI =CTImageStorage # 26, 1 ReferencedSOPClassUID\n"; fg_dump += " (0008,1155) UI [1.2.3.4] # 8, 1 ReferencedSOPInstanceUID\n"; fg_dump += " (0008,1160) IS [1\\2] # 4, 2 ReferencedFrameNumber\n"; fg_dump += " (0040,a170) SQ (Sequence with explicit length #=1) # 0, 1 PurposeOfReferenceCodeSequence\n"; fg_dump += " (fffe,e000) na (Item with explicit length #=3) # 0, 1 Item\n"; fg_dump += " (0008,0100) SH [PURPOSE CODE] # 12, 1 CodeValue\n"; fg_dump += " (0008,0102) SH [99DCMFG] # 8, 1 CodingSchemeDesignator\n"; fg_dump += " (0008,0104) LO [Code Meaning Purpose] # 20, 1 CodeMeaning\n"; fg_dump += " (fffe,e00d) na (ItemDelimitationItem for re-encoding) # 0, 0 ItemDelimitationItem\n"; fg_dump += " (fffe,e0dd) na (SequenceDelimitationItem for re-encod.) # 0, 0 SequenceDelimitationItem\n"; fg_dump += " (0062,000b) US 3\\4 # 4, 2 ReferencedSegmentNumber\n"; fg_dump += " (fffe,e00d) na (ItemDelimitationItem for re-encoding) # 0, 0 ItemDelimitationItem\n"; fg_dump += " (fffe,e0dd) na (SequenceDelimitationItem for re-encod.) # 0, 0 SequenceDelimitationItem\n"; fg_dump += " (0008,9215) SQ (Sequence with explicit length #=1) # 0, 1 DerivationCodeSequence\n"; fg_dump += " (fffe,e000) na (Item with explicit length #=3) # 0, 1 Item\n"; fg_dump += " (0008,0100) SH [CODE_VALUE] # 10, 1 CodeValue\n"; fg_dump += " (0008,0102) SH [99DCMFG] # 8, 1 CodingSchemeDesignator\n"; fg_dump += " (0008,0104) LO [Code Meaning Derivation Description] # 36, 1 CodeMeaning\n"; fg_dump += " (fffe,e00d) na (ItemDelimitationItem for re-encoding) # 0, 0 ItemDelimitationItem\n"; fg_dump += " (fffe,e0dd) na (SequenceDelimitationItem for re-encod.) # 0, 0 SequenceDelimitationItem\n"; fg_dump += " (fffe,e00d) na (ItemDelimitationItem for re-encoding) # 0, 0 ItemDelimitationItem\n"; fg_dump += "(fffe,e0dd) na (SequenceDelimitationItem for re-encod.) # 0, 0 SequenceDelimitationItem\n"; fg_dump += "(fffe,e00d) na (ItemDelimitationItem for re-encoding) # 0, 0 ItemDelimitationItem\n"; } static void check_deriv_image_fg(FGDerivationImage& fg) { OFVector<DerivationImageItem*> deriv_img_items = fg.getDerivationImageItems(); OFCHECK(deriv_img_items.size() == 1); if (deriv_img_items.size() == 0) return; OFVector<CodeSequenceMacro*>& deriv_code_items = deriv_img_items[0]->getDerivationCodeItems(); OFCHECK(deriv_code_items.size() == 1); if (deriv_code_items.size() == 0) return; CodeSequenceMacro* code_item = deriv_code_items[0]; OFString str; code_item->getCodeValue(str); OFCHECK(str == "CODE_VALUE"); code_item->getCodingSchemeDesignator(str); OFCHECK(str == "99DCMFG"); code_item->getCodeMeaning(str); OFCHECK(str == "Code Meaning Derivation Description"); DerivationImageItem* deriv_item = deriv_img_items[0]; OFCHECK(deriv_item->getSourceImageItems().size() == 1); OFVector<Uint16> numbers; deriv_item->getSourceImageItems()[0]->getImageSOPInstanceReference().getReferencedFrameNumber(numbers); OFCHECK(numbers.size() == 2); OFCHECK(numbers[0] == 1); OFCHECK(numbers[1] == 2); numbers.clear(); deriv_item->getSourceImageItems()[0]->getImageSOPInstanceReference().getReferencedSegmentNumber(numbers); OFCHECK(numbers.size() == 2); OFCHECK(numbers[0] == 3); OFCHECK(numbers[1] == 4); deriv_item->getSourceImageItems()[0]->getImageSOPInstanceReference().getReferencedSOPClassUID(str); OFCHECK(str == UID_CTImageStorage); deriv_item->getSourceImageItems()[0]->getImageSOPInstanceReference().getReferencedSOPInstanceUID(str); OFCHECK(str == "1.2.3.4"); CodeSequenceMacro& code = deriv_item->getSourceImageItems()[0]->getPurposeOfReferenceCode(); code.getCodeValue(str); OFCHECK(str == "PURPOSE CODE"); code.getCodingSchemeDesignator(str); OFCHECK(str == "99DCMFG"); code.getCodeMeaning(str); OFCHECK(str == "Code Meaning Purpose"); } OFTEST(dcmfg_derivation_image) { // Make sure data dictionary is loaded if (!dcmDataDict.isDictionaryLoaded()) { OFCHECK_FAIL("no data dictionary loaded, check environment variable: " DCM_DICT_ENVIRONMENT_VARIABLE); return; } OFString fg_dump; init_template(fg_dump); FGDerivationImage fg; CodeSequenceMacro deriv_code("CODE_VALUE", "99DCMFG", "Code Meaning Derivation Description"); DerivationImageItem* deriv_item = NULL; OFCondition result = fg.addDerivationImageItem(deriv_code, "Some Description", deriv_item); OFCHECK(result.good()); OFCHECK(deriv_item != NULL); if (result.bad() || !deriv_item) return; SourceImageItem* src_image_item = new SourceImageItem(); OFCHECK(src_image_item != NULL); if (!deriv_item) return; OFCHECK(src_image_item->getImageSOPInstanceReference().addReferencedFrameNumber(1).good()); OFCHECK(src_image_item->getImageSOPInstanceReference().addReferencedFrameNumber(2).good()); OFCHECK(src_image_item->getImageSOPInstanceReference().addReferencedSegmentNumber(3).good()); OFCHECK(src_image_item->getImageSOPInstanceReference().addReferencedSegmentNumber(4).good()); OFCHECK(src_image_item->getImageSOPInstanceReference().setReferencedSOPInstanceUID("1.2.3.4").good()); OFCHECK(src_image_item->getImageSOPInstanceReference().setReferencedSOPClassUID(UID_CTImageStorage).good()); OFCHECK(src_image_item->getPurposeOfReferenceCode().set("PURPOSE CODE", "99DCMFG", "Code Meaning Purpose").good()); OFVector<SourceImageItem*>& src_image_items = deriv_item->getSourceImageItems(); src_image_items.push_back(src_image_item); // Check data structure in memory check_deriv_image_fg(fg); // Write to DcmItem and compare with pre-defined template DcmItem dest_item; result = fg.write(dest_item); OFCHECK(result.good()); OFStringStream out; dest_item.print(out); OFCHECK(out.str() == fg_dump.c_str()); // Test read method: Read from dataset, write again, and compare another time FGDerivationImage fg_for_read; out.str(""); // set to empty fg_for_read.read(dest_item); dest_item.clear(); result = fg_for_read.write(dest_item); OFCHECK(result.good()); if (result.bad()) return; dest_item.print(out); OFCHECK(out.str() == fg_dump.c_str()); // Test compare() method OFCHECK(fg.compare(fg_for_read) == 0); fg_for_read.getDerivationImageItems()[0]->setDerivationDescription("Another Description"); OFCHECK(fg.compare(fg_for_read) != 0); // Test clone() method FGDerivationImage* clone = OFstatic_cast(FGDerivationImage*, fg.clone()); OFCHECK(clone != NULL); if (clone == NULL) return; OFCHECK(clone->compare(fg) == 0); delete clone; }
48.129213
119
0.646317
happymanx
a33da221d284643b9a07f8d6988fd1ee724e6ba4
3,031
hpp
C++
Day2.hpp
pauwell/Advent-Of-Code-2017
0d334f70b1a9b183ff5be9f4317c3bbaec7919ac
[ "MIT" ]
null
null
null
Day2.hpp
pauwell/Advent-Of-Code-2017
0d334f70b1a9b183ff5be9f4317c3bbaec7919ac
[ "MIT" ]
null
null
null
Day2.hpp
pauwell/Advent-Of-Code-2017
0d334f70b1a9b183ff5be9f4317c3bbaec7919ac
[ "MIT" ]
null
null
null
/** --- AoC 2017 --- --- Day 2: Corruption Checksum --- http://adventofcode.com/2017/day/2 ------------------------------------------------------------------------------------------------------------- Part 1: The spreadsheet consists of rows of apparently-random numbers. To make sure the recovery process is on the right track, they need you to calculate the spreadsheet's checksum. For each row, determine the difference between the largest value and the smallest value; the checksum is the sum of all of these differences. For example, given the following spreadsheet: 5 1 9 5 7 5 3 2 4 6 8 The first row's largest and smallest values are 9 and 1, and their difference is 8. The second row's largest and smallest values are 7 and 3, and their difference is 4. The third row's difference is 6. In this example, the spreadsheet's checksum would be 8 + 4 + 6 = 18. ------------------------------------------------------------------------------------------------------------- Part 2: It sounds like the goal is to find the only two numbers in each row where one evenly divides the other - that is, where the result of the division operation is a whole number. They would like you to find those numbers on each line, divide them, and add up each line's result. For example, given the following spreadsheet: 5 9 2 8 9 4 7 3 3 8 6 5 In the first row, the only two numbers that evenly divide are 8 and 2; the result of this division is 4. In the second row, the two numbers are 9 and 3; the result is 3. In the third row, the result is 2. In this example, the sum of the results would be 4 + 3 + 2 = 9. */ #pragma once #include <iostream> #include <fstream> #include <vector> void day2() { std::vector<int> input; // Read the input from file. { std::ifstream ifs("input_day2.txt"); int num; while(ifs >> num) input.push_back(num); } // Get the length of each row and column. const unsigned SZ = std::sqrt((float)input.size()); // == Part 1 ================================================================================== { int totalSum = 0; for(unsigned y=0; y<SZ; ++y) { int max = input[y * SZ]; int min = max; for(unsigned x=0; x<SZ; ++x) { const int NUM = input[y * SZ + x]; if(NUM > max) max = NUM; if(NUM < min) min = NUM; } totalSum += (max-min); } std::cout << "Part 1 sum: " << totalSum << std::endl; // Correct result: 36174 } // == Part 2 ================================================================================== { int totalSum = 0; for(unsigned y=0; y<SZ; ++y) { for(unsigned x=0; x<SZ; ++x) { int numerator = input[y * SZ + x]; for(unsigned ix=0; ix<SZ; ++ix) { int denominator = input[y * SZ + ix]; if(numerator > denominator && numerator % denominator == 0) totalSum += (numerator / denominator); } } } std::cout << "Part 2 sum: " << totalSum << std::endl; // Correct result: 244 } }
30.009901
121
0.553283
pauwell
a33da6d36b55415f64977fedd1e8522918a8c78e
1,170
cpp
C++
GSLAM/plugins/gmap/main.cpp
qistout/GSLAM
0dc339faffed1c17efa3ddb1da63442b53ec4618
[ "BSD-2-Clause" ]
875
2016-09-19T01:35:56.000Z
2022-03-28T09:12:00.000Z
GSLAM/plugins/gmap/main.cpp
bhsphd/GSLAM
a2139d1c52ad70c282bc950b51876a0b0ba019e0
[ "BSD-2-Clause" ]
40
2017-08-01T02:32:35.000Z
2021-05-31T13:45:59.000Z
GSLAM/plugins/gmap/main.cpp
bhsphd/GSLAM
a2139d1c52ad70c282bc950b51876a0b0ba019e0
[ "BSD-2-Clause" ]
259
2016-08-20T14:54:09.000Z
2022-03-09T06:18:05.000Z
#include "MapHash.h" using namespace GSLAM; int run(Svar config){ std::string in =config.arg<std::string>("in","","the map to load"); std::string out=config.arg<std::string>("out","","the map file to save"); std::string map=config.arg<std::string>("map","map","the map topic to publish or subscribe"); Publisher pub=messenger.advertise<MapPtr>(map); Subscriber sub=messenger.subscribe(map,[out](MapPtr mp){ if(out.size()) mp->save(out); }); Subscriber subOpen=messenger.subscribe("qviz/open",1,[&](std::string file){ if(file.find(".gmap")==std::string::npos) return; MapPtr mapHash(new MapHash()); mapHash->load(file); pub.publish(Svar::create(mapHash)); }); if(config.get("help",false)){ config["__usage__"]=messenger.introduction(); return config.help(); } auto sub_request=messenger.subscribe("qviz/ready",[&](bool){ if(in.size()){ MapPtr mapHash(new MapHash()); mapHash->load(in); pub.publish(Svar::create(mapHash)); } }); return Messenger::exec(); } GSLAM_REGISTER_APPLICATION(gmap,run);
29.25
97
0.604274
qistout
a33dc5af8c61c21a8f804a79d17d309f8d76b407
1,453
hpp
C++
ReactNativeFrontend/ios/Pods/boost/boost/hana/fwd/is_empty.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
ReactNativeFrontend/ios/Pods/boost/boost/hana/fwd/is_empty.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
ReactNativeFrontend/ios/Pods/boost/boost/hana/fwd/is_empty.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
/*! @file Forward declares `boost::hana::is_empty`. @copyright Louis Dionne 2013-2017 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_HANA_FWD_IS_EMPTY_HPP #define BOOST_HANA_FWD_IS_EMPTY_HPP #include <boost/hana/config.hpp> #include <boost/hana/core/when.hpp> BOOST_HANA_NAMESPACE_BEGIN //! Returns whether the iterable is empty. //! @ingroup group-Iterable //! //! Given an `Iterable` `xs`, `is_empty` returns whether `xs` contains //! no more elements. In other words, it returns whether trying to //! extract the tail of `xs` would be an error. In the current version //! of the library, `is_empty` must return an `IntegralConstant` holding //! a value convertible to `bool`. This is because only compile-time //! `Iterable`s are supported right now. //! //! //! Example //! ------- //! @include example/is_empty.cpp #ifdef BOOST_HANA_DOXYGEN_INVOKED constexpr auto is_empty = [](auto const& xs) { return tag-dispatched; }; #else template <typename It, typename = void> struct is_empty_impl : is_empty_impl<It, when<true>> { }; struct is_empty_t { template <typename Xs> constexpr auto operator()(Xs const& xs) const; }; constexpr is_empty_t is_empty{}; #endif BOOST_HANA_NAMESPACE_END #endif // !BOOST_HANA_FWD_IS_EMPTY_HPP
29.06
78
0.689608
Harshitha91
a33e38d585cde1ecb634f89cb3c7a20905c1c274
2,829
hpp
C++
include/codegen/include/GlobalNamespace/NoteBasicCutInfo.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/GlobalNamespace/NoteBasicCutInfo.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/GlobalNamespace/NoteBasicCutInfo.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Single #include "System/Single.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Transform class Transform; // Forward declaring type: Vector3 struct Vector3; } // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: NoteType struct NoteType; // Forward declaring type: NoteCutDirection struct NoteCutDirection; // Forward declaring type: SaberType struct SaberType; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Autogenerated type: NoteBasicCutInfo class NoteBasicCutInfo : public ::Il2CppObject { public: // static field const value: static private System.Single kCutAngleTolerance static constexpr const float kCutAngleTolerance = 60; // Get static field: static private System.Single kCutAngleTolerance static float _get_kCutAngleTolerance(); // Set static field: static private System.Single kCutAngleTolerance static void _set_kCutAngleTolerance(float value); // static field const value: static private System.Single kMinBladeSpeedForCut static constexpr const float kMinBladeSpeedForCut = 2; // Get static field: static private System.Single kMinBladeSpeedForCut static float _get_kMinBladeSpeedForCut(); // Set static field: static private System.Single kMinBladeSpeedForCut static void _set_kMinBladeSpeedForCut(float value); // static public System.Void GetBasicCutInfo(UnityEngine.Transform noteTransform, NoteType noteType, NoteCutDirection cutDirection, SaberType saberType, System.Single saberBladeSpeed, UnityEngine.Vector3 cutDirVec, System.Boolean directionOK, System.Boolean speedOK, System.Boolean saberTypeOK, System.Single cutDirDeviation) // Offset: 0xC14408 static void GetBasicCutInfo(UnityEngine::Transform* noteTransform, GlobalNamespace::NoteType noteType, GlobalNamespace::NoteCutDirection cutDirection, GlobalNamespace::SaberType saberType, float saberBladeSpeed, UnityEngine::Vector3 cutDirVec, bool& directionOK, bool& speedOK, bool& saberTypeOK, float& cutDirDeviation); // public System.Void .ctor() // Offset: 0xC14614 // Implemented from: System.Object // Base method: System.Void Object::.ctor() static NoteBasicCutInfo* New_ctor(); }; // NoteBasicCutInfo } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::NoteBasicCutInfo*, "", "NoteBasicCutInfo"); #pragma pack(pop)
47.949153
329
0.7614
Futuremappermydud
a340e33e6ef0760031216727f7fe8f4e3bfc85f4
7,775
cpp
C++
src/utils.cpp
mightybruno/KShare
c1124354be9c8bb5c1931e37e19391f0b6c4389f
[ "MIT" ]
16
2020-01-22T04:52:46.000Z
2022-02-22T09:53:39.000Z
src/utils.cpp
mightybruno/KShare
c1124354be9c8bb5c1931e37e19391f0b6c4389f
[ "MIT" ]
15
2020-02-16T01:12:42.000Z
2021-05-03T21:51:26.000Z
src/utils.cpp
mightybruno/KShare
c1124354be9c8bb5c1931e37e19391f0b6c4389f
[ "MIT" ]
3
2020-04-03T22:20:14.000Z
2020-09-23T07:58:09.000Z
#include "utils.hpp" #include <QApplication> #include <QClipboard> #include <QPainter> #include <QPixmap> #include <QProcess> #include <QScreen> #include <logger.hpp> #include <platformbackend.hpp> #include <settings.hpp> QColor utils::invertColor(QColor color) { return QColor(255 - color.red(), 255 - color.green(), 255 - color.blue()); } QPixmap utils::extend(QPixmap img, int extraSize, QColor hl) { QPixmap newImg(img.width() + extraSize * 2, img.height() + extraSize * 2); newImg.fill(hl); QPainter ptr(&newImg); ptr.drawPixmap(extraSize, extraSize, img); ptr.end(); return newImg; } QPixmap utils::fullscreen(bool cursor) { QPixmap image; QPainter painter; QPoint smallestCoordinate = smallestScreenCoordinate(); // Hack for https://bugreports.qt.io/browse/QTBUG-58110 #ifdef Q_OS_LINUX static QStringList qVer = QString(qVersion()).split('.'); if (qVer.at(0).toInt() == 5 && qVer.at(1).toInt() < 9) { image = window(0); painter.begin(&image); } else { #endif int height = 0, width = 0; int ox = smallestCoordinate.x() * -1, oy = smallestCoordinate.y() * -1; for (QScreen *screen : QApplication::screens()) { QRect geo = screen->geometry(); width = qMax(ox + geo.left() + geo.width(), width); height = qMax(oy + geo.top() + geo.height(), height); } image = QPixmap(width, height); image.fill(Qt::transparent); width = 0; painter.begin(&image); painter.translate(ox, oy); for (QScreen *screen : QApplication::screens()) { QPixmap currentScreen = window(0, screen); QRect geo = screen->geometry(); painter.drawPixmap(geo.left(), geo.top(), geo.width(), geo.height(), currentScreen); width += screen->size().width(); } #ifdef Q_OS_LINUX } #endif #ifdef PLATFORM_CAPABILITY_CURSOR if (cursor) { auto cursorData = PlatformBackend::inst().getCursor(); painter.drawPixmap(QCursor::pos() - std::get<0>(cursorData), std::get<1>(cursorData)); } #endif painter.end(); return image; } QPixmap utils::window(WId wid, QScreen *w) { return w->grabWindow(wid); } void utils::toClipboard(QString value) { QApplication::clipboard()->setText(value); } QPixmap utils::fullscreenArea(bool cursor, qreal x, qreal y, qreal w, qreal h) { return fullscreen(cursor).copy(x, y, w, h); } QPoint utils::smallestScreenCoordinate() { QPoint smallestCoordinate; for (QScreen *screen : QApplication::screens()) { smallestCoordinate.rx() = qMin(smallestCoordinate.x(), screen->geometry().left()); smallestCoordinate.ry() = qMin(smallestCoordinate.y(), screen->geometry().top()); } return smallestCoordinate; } QPixmap utils::renderText(QString toRender, int padding, QColor background, QColor pen, QFont font) { QFontMetrics metric(font); QStringList lines = toRender.replace("\r", "").split('\n'); QSize resultingSize(0, padding * 2); int lineSpace = metric.leading(); for (QString line : lines) { QRect br = metric.boundingRect(line); resultingSize.rheight() += lineSpace + br.height(); resultingSize.rwidth() = qMax(br.width(), resultingSize.width()); } resultingSize.rwidth() += padding * 2; QPixmap renderred(resultingSize); renderred.fill(background); QPainter painter(&renderred); painter.setPen(pen); int y = padding; for (QString line : lines) { QRect br = metric.boundingRect(line); painter.drawText(padding, y, br.width(), br.height(), 0, line); y += lineSpace + br.height(); } painter.end(); return renderred; } QString utils::randomString(int length) { QString str; str.resize(length); for (int s = 0; s < length; s++) str[s] = QChar('A' + char(qrand() % ('Z' - 'A'))); return str; } void utils::externalScreenshot(std::function<void(QPixmap)> callback) { QString cmd = settings::settings().value("command/fullscreenCommand", "").toString(); QStringList args = cmd.split(' '); QString tempPath; for (QString &arg : args) { if (arg == "%FILE_PATH") { if (tempPath.isEmpty()) tempPath = "KShare-Ext-Screenshot." + randomString(5); arg = tempPath; } } QProcess *process = new QProcess; QObject::connect(process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), [callback, process, tempPath](int code, QProcess::ExitStatus) { if (code != 0) { logger::fatal(QObject::tr("Failed to take external screenshot: \n") + process->readAllStandardError()); } else { QPixmap pixmap; if (!tempPath.isEmpty()) pixmap.load(tempPath); else pixmap.loadFromData(process->readAllStandardOutput()); callback(pixmap); } if (!tempPath.isEmpty()) QFile(tempPath).remove(); }); QObject::connect(process, &QProcess::errorOccurred, [](QProcess::ProcessError err) { if (err == QProcess::FailedToStart) settings::settings().remove("command/fullscreenCommand"); }); process->start(args.takeFirst(), args); } void utils::externalScreenshotActive(std::function<void(QPixmap)> callback) { QString cmd = settings::settings().value("command/activeCommand", "").toString(); QStringList args = cmd.split(' '); QString tempPath; for (QString &arg : args) { if (arg == "%FILE_PATH") { if (tempPath.isEmpty()) tempPath = "KShare-Ext-Screenshot." + randomString(5); arg = tempPath; } } QProcess *process = new QProcess; QObject::connect(process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), [callback, process, tempPath](int code, QProcess::ExitStatus) { if (code != 0) { logger::fatal(QObject::tr("Failed to take external screenshot: \n") + process->readAllStandardError()); } else { QPixmap pixmap; if (!tempPath.isEmpty()) pixmap.load(tempPath); else pixmap.loadFromData(process->readAllStandardOutput()); callback(pixmap); } if (!tempPath.isEmpty()) QFile(tempPath).remove(); }); QObject::connect(process, &QProcess::errorOccurred, [](QProcess::ProcessError err) { if (err == QProcess::FailedToStart) settings::settings().remove("command/activeCommand"); }); process->start(args.takeFirst(), args); } QIcon defaultIcon() { static QIcon icon = QIcon(":/icons/icon.png"); return icon; } QIcon infinity() { static QIcon icon = QIcon(":/icons/infinity.png"); return icon; } QIcon utils::getTrayIcon(int num) { if (!num) { return defaultIcon(); } else if (num < 100) { QPixmap unscaled = utils::renderText(QString::number(num), 0, Qt::lightGray, Qt::black); int dim = qMax(unscaled.width(), unscaled.height()); QPixmap scaled(dim, dim); scaled.fill(Qt::lightGray); QPainter *painter = new QPainter(&scaled); painter->drawPixmap((dim / 2) - (unscaled.width() / 2), 0, unscaled); delete painter; return scaled; } else { return infinity(); } }
36.502347
132
0.580322
mightybruno
a340ffc53e4e4c2a4ddbb9622504e595703ae398
2,965
cpp
C++
examples/Direct3D9Widget/MainWindow.cpp
giladreich/QtDirect3D
757568d4fc0c754ce445f145bb114ac1281f8b18
[ "MIT" ]
90
2019-01-16T21:40:27.000Z
2022-03-31T08:22:51.000Z
examples/Direct3D9Widget/MainWindow.cpp
giladreich/QtDirect3D
757568d4fc0c754ce445f145bb114ac1281f8b18
[ "MIT" ]
7
2021-08-20T00:06:12.000Z
2021-09-28T21:06:12.000Z
examples/Direct3D9Widget/MainWindow.cpp
giladreich/QtDirect3D
757568d4fc0c754ce445f145bb114ac1281f8b18
[ "MIT" ]
17
2019-01-16T21:40:32.000Z
2022-01-17T19:19:07.000Z
/* * */ #include "MainWindow.h" #include <QStyle> #include <QDebug> #include <QTime> #include <QScreen> #include <QMessageBox> #include <QCloseEvent> #include <QDesktopWidget> MainWindow::MainWindow(QWidget * parent) : QMainWindow(parent) , ui(new Ui::MainWindowClass) , m_WindowSize(QSize(1280, 800)) , m_pCbxDoFrames(new QCheckBox(this)) { ui->setupUi(this); m_pScene = ui->view; adjustWindowSize(); addToolbarWidgets(); connectSlots(); } MainWindow::~MainWindow() = default; void MainWindow::adjustWindowSize() { resize(m_WindowSize.width(), m_WindowSize.height()); setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, size(), qApp->screens().first()->availableGeometry())); } void MainWindow::addToolbarWidgets() { // Add CheckBox to tool-bar to stop/continue frames execution. m_pCbxDoFrames->setText("Do Frames"); m_pCbxDoFrames->setChecked(true); connect(m_pCbxDoFrames, &QCheckBox::stateChanged, [&] { if (m_pCbxDoFrames->isChecked()) m_pScene->continueFrames(); else m_pScene->pauseFrames(); }); ui->mainToolBar->addWidget(m_pCbxDoFrames); } void MainWindow::connectSlots() { connect(m_pScene, &QDirect3D9Widget::deviceInitialized, this, &MainWindow::init); connect(m_pScene, &QDirect3D9Widget::ticked, this, &MainWindow::tick); connect(m_pScene, &QDirect3D9Widget::rendered, this, &MainWindow::render); // NOTE: Additionally, you can listen to some basic IO events. // connect(m_pScene, &QDirect3D9Widget::keyPressed, this, &MainWindow::onKeyPressed); // connect(m_pScene, &QDirect3D9Widget::mouseMoved, this, &MainWindow::onMouseMoved); // connect(m_pScene, &QDirect3D9Widget::mouseClicked, this, &MainWindow::onMouseClicked); // connect(m_pScene, &QDirect3D9Widget::mouseReleased, this, &MainWindow::onMouseReleased); } void MainWindow::init(bool success) { if (!success) { QMessageBox::critical(this, "ERROR", "Direct3D widget initialization failed.", QMessageBox::Ok); return; } // TODO: Add here your extra initialization here. // ... // Start processing frames with a short delay in case things are still initializing/loading // in the background. QTimer::singleShot(500, this, [&] { m_pScene->run(); }); disconnect(m_pScene, &QDirect3D9Widget::deviceInitialized, this, &MainWindow::init); } void MainWindow::tick() { // TODO: Update the scene here. // m_pMesh->Tick(); } void MainWindow::render() { // TODO: Present the scene here. // m_pMesh->Render(); } void MainWindow::closeEvent(QCloseEvent * event) { event->ignore(); m_pScene->release(); QTime dieTime = QTime::currentTime().addMSecs(500); while (QTime::currentTime() < dieTime) QCoreApplication::processEvents(QEventLoop::AllEvents, 100); event->accept(); }
28.509615
95
0.668465
giladreich
a341ab073081693f8914f72a51430280b11d143b
6,105
cpp
C++
tools/llvm-pdbdump/PdbYaml.cpp
tlatkdgus1/llvm-code_obfuscate
c4d0641f95704fb9909e2ac09500df1b6bc5d017
[ "Unlicense" ]
6
2016-07-18T01:52:11.000Z
2020-11-18T14:07:07.000Z
tools/llvm-pdbdump/PdbYaml.cpp
tlatkdgus1/llvm-code_obfuscate
c4d0641f95704fb9909e2ac09500df1b6bc5d017
[ "Unlicense" ]
null
null
null
tools/llvm-pdbdump/PdbYaml.cpp
tlatkdgus1/llvm-code_obfuscate
c4d0641f95704fb9909e2ac09500df1b6bc5d017
[ "Unlicense" ]
null
null
null
//===- PdbYAML.cpp -------------------------------------------- *- C++ --*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "PdbYaml.h" #include "llvm/DebugInfo/PDB/PDBExtras.h" #include "llvm/DebugInfo/PDB/Raw/PDBFile.h" using namespace llvm; using namespace llvm::yaml; using namespace llvm::pdb; using namespace llvm::pdb::yaml; namespace llvm { namespace yaml { template <> struct ScalarTraits<llvm::pdb::PDB_UniqueId> { static void output(const llvm::pdb::PDB_UniqueId &S, void *, llvm::raw_ostream &OS) { OS << S; } static StringRef input(StringRef Scalar, void *Ctx, llvm::pdb::PDB_UniqueId &S) { if (Scalar.size() != 38) return "GUID strings are 38 characters long"; if (Scalar[0] != '{' || Scalar[37] != '}') return "GUID is not enclosed in {}"; if (Scalar[9] != '-' || Scalar[14] != '-' || Scalar[19] != '-' || Scalar[24] != '-') return "GUID sections are not properly delineated with dashes"; char *OutBuffer = S.Guid; for (auto Iter = Scalar.begin(); Iter != Scalar.end();) { if (*Iter == '-' || *Iter == '{' || *Iter == '}') { ++Iter; continue; } uint8_t Value = (llvm::hexDigitValue(*Iter) << 4); ++Iter; Value |= llvm::hexDigitValue(*Iter); ++Iter; *OutBuffer++ = Value; } return ""; } static bool mustQuote(StringRef Scalar) { return needsQuotes(Scalar); } }; template <> struct ScalarEnumerationTraits<llvm::pdb::PDB_Machine> { static void enumeration(IO &io, llvm::pdb::PDB_Machine &Value) { io.enumCase(Value, "Invalid", PDB_Machine::Invalid); io.enumCase(Value, "Am33", PDB_Machine::Am33); io.enumCase(Value, "Amd64", PDB_Machine::Amd64); io.enumCase(Value, "Arm", PDB_Machine::Arm); io.enumCase(Value, "ArmNT", PDB_Machine::ArmNT); io.enumCase(Value, "Ebc", PDB_Machine::Ebc); io.enumCase(Value, "x86", PDB_Machine::x86); io.enumCase(Value, "Ia64", PDB_Machine::Ia64); io.enumCase(Value, "M32R", PDB_Machine::M32R); io.enumCase(Value, "Mips16", PDB_Machine::Mips16); io.enumCase(Value, "MipsFpu", PDB_Machine::MipsFpu); io.enumCase(Value, "MipsFpu16", PDB_Machine::MipsFpu16); io.enumCase(Value, "PowerPCFP", PDB_Machine::PowerPCFP); io.enumCase(Value, "R4000", PDB_Machine::R4000); io.enumCase(Value, "SH3", PDB_Machine::SH3); io.enumCase(Value, "SH3DSP", PDB_Machine::SH3DSP); io.enumCase(Value, "Thumb", PDB_Machine::Thumb); io.enumCase(Value, "WceMipsV2", PDB_Machine::WceMipsV2); } }; template <> struct ScalarEnumerationTraits<llvm::pdb::PdbRaw_DbiVer> { static void enumeration(IO &io, llvm::pdb::PdbRaw_DbiVer &Value) { io.enumCase(Value, "V41", llvm::pdb::PdbRaw_DbiVer::PdbDbiVC41); io.enumCase(Value, "V50", llvm::pdb::PdbRaw_DbiVer::PdbDbiV50); io.enumCase(Value, "V60", llvm::pdb::PdbRaw_DbiVer::PdbDbiV60); io.enumCase(Value, "V70", llvm::pdb::PdbRaw_DbiVer::PdbDbiV70); io.enumCase(Value, "V110", llvm::pdb::PdbRaw_DbiVer::PdbDbiV110); } }; template <> struct ScalarEnumerationTraits<llvm::pdb::PdbRaw_ImplVer> { static void enumeration(IO &io, llvm::pdb::PdbRaw_ImplVer &Value) { io.enumCase(Value, "VC2", llvm::pdb::PdbRaw_ImplVer::PdbImplVC2); io.enumCase(Value, "VC4", llvm::pdb::PdbRaw_ImplVer::PdbImplVC4); io.enumCase(Value, "VC41", llvm::pdb::PdbRaw_ImplVer::PdbImplVC41); io.enumCase(Value, "VC50", llvm::pdb::PdbRaw_ImplVer::PdbImplVC50); io.enumCase(Value, "VC98", llvm::pdb::PdbRaw_ImplVer::PdbImplVC98); io.enumCase(Value, "VC70Dep", llvm::pdb::PdbRaw_ImplVer::PdbImplVC70Dep); io.enumCase(Value, "VC70", llvm::pdb::PdbRaw_ImplVer::PdbImplVC70); io.enumCase(Value, "VC80", llvm::pdb::PdbRaw_ImplVer::PdbImplVC80); io.enumCase(Value, "VC110", llvm::pdb::PdbRaw_ImplVer::PdbImplVC110); io.enumCase(Value, "VC140", llvm::pdb::PdbRaw_ImplVer::PdbImplVC140); } }; } } void MappingTraits<PdbObject>::mapping(IO &IO, PdbObject &Obj) { IO.mapOptional("MSF", Obj.Headers); IO.mapOptional("StreamSizes", Obj.StreamSizes); IO.mapOptional("StreamMap", Obj.StreamMap); IO.mapOptional("PdbStream", Obj.PdbStream); IO.mapOptional("DbiStream", Obj.DbiStream); } void MappingTraits<MsfHeaders>::mapping(IO &IO, MsfHeaders &Obj) { IO.mapRequired("SuperBlock", Obj.SuperBlock); IO.mapRequired("NumDirectoryBlocks", Obj.NumDirectoryBlocks); IO.mapRequired("BlockMapOffset", Obj.BlockMapOffset); IO.mapRequired("DirectoryBlocks", Obj.DirectoryBlocks); IO.mapRequired("NumStreams", Obj.NumStreams); IO.mapRequired("FileSize", Obj.FileSize); } void MappingTraits<PDBFile::SuperBlock>::mapping(IO &IO, PDBFile::SuperBlock &SB) { if (!IO.outputting()) { ::memcpy(SB.MagicBytes, MsfMagic, sizeof(MsfMagic)); } IO.mapRequired("BlockSize", SB.BlockSize); IO.mapRequired("Unknown0", SB.Unknown0); IO.mapRequired("NumBlocks", SB.NumBlocks); IO.mapRequired("NumDirectoryBytes", SB.NumDirectoryBytes); IO.mapRequired("Unknown1", SB.Unknown1); IO.mapRequired("BlockMapAddr", SB.BlockMapAddr); } void MappingTraits<StreamBlockList>::mapping(IO &IO, StreamBlockList &SB) { IO.mapRequired("Stream", SB.Blocks); } void MappingTraits<PdbInfoStream>::mapping(IO &IO, PdbInfoStream &Obj) { IO.mapRequired("Age", Obj.Age); IO.mapRequired("Guid", Obj.Guid); IO.mapRequired("Signature", Obj.Signature); IO.mapRequired("Version", Obj.Version); } void MappingTraits<PdbDbiStream>::mapping(IO &IO, PdbDbiStream &Obj) { IO.mapRequired("VerHeader", Obj.VerHeader); IO.mapRequired("Age", Obj.Age); IO.mapRequired("BuildNumber", Obj.BuildNumber); IO.mapRequired("PdbDllVersion", Obj.PdbDllVersion); IO.mapRequired("PdbDllRbld", Obj.PdbDllRbld); IO.mapRequired("Flags", Obj.Flags); IO.mapRequired("MachineType", Obj.MachineType); }
38.639241
80
0.658804
tlatkdgus1
a3440031ed80644b873404c9762928ef4b9ac7ec
29,153
cpp
C++
source/ablscript/ablxstd.cpp
mechasource/mechcommander2
b2c7cecf001cec1f535aa8d29c31bdc30d9aa983
[ "BSD-2-Clause" ]
38
2015-04-10T13:31:03.000Z
2021-09-03T22:34:05.000Z
source/ablscript/ablxstd.cpp
mechasource/mechcommander2
b2c7cecf001cec1f535aa8d29c31bdc30d9aa983
[ "BSD-2-Clause" ]
1
2020-07-09T09:48:44.000Z
2020-07-12T12:41:43.000Z
source/ablscript/ablxstd.cpp
mechasource/mechcommander2
b2c7cecf001cec1f535aa8d29c31bdc30d9aa983
[ "BSD-2-Clause" ]
12
2015-06-29T08:06:57.000Z
2021-10-13T13:11:41.000Z
//===========================================================================// // Copyright (C) Microsoft Corporation. All rights reserved. // //===========================================================================// //*************************************************************************** // // ABLXSTD.CPP // //*************************************************************************** #include "stdinc.h" #include "abl.h" namespace mclib::abl { //*************************************************************************** inline int32_t double2long(double _in) { _in += 6755399441055744.0; return (*(int32_t*)&_in); } //---------- // EXTERNALS extern int32_t level; extern int32_t execLineNumber; extern int32_t FileNumber; extern const std::wstring_view& codeSegmentPtr; extern TokenCodeType codeToken; extern StackItem* stack; extern const std::unique_ptr<StackItem>& tos; extern const std::unique_ptr<StackItem>& stackFrameBasePtr; extern const std::unique_ptr<SymTableNode>& CurRoutineIdPtr; extern int32_t CurModuleHandle; extern const std::unique_ptr<Type>& IntegerTypePtr; extern const std::unique_ptr<Type>& RealTypePtr; extern const std::unique_ptr<Type>& BooleanTypePtr; extern const std::unique_ptr<Type>& CharTypePtr; extern const std::unique_ptr<ABLModule>& CurModule; extern const std::unique_ptr<ABLModule>& CurFSM; extern int32_t MaxLoopIterations; extern const std::unique_ptr<Debugger>& debugger; extern bool NewStateSet; //-------- // GLOBALS StackItem returnValue; bool eofFlag = false; bool ExitWithReturn = false; bool ExitFromTacOrder = false; bool SkipOrder = false; TokenCodeType ExitRoutineCodeSegment[2] = {TKN_END_FUNCTION, TKN_SEMICOLON}; TokenCodeType ExitOrderCodeSegment[2] = {TKN_END_ORDER, TKN_SEMICOLON}; TokenCodeType ExitStateCodeSegment[2] = {TKN_END_STATE, TKN_SEMICOLON}; //*************************************************************************** // USEFUL ABL HELP ROUTINES //*************************************************************************** wchar_t ABLi_popChar(void) { getCodeToken(); execExpression(); wchar_t val = (wchar_t)tos->integer; pop(); return (val); } //--------------------------------------------------------------------------- int32_t ABLi_popInteger(void) { getCodeToken(); execExpression(); int32_t val = tos->integer; pop(); return (val); } //--------------------------------------------------------------------------- float ABLi_popReal(void) { getCodeToken(); execExpression(); float val = tos->real; pop(); return (val); } //--------------------------------------------------------------------------- float ABLi_popIntegerReal(void) { getCodeToken(); const std::unique_ptr<Type>& paramTypePtr = execExpression(); float val = 0.0; if (paramTypePtr == IntegerTypePtr) val = (float)tos->integer; else val = tos->real; pop(); return (val); } //--------------------------------------------------------------------------- bool ABLi_popBoolean(void) { getCodeToken(); execExpression(); int32_t val = tos->integer; pop(); return (val == 1); } //--------------------------------------------------------------------------- const std::wstring_view& ABLi_popCharPtr(void) { //-------------------------- // Get destination string... getCodeToken(); execExpression(); const std::wstring_view& charPtr = (const std::wstring_view&)tos->address; pop(); return (charPtr); } //--------------------------------------------------------------------------- int32_t* ABLi_popIntegerPtr(void) { getCodeToken(); const std::unique_ptr<SymTableNode>& idPtr = getCodeSymTableNodePtr(); execVariable(idPtr, USE_REFPARAM); int32_t* integerPtr = (int32_t*)(&((const std::unique_ptr<StackItem>&)tos->address)->integer); pop(); return (integerPtr); } //--------------------------------------------------------------------------- float* ABLi_popRealPtr(void) { getCodeToken(); const std::unique_ptr<SymTableNode>& idPtr = getCodeSymTableNodePtr(); execVariable(idPtr, USE_REFPARAM); float* realPtr = (float*)(&((const std::unique_ptr<StackItem>&)tos->address)->real); pop(); return (realPtr); } //--------------------------------------------------------------------------- const std::wstring_view& ABLi_popBooleanPtr(void) { //-------------------------- // Get destination string... getCodeToken(); execExpression(); const std::wstring_view& charPtr = (const std::wstring_view&)tos->address; pop(); return (charPtr); } //--------------------------------------------------------------------------- int32_t ABLi_popAnything(ABLStackItem* value) { getCodeToken(); const std::unique_ptr<Type>& paramTypePtr = execExpression(); int32_t type = -1; if (paramTypePtr == IntegerTypePtr) { value->type = type = ABL_STACKITEM_INTEGER; value->data.integer = tos->integer; } else if (paramTypePtr == BooleanTypePtr) { value->type = type = ABL_STACKITEM_BOOLEAN; value->data.boolean = (tos->integer ? true : false); } else if (paramTypePtr == CharTypePtr) { value->type = type = ABL_STACKITEM_CHAR; value->data.character = tos->byte; } else if (paramTypePtr == RealTypePtr) { value->type = type = ABL_STACKITEM_REAL; value->data.real = tos->real; } else if (paramTypePtr->form == FRM_ARRAY) { if (paramTypePtr->info.array.elementTypePtr == CharTypePtr) { value->type = type = ABL_STACKITEM_CHAR_PTR; value->data.characterPtr = (const std::wstring_view&)tos->address; } else if (paramTypePtr->info.array.elementTypePtr == IntegerTypePtr) { value->type = type = ABL_STACKITEM_INTEGER_PTR; value->data.integerPtr = (int32_t*)tos->address; } else if (paramTypePtr->info.array.elementTypePtr == RealTypePtr) { value->type = type = ABL_STACKITEM_REAL_PTR; value->data.realPtr = (float*)tos->address; } else if (paramTypePtr->info.array.elementTypePtr == BooleanTypePtr) { value->type = type = ABL_STACKITEM_BOOLEAN_PTR; value->data.booleanPtr = (bool*)tos->address; } } pop(); return (type); } //--------------------------------------------------------------------------- void ABLi_pushBoolean(bool value) { const std::unique_ptr<StackItem>& valuePtr = ++tos; if (valuePtr >= &stack[MAXSIZE_STACK]) runtimeError(ABL_ERR_RUNTIME_STACK_OVERFLOW); valuePtr->integer = value ? 1 : 0; } //--------------------------------------------------------------------------- void ABLi_pushInteger(int32_t value) { const std::unique_ptr<StackItem>& valuePtr = ++tos; if (valuePtr >= &stack[MAXSIZE_STACK]) runtimeError(ABL_ERR_RUNTIME_STACK_OVERFLOW); valuePtr->integer = value; } //--------------------------------------------------------------------------- void ABLi_pushReal(float value) { const std::unique_ptr<StackItem>& valuePtr = ++tos; if (valuePtr >= &stack[MAXSIZE_STACK]) runtimeError(ABL_ERR_RUNTIME_STACK_OVERFLOW); valuePtr->real = value; } //--------------------------------------------------------------------------- void ABLi_pushChar(wchar_t value) { const std::unique_ptr<StackItem>& valuePtr = ++tos; if (valuePtr >= &stack[MAXSIZE_STACK]) runtimeError(ABL_ERR_RUNTIME_STACK_OVERFLOW); valuePtr->integer = value; } //--------------------------------------------------------------------------- int32_t ABLi_peekInteger(void) { getCodeToken(); execExpression(); return (tos->integer); } //--------------------------------------------------------------------------- float ABLi_peekReal(void) { getCodeToken(); execExpression(); return (tos->real); } //--------------------------------------------------------------------------- bool ABLi_peekBoolean(void) { getCodeToken(); execExpression(); return (tos->integer == 1); } //--------------------------------------------------------------------------- const std::wstring_view& ABLi_peekCharPtr(void) { getCodeToken(); execExpression(); return ((const std::wstring_view&)tos->address); } //--------------------------------------------------------------------------- int32_t* ABLi_peekIntegerPtr(void) { getCodeToken(); const std::unique_ptr<SymTableNode>& idPtr = getCodeSymTableNodePtr(); execVariable(idPtr, USE_REFPARAM); return ((int32_t*)(&((const std::unique_ptr<StackItem>&)tos->address)->integer)); } //--------------------------------------------------------------------------- float* ABLi_peekRealPtr(void) { getCodeToken(); const std::unique_ptr<SymTableNode>& idPtr = getCodeSymTableNodePtr(); execVariable(idPtr, USE_REFPARAM); return ((float*)(&((const std::unique_ptr<StackItem>&)tos->address)->real)); } //--------------------------------------------------------------------------- void ABLi_pokeChar(int32_t val) { tos->integer = val; } //--------------------------------------------------------------------------- void ABLi_pokeInteger(int32_t val) { tos->integer = val; } //--------------------------------------------------------------------------- void ABLi_pokeReal(float val) { tos->real = val; } //--------------------------------------------------------------------------- void ABLi_pokeBoolean(bool val) { tos->integer = val ? 1 : 0; } //*************************************************************************** void execOrderReturn(int32_t returnVal) { //----------------------------- // Assignment to function id... const std::unique_ptr<StackFrameHeader>& headerPtr = (const std::unique_ptr<StackFrameHeader>&)stackFrameBasePtr; int32_t delta = level - CurRoutineIdPtr->level - 1; while (delta-- > 0) headerPtr = (const std::unique_ptr<StackFrameHeader>&)headerPtr->staticLink.address; if (CurRoutineIdPtr->defn.info.routine.flags & ROUTINE_FLAG_STATE) { //---------------------------------- // Return in a state function, so... if (debugger) debugger->traceDataStore(CurRoutineIdPtr, CurRoutineIdPtr->ptype, (const std::unique_ptr<StackItem>&)headerPtr, CurRoutineIdPtr->ptype); ExitWithReturn = true; ExitFromTacOrder = true; if (returnVal == 0) { //---------------------------------------------------------- // Use the "eject" code only if called for a failed Order... codeSegmentPtr = (const std::wstring_view&)ExitStateCodeSegment; getCodeToken(); } } else { //------------------------------------------------------------------------- // All Order functions (TacticalOrder/GeneralOrder/ActionOrder) must // return an integer error code, so we assume the return type is // IntegerTypePtr... const std::unique_ptr<StackItem>& targetPtr = (const std::unique_ptr<StackItem>&)headerPtr; targetPtr->integer = returnVal; //---------------------------------------------------------------------- // Preserve the return value, in case we need it for the calling user... memcpy(&returnValue, targetPtr, sizeof(StackItem)); if (debugger) debugger->traceDataStore(CurRoutineIdPtr, CurRoutineIdPtr->ptype, (const std::unique_ptr<StackItem>&)headerPtr, CurRoutineIdPtr->ptype); ExitWithReturn = true; ExitFromTacOrder = true; if (returnVal == 0) { //---------------------------------------------------------- // Use the "eject" code only if called for a failed Order... codeSegmentPtr = (const std::wstring_view&)ExitOrderCodeSegment; getCodeToken(); } } } //*************************************************************************** void execStdReturn(void) { memset(&returnValue, 0, sizeof(StackItem)); if (CurRoutineIdPtr->ptype) { //----------------------------- // Assignment to function id... const std::unique_ptr<StackFrameHeader>& headerPtr = (const std::unique_ptr<StackFrameHeader>&)stackFrameBasePtr; int32_t delta = level - CurRoutineIdPtr->level - 1; while (delta-- > 0) headerPtr = (const std::unique_ptr<StackFrameHeader>&)headerPtr->staticLink.address; const std::unique_ptr<StackItem>& targetPtr = (const std::unique_ptr<StackItem>&)headerPtr; const std::unique_ptr<Type>& targetTypePtr = (const std::unique_ptr<Type>&)(CurRoutineIdPtr->ptype); getCodeToken(); //--------------------------------------------------------------- // Routine execExpression() leaves the expression value on top of // stack... getCodeToken(); const std::unique_ptr<Type>& expressionTypePtr = execExpression(); //-------------------------- // Now, do the assignment... if ((targetTypePtr == RealTypePtr) && (expressionTypePtr == IntegerTypePtr)) { //------------------------- // integer assigned to real targetPtr->real = (float)(tos->integer); } else if (targetTypePtr->form == FRM_ARRAY) { //------------------------- // Copy the array/record... const std::wstring_view& dest = (const std::wstring_view&)targetPtr; const std::wstring_view& src = tos->address; int32_t size = targetTypePtr->size; memcpy(dest, src, size); } else if ((targetTypePtr == IntegerTypePtr) || (targetTypePtr->form == FRM_ENUM)) { //------------------------------------------------------ // Range check assignment to integer or enum subrange... targetPtr->integer = tos->integer; } else { //----------------------- // Assign real to real... targetPtr->real = tos->real; } //----------------------------- // Grab the expression value... pop(); //---------------------------------------------------------------------- // Preserve the return value, in case we need it for the calling user... memcpy(&returnValue, targetPtr, sizeof(StackItem)); if (debugger) debugger->traceDataStore( CurRoutineIdPtr, CurRoutineIdPtr->ptype, targetPtr, targetTypePtr); } //----------------------- // Grab the semi-colon... getCodeToken(); if (CurRoutineIdPtr->defn.info.routine.flags & ROUTINE_FLAG_ORDER) codeSegmentPtr = (const std::wstring_view&)ExitOrderCodeSegment; else if (CurRoutineIdPtr->defn.info.routine.flags & ROUTINE_FLAG_STATE) codeSegmentPtr = (const std::wstring_view&)ExitStateCodeSegment; else codeSegmentPtr = (const std::wstring_view&)ExitRoutineCodeSegment; ExitWithReturn = true; getCodeToken(); } //*************************************************************************** void execStdPrint(void) { //--------------------------- // Grab the opening LPAREN... getCodeToken(); //---------------------------- // Get parameter expression... getCodeToken(); const std::unique_ptr<Type>& paramTypePtr = execExpression(); wchar_t buffer[20]; const std::wstring_view& s = buffer; if (paramTypePtr == IntegerTypePtr) sprintf(buffer, "%d", tos->integer); else if (paramTypePtr == BooleanTypePtr) sprintf(buffer, "%s", tos->integer ? "true" : "false"); else if (paramTypePtr == CharTypePtr) sprintf(buffer, "%c", tos->byte); else if (paramTypePtr == RealTypePtr) sprintf(buffer, "%.4f", tos->real); else if ((paramTypePtr->form == FRM_ARRAY) && (paramTypePtr->info.array.elementTypePtr == CharTypePtr)) s = (const std::wstring_view&)tos->address; pop(); if (debugger) { wchar_t message[512]; sprintf(message, "PRINT: \"%s\"", s); debugger->print(message); sprintf(message, " MODULE %s", CurModule->getName()); debugger->print(message); sprintf(message, " FILE %s", CurModule->getSourceFile(FileNumber)); debugger->print(message); sprintf(message, " LINE %d", execLineNumber); debugger->print(message); } /* else if (TACMAP) { aChatWindow* chatWin = TACMAP->getChatWindow(); if (chatWin) chatWin->processChatString(0, s, -1); else { #ifdef _DEBUG OutputDebugString(s); #endif } } */ else { #ifdef _DEBUG ABLDebugPrintCallback(s); #endif } //----------------------- // Grab closing RPAREN... getCodeToken(); } //*************************************************************************** const std::unique_ptr<Type>& execStdConcat(void) { //------------------- // Grab the LPAREN... getCodeToken(); //-------------------------- // Get destination string... getCodeToken(); execExpression(); const std::wstring_view& dest = (const std::wstring_view&)tos->address; pop(); //---------------------- // Get item to append... getCodeToken(); const std::unique_ptr<Type>& paramTypePtr = execExpression(); wchar_t buffer[20]; if (paramTypePtr == IntegerTypePtr) { sprintf(buffer, "%d", tos->integer); strcat(dest, buffer); } else if (paramTypePtr == CharTypePtr) { sprintf(buffer, "%c", tos->byte); strcat(dest, buffer); } else if (paramTypePtr == RealTypePtr) { sprintf(buffer, "%.2f", tos->real); strcat(dest, buffer); } else if (paramTypePtr == BooleanTypePtr) { sprintf(buffer, "%s", tos->integer ? "true" : "false"); strcat(dest, buffer); } else if ((paramTypePtr->form == FRM_ARRAY) && (paramTypePtr->info.array.elementTypePtr == CharTypePtr)) strcat(dest, (const std::wstring_view&)tos->address); tos->integer = 0; getCodeToken(); return (IntegerTypePtr); } //*************************************************************************** void execStdAbs(void) { float val = ABLi_popIntegerReal(); if (val < 0.0) val = -val; ABLi_pushReal(val); } //***************************************************************************** void execStdRound(void) { float val = ABLi_popReal(); if (val > 0.0) ABLi_pushInteger((int32_t)(val + 0.5)); else ABLi_pushInteger((int32_t)(val - 0.5)); } //*************************************************************************** void execStdSqrt(void) { float val = ABLi_popIntegerReal(); if (val < 0.0) runtimeError(ABL_ERR_RUNTIME_INVALID_FUNCTION_ARGUMENT); else ABLi_pushReal((float)sqrt(val)); } //*************************************************************************** void execStdTrunc(void) { float val = ABLi_popReal(); ABLi_pushInteger((int32_t)val); } //*************************************************************************** void execStdFileOpen(void) { const std::wstring_view& fileName = ABLi_popCharPtr(); int32_t fileHandle = -1; UserFile* userFile = UserFile::getNewFile(); if (userFile) { int32_t err = userFile->open(fileName); if (!err) fileHandle = userFile->handle; } ABLi_pushInteger(fileHandle); } //--------------------------------------------------------------------------- void execStdFileWrite(void) { int32_t fileHandle = ABLi_popInteger(); const std::wstring_view& string = ABLi_popCharPtr(); UserFile* userFile = UserFile::files[fileHandle]; if (userFile->inUse) userFile->write(string); } //--------------------------------------------------------------------------- void execStdFileClose(void) { int32_t fileHandle = ABLi_popInteger(); UserFile* userFile = UserFile::files[fileHandle]; if (userFile->inUse) userFile->close(); } //*************************************************************************** void execStdGetModule(void) { //---------------------------------------------------------- // Return the handle of the current module being executed... const std::wstring_view& curBuffer = ABLi_popCharPtr(); const std::wstring_view& fsmBuffer = ABLi_popCharPtr(); strcpy(curBuffer, CurModule->getFileName()); strcpy(fsmBuffer, CurFSM ? CurFSM->getFileName() : "none"); ABLi_pushInteger(CurModuleHandle); } //*************************************************************************** void execStdSetMaxLoops(void) { //---------------------------------------------------------------------- // // SET MAX LOOPS function: // // Sets the max number of loops that may occur (in a for, while or // repeat loop) before an infinite loop run-time error occurs. // // PARAMS: integer // // RETURN: none // //---------------------------------------------------------------------- MaxLoopIterations = ABLi_popInteger() + 1; } //--------------------------------------------------------------------------- void execStdFatal(void) { //---------------------------------------------------------------------- // // FATAL function: // // If the debugger is active, this immediately jumps into debug mode. // Otherwise, it causes a fatal and exits the game (displaying the // string passed in). // // PARAMS: integer fatal code to display // // wchar_t[] message // // RETURN: none // //---------------------------------------------------------------------- int32_t code = ABLi_popInteger(); const std::wstring_view& s = ABLi_popCharPtr(); wchar_t message[512]; if (debugger) { sprintf(message, "FATAL: [%d] \"%s\"", code, s); debugger->print(message); sprintf(message, " MODULE (%d) %s", CurModule->getId(), CurModule->getName()); debugger->print(message); sprintf(message, " FILE %s", CurModule->getSourceFile(FileNumber)); debugger->print(message); sprintf(message, " LINE %d", execLineNumber); debugger->print(message); debugger->debugMode(); } else { sprintf(message, "ABL FATAL: [%d] %s", code, s); ABL_Fatal(0, s); } } //--------------------------------------------------------------------------- void execStdAssert(void) { //---------------------------------------------------------------------- // // ASSERT function: // // If the debugger is active, this immediately jumps into debug mode // if expression is FALSE. Otherwise, the _ASSERT statement is ignored // unless the #debug directive has been issued in the module. If // so, a fatal occurs and exits the game (displaying the // string passed in). // // PARAMS: boolean expression // // integer _ASSERT code to display // // wchar_t[] message // // RETURN: none // //---------------------------------------------------------------------- int32_t expression = ABLi_popInteger(); int32_t code = ABLi_popInteger(); const std::wstring_view& s = ABLi_popCharPtr(); if (!expression) { wchar_t message[512]; if (debugger) { sprintf(message, "ASSERT: [%d] \"%s\"", code, s); debugger->print(message); sprintf(message, " MODULE (%d) %s", CurModule->getId(), CurModule->getName()); debugger->print(message); sprintf(message, " FILE %s", CurModule->getSourceFile(FileNumber)); debugger->print(message); sprintf(message, " LINE %d", execLineNumber); debugger->print(message); debugger->debugMode(); } else { sprintf(message, "ABL ASSERT: [%d] %s", code, s); ABL_Fatal(0, message); } } } //----------------------------------------------------------------------------- void execStdRandom(void) { int32_t n = ABLi_peekInteger(); //--------------------------------------------------------------------- // This is, like, a really bad number generator. But, you get the idea. // Once we know which pseudo-random number algorithm we want to use, we // should plug it in here. The range for the random number (r), given a // param of (n), should be: 0 <= r <= (n-1). ABLi_pokeInteger(ABLRandomCallback(n)); } //----------------------------------------------------------------------------- void execStdSeedRandom(void) { int32_t seed = ABLi_popInteger(); if (seed == -1) ABLSeedRandomCallback(time(nullptr)); else ABLSeedRandomCallback(seed); } //----------------------------------------------------------------------------- void execStdResetOrders(void) { int32_t scope = ABLi_popInteger(); if (scope == 0) CurModule->resetOrderCallFlags(); else if (scope == 1) { int32_t startIndex = CurRoutineIdPtr->defn.info.routine.orderCallIndex; int32_t endIndex = startIndex + CurRoutineIdPtr->defn.info.routine.numOrderCalls; for (size_t i = startIndex; i < endIndex; i++) { uint8_t orderDWord = (uint8_t)(i / 32); uint8_t orderBitMask = (uint8_t)(i % 32); CurModule->clearOrderCallFlag(orderDWord, orderBitMask); } } } //--------------------------------------------------------------------------- void execStdGetStateHandle(void) { const std::wstring_view& name = ABLi_popCharPtr(); int32_t stateHandle = CurFSM->findStateHandle(_strlwr(name)); ABLi_pushInteger(stateHandle); } //--------------------------------------------------------------------------- void execStdGetCurrentStateHandle(void) { int32_t stateHandle = CurFSM->getStateHandle(); ABLi_pushInteger(stateHandle); } //--------------------------------------------------------------------------- extern const std::unique_ptr<ModuleEntry>& ModuleRegistry; extern wchar_t SetStateDebugStr[256]; void execStdSetState(void) { uint32_t stateHandle = ABLi_popInteger(); if (stateHandle > 0) { const std::unique_ptr<SymTableNode>& stateFunction = ModuleRegistry[CurFSM->getHandle()].stateHandles[stateHandle].state; CurFSM->setPrevState(CurFSM->getState()); CurFSM->setState(stateFunction); sprintf(SetStateDebugStr, "%s:%s, line %d", CurFSM->getFileName(), stateFunction->name, execLineNumber); NewStateSet = true; } } //--------------------------------------------------------------------------- void execStdGetFunctionHandle(void) { const std::wstring_view& name = ABLi_popCharPtr(); const std::unique_ptr<SymTableNode>& function = CurModule->findFunction(name, false); if (function) ABLi_pushInteger((uint32_t)function); else ABLi_pushInteger(0); } //--------------------------------------------------------------------------- void execStdSetFlag(void) { uint32_t bits = (uint32_t)ABLi_popInteger(); uint32_t flag = (uint32_t)ABLi_popInteger(); bool set = ABLi_popBoolean(); bits &= (flag ^ 0xFFFFFFFF); if (set) bits |= flag; ABLi_pushInteger(bits); } //--------------------------------------------------------------------------- void execStdGetFlag(void) { uint32_t bits = (uint32_t)ABLi_popInteger(); uint32_t flag = (uint32_t)ABLi_popInteger(); bool set = ((bits & flag) != 0); ABLi_pushInteger(set); } //--------------------------------------------------------------------------- void execStdCallFunction(void) { uint32_t address = ABLi_popInteger(); if (address) { // GLENN: Not functional, yet... } } //*************************************************************************** void initStandardRoutines(void) { //------------------------------------------------------------- // Fatal and Assert will have hardcoded keys so we can look for // 'em in the rest of the ABL code (example: ignore asserts if // the assert_off option has been set). enterStandardRoutine("fatal", RTN_FATAL, false, "iC", nullptr, execStdFatal); enterStandardRoutine("_ASSERT", RTN_ASSERT, false, "biC", nullptr, execStdAssert); enterStandardRoutine( "getstatehandle", RTN_GET_STATE_HANDLE, false, "C", "i", execStdGetStateHandle); enterStandardRoutine( "getcurrentstatehandle", -1, false, nullptr, "i", execStdGetCurrentStateHandle); enterStandardRoutine("abs", -1, false, "*", "r", execStdAbs); enterStandardRoutine("sqrt", -1, false, "*", "r", execStdSqrt); enterStandardRoutine("round", -1, false, "r", "i", execStdRound); enterStandardRoutine("trunc", -1, false, "r", "i", execStdTrunc); enterStandardRoutine("random", -1, false, "i", "i", execStdRandom); enterStandardRoutine("seedrandom", -1, false, "i", nullptr, execStdSeedRandom); enterStandardRoutine("setmaxloops", -1, false, "i", nullptr, execStdSetMaxLoops); enterStandardRoutine("fileopen", -1, false, "C", "i", execStdFileOpen); enterStandardRoutine("filewrite", -1, false, "iC", nullptr, execStdFileWrite); enterStandardRoutine("fileclose", -1, false, "i", nullptr, execStdFileClose); enterStandardRoutine("getmodule", -1, false, "CC", "i", execStdGetModule); enterStandardRoutine("resetorders", -1, false, "i", nullptr, execStdResetOrders); enterStandardRoutine("setstate", -1, false, "i", nullptr, execStdSetState); enterStandardRoutine("getfunctionhandle", -1, false, "C", "i", execStdGetFunctionHandle); enterStandardRoutine("callfunction", -1, false, "i", nullptr, execStdCallFunction); enterStandardRoutine("setflag", -1, false, "iib", "i", execStdSetFlag); enterStandardRoutine("getflag", -1, false, "ii", "b", execStdGetFlag); } //----------------------------------------------------------------------------- const std::unique_ptr<Type>& execStandardRoutineCall(const std::unique_ptr<SymTableNode>& routineIdPtr, bool skipOrder) { int32_t key = routineIdPtr->defn.info.routine.key; switch (key) { case RTN_RETURN: execStdReturn(); return (nullptr); case RTN_PRINT: execStdPrint(); return (nullptr); case RTN_CONCAT: return (execStdConcat()); default: { if (key >= NumStandardFunctions) { wchar_t err[255]; sprintf(err, " ABL: Undefined ABL RoutineKey in %s:%d", CurModule->getName(), execLineNumber); ABL_Fatal(0, err); } if (FunctionInfoTable[key].numParams > 0) getCodeToken(); SkipOrder = skipOrder; if (FunctionCallbackTable[key]) (*FunctionCallbackTable[key])(); else { wchar_t err[255]; sprintf(err, " ABL: Undefined ABL RoutineKey %d in %s:%d", key, CurModule->getName(), execLineNumber); ABL_Fatal(key, err); } getCodeToken(); switch (FunctionInfoTable[key].returnType) { case RETURN_TYPE_NONE: return (nullptr); case RETURN_TYPE_INTEGER: return (IntegerTypePtr); case RETURN_TYPE_REAL: return (RealTypePtr); case RETURN_TYPE_BOOLEAN: return (BooleanTypePtr); } } } return (nullptr); } //*************************************************************************** } // namespace mclib::abl
27.92433
115
0.556135
mechasource
a3453eed730064b30cc16c9bceca3dcd94cb60ec
8,770
cpp
C++
HaloExchangeTests/src/GnuplotLogger.cpp
pspoerri/HaloExchangeBenchmarks
6e86202aa3e5bf073cbcb38afdbf6db78f4d8c58
[ "BSD-3-Clause" ]
null
null
null
HaloExchangeTests/src/GnuplotLogger.cpp
pspoerri/HaloExchangeBenchmarks
6e86202aa3e5bf073cbcb38afdbf6db78f4d8c58
[ "BSD-3-Clause" ]
null
null
null
HaloExchangeTests/src/GnuplotLogger.cpp
pspoerri/HaloExchangeBenchmarks
6e86202aa3e5bf073cbcb38afdbf6db78f4d8c58
[ "BSD-3-Clause" ]
null
null
null
#include <cmath> #include <climits> #include <iostream> #include <sstream> #include <stdexcept> #include <stdlib.h> #include "GnuplotLogger.h" void GnuplotLogger::Init(int saveDigits, int iSize, int jSize, int kSize, std::string filename, int kmin = 0, int kmax = 0, int numRowPlots = 2, int numColumnPlots = 3) { assert(numRowPlots > 0); assert(numColumnPlots > 0); SetRelativePrecision(pow(10.0, -saveDigits)); passed_ = true; assert(kmin >= 0 && kmin < kSize); assert(kmax >= 0 && kmax >= kmin && kmax <= kSize); iSize_ = iSize; jSize_ = jSize; kSize_ = kSize; pValidatedGrid_ = (int*)malloc( iSize_*jSize_*kSize*sizeof(int) ); filename_ = filename+".gpi"; kmin_ = kmin; kmax_ = kmax; numRowPlots_ = numRowPlots; numColumnPlots_ = numColumnPlots; numLevels_ = kmax_ - kmin_; if (kmin_ == 0) { numLevels_++; } if( numLevels_ < numRowPlots_ * numColumnPlots_) { bool inLoop = true; while(inLoop) { inLoop = false; if (numRowPlots_ > numColumnPlots_) { if (numLevels_ < (numRowPlots_ - 1) * numColumnPlots_) { numRowPlots_--; inLoop = true; } } else { if(numLevels_ < (numRowPlots_ * (numColumnPlots_-1)) ) { numColumnPlots_--; inLoop = true; } } } } SetUp(); } std::string GnuplotLogger::Name() { std::stringstream buffer; buffer << "GnuplotLogger, Epsilon = " << relativePrecision_; return buffer.str(); } void GnuplotLogger::SetUp() { for (int i = 0; i < iSize_ ; ++i) { for (int j = 0; j < jSize_ ; ++j) { for (int k = 0; k < kSize_ ; ++k) { pValidatedGrid_[i+iSize_*(j+k*jSize_) ] = -1; } } } } void GnuplotLogger::ConvertValidatedMatrix(double* valid) { int asize = iSize_*jSize_*kSize_; for(int l=0; l < asize; ++l) { // value == 0 : correct inner domain if((int) valid[l] == 0 ) pValidatedGrid_[l] = 0; // value == 1 : correct halo else if((int) valid[l] == 1) pValidatedGrid_[l] = 1; // value == 5 : wrong inner domain else if((int) valid[l] == 5) pValidatedGrid_[l] = 10; // value == 6 : wrong halo else if((int) valid[l] == 6) pValidatedGrid_[l] = 6.5; // value == 5 : uninitialized else if((int) valid[l] < 0 ) pValidatedGrid_[l] = 5; if( (int) valid[l] != 0 && (int) valid[l] != 1) passed_ = false; } } void GnuplotLogger::Compare(int i, int j, int k, double* demanded, double* actual) { if (BasicCompare(demanded[ i+iSize_*(j+k*jSize_) ], actual[ i+iSize_*(j+k*jSize_) ]) == false) { passed_ = false; pValidatedGrid_[i+iSize_*(j+k*jSize_) ] = 3; } else { pValidatedGrid_[i+iSize_*(j+k*jSize_) ] = 1; } } bool GnuplotLogger::Passed() { return passed_; } std::string GnuplotLogger::getResult() { if( ! passed_ ) { outFile_.open(filename_.c_str(), std::ios::out); if (!outFile_) { throw std::runtime_error("MatlabLogger::Init(...) Can't open file\n"); } if (numLevels_ > 1) { outFile_ << "set xrange [-1:1]" << std::endl; outFile_ << "set yrange [-1:1]" << std::endl; outFile_ << "set size 1,1" << std::endl; outFile_ << "set origin 0,0" << std::endl; outFile_ << "set object 2 rect from screen 0.87, 0.94 to screen 0.88, 0.96 fc ls 6 fs bo 1" << std::endl; outFile_ << "set label \"Uninitialized\" at screen 0.885, 0.952 font \",9\"" << std::endl; outFile_ << "set object 3 rect from screen 0.87, 0.9 to screen 0.88, 0.92 fc ls 3 fs bo 1" << std::endl; outFile_ << "set label \"Correct\" at screen 0.885, 0.912 font \",9\"" << std::endl; outFile_ << "set object 4 rect from screen 0.87, 0.86 to screen 0.88, 0.88 fc ls 1 fs bo 1" << std::endl; outFile_ << "set label \"Incorrect\" at screen 0.885, 0.872 font \",9\"" << std::endl; outFile_ << "set multiplot" << std::endl; } int kInPage = 0; int kInRow = 0; int kInColumn = 0; float xOrigin = 0; float yOrigin = 0; float xSize = 0; float ySize = 0; std::stringstream ss; for (int k = kmin_; k < kmax_ + 1; ++k) { kInPage = (k - kmin_); kInPage = kInPage % (numRowPlots_ * numColumnPlots_); kInPage++; if (kInPage == 1 && k != kmin_) { outFile_ << "unset multiplot" << std::endl; outFile_ << "pause -1 \"Hit return to continue\"" << std::endl; outFile_ << "set xrange [-1:1]" << std::endl; outFile_ << "set size 1,1" << std::endl; outFile_ << "set origin 0,0" << std::endl; outFile_ << "set multiplot" << std::endl; } kInRow = (kInPage - 1) / numColumnPlots_ + 1; kInColumn = (kInPage - 1) % numColumnPlots_ + 1; float ratio = iSize_ / (float)(jSize_) ; yOrigin = 1 / (float) (numRowPlots_) * (numRowPlots_ - kInRow); xOrigin = 1 / (float) (numColumnPlots_) * (kInColumn - 1); xSize = 1 / (float) (numRowPlots_); ySize = 1 / (float) (numColumnPlots_); if (ySize / xSize < ratio) { xSize = ySize * 1 / ratio; } else { ySize = xSize * ratio; } if (numRowPlots_ * numColumnPlots_ > 5 && numRowPlots_ * numColumnPlots_ < 8) { xSize = xSize * 1.15; ySize = ySize * 1.15; } if (numRowPlots_ * numColumnPlots_ > 7) { xSize = xSize * 1.25; ySize = ySize * 1.25; } outFile_ << "set title \"Level " << k << "\"" << std::endl; outFile_ << "set size " << xSize << "," << ySize << std::endl; outFile_ << "set origin " << xOrigin << "," << yOrigin << std::endl; outFile_ << "unset key" << std::endl; outFile_ << "set tic scale 0" << std::endl; outFile_ << "set border 3 front" << std::endl; outFile_ << "unset colorbox" << std::endl; outFile_ << "set cbrange [-2:7]" << std::endl; outFile_ << "set cbtics 0,1,5" << std::endl; outFile_ << "set size ratio " << ratio << std::endl; float xrangemin = -0.5; float xrangemax = jSize_ - 0.5; outFile_ << "set xrange ["<<xrangemin<< ":" << xrangemax << "]" << std::endl; float yrangemin = -0.5; float yrangemax = iSize_ - 0.5; outFile_ << "set yrange ["<<yrangemin<< ":" << yrangemax << "] reverse" << std::endl; outFile_ << "unset ytics" << std::endl; outFile_ << "unset xtics" << std::endl; outFile_ << "set view map" << std::endl; outFile_ << "set title \"Level " << k << "\"" << std::endl; outFile_ << "set xtics" << std::endl; outFile_ << "set ytics" << std::endl; outFile_ << "set xlabel 'j'" << std::endl; outFile_ << "set ylabel 'i'" << std::endl; outFile_ << "set palette defined (0 \"blue\", 14 \"yellow\", 20 \"red\" )" << std::endl; outFile_ << "splot '-' matrix with image failsafe" << std::endl; for (int i = 0; i < iSize_ ; ++i) { for (int j = 0; j < jSize_ ; ++j) { // for(int k=0; k < calculationDomain_.kSize() + 1; ++k) outFile_ << pValidatedGrid_[i+iSize_*(j+k*jSize_) ] << " "; } outFile_ << std::endl; } outFile_ << "e" << std::endl; outFile_ << "e" << std::endl; } if (numLevels_ > 1) { outFile_ << "unset multiplot" << std::endl; } outFile_ << "pause -1 \"Hit return to continue\"" << std::endl; outFile_.close(); } if ( ! passed_ ) return std::string("GnuplotLogger: failures detected written in gnuplot file " + filename_); else return std::string("GnuplotLogger: passed"); } bool GnuplotLogger::BasicRelativeCompare(double demanded, double actual) { return fabs(demanded - actual) < fabs(demanded*relativePrecision_); } bool GnuplotLogger::BasicAbsoluteCompare(double demanded, double actual) { return fabs(demanded - actual) < relativePrecision_ ; } bool GnuplotLogger::BasicCompare(double demanded, double actual) { const double absolutLimit = 1; if(fabs(demanded) < absolutLimit && fabs(actual) < absolutLimit) { return BasicAbsoluteCompare(demanded, actual); } else { return BasicRelativeCompare(demanded, actual); } }
29.233333
144
0.527024
pspoerri
a34af58cfb46131ea9c32cf303cc0786dcd034ed
22,925
cpp
C++
Core/Contents/Source/PolyImage.cpp
MattDBell/Polycode
fc66547813a34a2388c9a45ec0b69919ce3253b2
[ "MIT" ]
1
2020-04-30T23:05:26.000Z
2020-04-30T23:05:26.000Z
Core/Contents/Source/PolyImage.cpp
MattDBell/Polycode
fc66547813a34a2388c9a45ec0b69919ce3253b2
[ "MIT" ]
null
null
null
Core/Contents/Source/PolyImage.cpp
MattDBell/Polycode
fc66547813a34a2388c9a45ec0b69919ce3253b2
[ "MIT" ]
null
null
null
/* Copyright (C) 2011 by Ivan Safrin 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 "png.h" #include <math.h> #include "PolyImage.h" #include "PolyString.h" #include "PolyLogger.h" #include "OSBasics.h" #include "PolyPerlin.h" #include <algorithm> using namespace Polycode; void user_read_data(png_structp png_ptr, png_bytep data, png_size_t length) { OSFILE *file = (OSFILE*)png_get_io_ptr(png_ptr); OSBasics::read(data, length, 1, file); } Image::Image(const String& fileName) : imageData(NULL) { setPixelType(IMAGE_RGBA); loaded = false; if(!loadImage(fileName)) { Logger::log("Error loading %s\n", fileName.c_str()); } else { loaded = true; // Logger::log("image loaded!"); } } Image *Image::BlankImage(int width, int height, int type) { return new Image(width, height, type); } void Image::setPixelType(int type) { imageType = type; switch(imageType) { case IMAGE_RGB: pixelSize = 3; break; case IMAGE_RGBA: pixelSize = 4; break; case IMAGE_FP16: pixelSize = 16; break; default: pixelSize = 4; break; } } bool Image::isLoaded() const { return loaded; } Image::Image(int width, int height, int type) : imageData(NULL) { setPixelType(type); createEmpty(width, height); } Image::Image(Image *copyImage) { setPixelType(copyImage->getType()); width = copyImage->getWidth(); height = copyImage->getHeight(); imageData = (char*)malloc(width*height*pixelSize); memcpy(imageData, copyImage->getPixels(), width*height*pixelSize); } Image::Image(char *data, int width, int height, int type) { setPixelType(type); imageData = (char*)malloc(width*height*pixelSize); memcpy(imageData, data, width*height*pixelSize); this->width = width; this->height = height; } void Image::pasteImage(Image *image, int x, int y, int blendingMode , Number blendAmount, Color blendColor ) { for(int iy=0; iy<image->getHeight(); iy++) { for(int ix=0; ix<image->getWidth(); ix++) { Color src = image->getPixel(ix,iy); Color destColor = getPixel(x+ix, y+iy); Color finalColor = destColor.blendColor(src, blendingMode, blendAmount, blendColor); setPixel(x+ix, y+iy, finalColor); } } } Image::Image() { imageData = NULL; } Image::~Image() { free(imageData); } char *Image::getPixels() { return imageData; } char *Image::getPixelsInRect(int x, int y, int width, int height) { transformCoordinates(&x, &y, &width, &height); char *retBuf = (char*) malloc(pixelSize * width * height); memset(retBuf, 0, pixelSize * width * height); if(x < this->width-1 && y < this->height-1) { width = std::min(width, this->width - x); height = std::min(height, this->height - y); for(int i=0; i < height; i++) { long srcOffset = ((pixelSize*this->width) * (y+i)) + (pixelSize*x); long dstOffset = (pixelSize*width) * i; memcpy(retBuf + dstOffset, imageData+srcOffset, pixelSize * width); } } return retBuf; } Image *Image::getImagePart(Rectangle subRect) { char *newData = getPixelsInRect( (int) subRect.x, (int) subRect.y, (int) subRect.w, (int) subRect.h); return new Image(newData, subRect.w, subRect.h, this->imageType); } Color Image::getPixel(int x, int y) { transformCoordinates(&x, &y); if(x < 0 || x >= width || y < 0 || y >= height) return Color(0,0,0,0); unsigned int *imageData32 = (unsigned int*)imageData; unsigned int hex = imageData32[x+(y*width)]; int ta = (hex >> 24) & 0xFF; int tb = (hex >> 16) & 0xFF; int tg = (hex >> 8) & 0xFF; int tr = (hex ) & 0xFF; return Color(((Number)tr)/255.0f, ((Number)tg)/255.0f, ((Number)tb)/255.0f,((Number)ta)/255.0f); } int Image::getWidth() const { return width; } int Image::getHeight() const { return height; } void Image::createEmpty(int width, int height) { free(imageData); imageData = (char*)malloc(width*height*pixelSize); this->width = width; this->height = height; fill(Color(0,0,0,0)); } void Image::perlinNoise(int seed, bool alpha) { Perlin perlin = Perlin(12,33,1,seed); unsigned int *imageData32 = (unsigned int*)imageData; Color pixelColor; Number noiseVal; for(int i=0; i < width*height;i++) { noiseVal = fabs(1.0f/perlin.Get( 0.1+(0.9f/((Number)width)) * (i%width), (1.0f/((Number)height)) * (i - (i%width)))); if(alpha) pixelColor.setColor(noiseVal, noiseVal, noiseVal, noiseVal); else pixelColor.setColor(noiseVal, noiseVal, noiseVal, 1.0f); imageData32[i] = pixelColor.getUint(); } } void Image::writeBMP(const String& fileName) const { // SDL_Surface *image; // image = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 32, 0x0000FF, 0x00FF00, 0xFF0000, 0x000000); // memcpy(image->pixels,imageData,width * height * 4); // SDL_SaveBMP(image, fileName.c_str()); } void Image::fillRect(int x, int y, int w, int h, Color col) { for(int i=0; i < w; i++) { for(int j=0; j < h; j++) { setPixel(x+i,y+j,col); } } } void Image::setPixel(int x, int y, Color col) { transformCoordinates(&x, &y); if(x < 0 || x >= width || y < 0 || y >= height) return; unsigned int *imageData32 = (unsigned int*)imageData; imageData32[x+(y*width)] = col.getUint(); } void Image::moveBrush(int x, int y) { brushPosX += x; brushPosY -= y; } void Image::moveBrushTo(int x, int y) { brushPosX = x; brushPosY = y; } int Image::getBrushX() const { return brushPosX; } int Image::getBrushY() const { return brushPosY; } void Image::drawLineTo(int x, int y, Color col) { drawLine(brushPosX, brushPosY, brushPosX+x, brushPosY+y, col); } void Image::setPixel(int x, int y, Number r, Number g, Number b, Number a) { transformCoordinates(&x, &y); if(x < 0 || x > width || y < 0 || y > height) return; Color color; color.setColor(r,g,b,a); unsigned int *imageData32 = (unsigned int*)imageData; imageData32[x+(y*width)] = color.getUint(); } void Image::multiply(Number amt, bool color, bool alpha) { int startIndex = 0; int endIndex = 3; if(!color) startIndex = 3; if(!alpha) endIndex = 2; for (int i = 0; i < height*width*pixelSize; i+=pixelSize) { for(int j = startIndex; j < endIndex+1;j++) { if(((Number)imageData[i+j]) * amt< 0) imageData[i+j] = 0; else if(((Number)imageData[i+j]) * amt > 255) imageData[i+j] = 255; else imageData[i+j] = (char)(((Number)imageData[i+j]) * amt); } } } void Image::darken(Number amt, bool color, bool alpha) { char decAmt = 255.0f * amt; int startIndex = 0; int endIndex = 3; if(!color) startIndex = 3; if(!alpha) endIndex = 2; for (int i = 0; i < height*width*pixelSize; i+=pixelSize) { for(int j = startIndex; j < endIndex+1;j++) { if(imageData[i+j]-decAmt < 0) imageData[i+j] = 0; else imageData[i+j] -= decAmt; } } } void Image::lighten(Number amt, bool color, bool alpha) { char decAmt = 255.0f * amt; int startIndex = 0; int endIndex = 3; if(!color) startIndex = 3; if(!alpha) endIndex = 2; for (int i = 0; i < height*width*pixelSize; i+=pixelSize) { for(int j = startIndex; j < endIndex+1;j++) { if(imageData[i+j]+decAmt > 255) imageData[i+j] = 255; else imageData[i+j] += decAmt; } } } float* Image::createKernel(float radius, float deviation) { int size = 2 * (int)radius + 1; float* kernel = (float*)malloc(sizeof(float) * (size+1)); float radiusf = fabs(radius) + 1.0f; if(deviation == 0.0f) deviation = sqrtf( -(radiusf * radiusf) / (2.0f * logf(1.0f / 255.0f)) ); kernel[0] = size; float value = -radius; float sum = 0.0f; int i; for(i = 0; i < size; i++) { kernel[1 + i] = 1.0f / (2.506628275f * deviation) * expf(-((value * value) / (2.0f * (deviation * deviation)))); sum += kernel[1 + i]; value += 1.0f; } for(i = 0; i < size; i++) { kernel[1 + i] /= sum; } return kernel; } void Image::gaussianBlur(float radius, float deviation) { char *newData = (char*)malloc(width*height*pixelSize); char *horzBlur; char *vertBlur; horzBlur = (char*)malloc(sizeof(float)*pixelSize*width*height); vertBlur = (char*)malloc(sizeof(float)*pixelSize*width*height); float *kernel = createKernel(radius, deviation); int i, iY, iX; // Horizontal pass. for(iY = 0; iY < height; iY++) { for(iX = 0; iX < width; iX++) { float val[4]; memset(val, 0, sizeof(float) * 4); int offset = ((int)kernel[0]) / -2; for(i = 0; i < ((int)kernel[0]); i++) { int x = iX + offset; if(x < 0 || x >= width) { offset++; continue; } float kernip1 = kernel[i + 1]; if(imageType == IMAGE_FP16) { float *dataPtr = (float*)&imageData[(width * pixelSize * iY) + (pixelSize * x)]; for(int c=0; c < 4; c++) { val[c] += kernip1 * dataPtr[c]; } } else { char *dataPtr = &imageData[(width * pixelSize * iY) + (pixelSize * x)]; for(int c=0; c < pixelSize; c++) { val[c] += kernip1 * ((float)dataPtr[c]); } } offset++; } if(imageType == IMAGE_FP16) { int baseOffset = (width * 4 * iY) + (4 * iX); for(int c=0; c < 4; c++) { float *f_horzBlur = (float*)horzBlur; f_horzBlur[baseOffset+c] = val[c]; } } else { int baseOffset = (width * pixelSize * iY) + (pixelSize * iX); for(int c=0; c < pixelSize; c++) { if(val[c] > 255.0) { val[c] = 255.0; } horzBlur[baseOffset+c] = (char)val[c]; } } } } // Vertical pass. for(iY = 0; iY < height; iY++) { for(iX = 0; iX < width; iX++) { float val[4]; memset(val, 0, sizeof(float) * 4); int offset = ((int)kernel[0]) / -2; for(i = 0; i < ((int)kernel[0]); i++) { int y = iY + offset; if(y < 0 || y >= height) { offset++; continue; } float kernip1 = kernel[i + 1]; if(imageType == IMAGE_FP16) { float *dataPtr = (float*)&horzBlur[(width * pixelSize * y) + (pixelSize * iX)]; for(int c=0; c < 4; c++) { val[c] += kernip1 * dataPtr[c]; } } else { char *dataPtr = &horzBlur[(width * pixelSize * y) + (pixelSize * iX)]; for(int c=0; c < pixelSize; c++) { val[c] += kernip1 * ((float)dataPtr[c]); } } offset++; } if(imageType == IMAGE_FP16) { int baseOffset = (width * 4 * iY) + (4 * iX); for(int c=0; c < 4; c++) { float *f_vertBlur = (float*)vertBlur; f_vertBlur[baseOffset+c] = val[c]; } } else { int baseOffset = (width * pixelSize * iY) + (pixelSize * iX); for(int c=0; c < pixelSize; c++) { if(val[c] > 255.0) { val[c] = 255.0; } vertBlur[baseOffset+c] = (char)val[c]; } } } } memcpy(newData, vertBlur, height * width * pixelSize); free(horzBlur); free(vertBlur); free(kernel); free(imageData); imageData = newData; } void Image::fastBlurHor(int blurSize) { if(blurSize == 0) return; unsigned char *blurImage = (unsigned char*)malloc(width*height*pixelSize); int total_r; int total_g; int total_b; int total_a; unsigned int *imageData32 = (unsigned int*)imageData; unsigned char *pixel; int amt; for (int y = 1; y < height; y++) { for (int x = 0; x < width; x++) { total_r = 0; total_g = 0; total_b = 0; total_a = 0; amt = 0; for (int kx = -blurSize; kx <= blurSize; kx++) { if((x+kx > 0 && x+kx < width) && (x+kx+((y)*width) > 0 && x+kx+((y)*width) < width*height)) { pixel = (unsigned char*)&(imageData32[(x+kx)+((y)*width)]); total_r += pixel[0]; total_g += pixel[1]; total_b += pixel[2]; total_a += pixel[3]; amt++; } } // Logger::log("%d / %d = %d\n",total_r, amt, (total_r/amt)); blurImage[((x+(y*width))*pixelSize)] = (total_r/amt); blurImage[((x+(y*width))*pixelSize)+1] = (total_g / amt); blurImage[((x+(y*width))*pixelSize)+2] = (total_b / amt); blurImage[((x+(y*width))*pixelSize)+3] = (total_a / amt); } } free(imageData); imageData = (char*)blurImage; // free(imageData32); } void Image::fastBlurVert(int blurSize) { if(blurSize == 0) return; unsigned char *blurImage = (unsigned char*)malloc(width*height*pixelSize); int total_r; int total_g; int total_b; int total_a; unsigned int *imageData32 = (unsigned int*)imageData; unsigned char *pixel; int amt; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { total_r = 0; total_g = 0; total_b = 0; total_a = 0; amt = 0; for (int ky = -blurSize; ky <= blurSize; ky++) { if((y+ky > 0 && y+ky < height) && (x+((y+ky)*width) > 0 && x+((y+ky)*width) < width*height)) { pixel = (unsigned char*)&(imageData32[(x)+((y+ky)*width)]); total_r += pixel[0]; total_g += pixel[1]; total_b += pixel[2]; total_a += pixel[3]; amt++; } } //Logger::log("%d / %d = %d\n",total_r, amt, (total_r/amt)); blurImage[((x+(y*width))*pixelSize)] = (total_r/amt); blurImage[((x+(y*width))*pixelSize)+1] = (total_g / amt); blurImage[((x+(y*width))*pixelSize)+2] = (total_b / amt); blurImage[((x+(y*width))*pixelSize)+3] = (total_a / amt); } } free(imageData); imageData = (char*)blurImage; // free(imageData32); } void Image::fastBlur(int blurSize) { fastBlurHor(blurSize); fastBlurVert(blurSize); /* unsigned char *blurImage = (unsigned char*)malloc(width*height*4); int total_r; int total_g; int total_b; int total_a; unsigned int *imageData32 = (unsigned int*)imageData; unsigned char *pixel; int amt; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { total_r = 0; total_g = 0; total_b = 0; total_a = 0; amt = 0; for (int ky = -blurSize; ky <= blurSize; ky++) { for (int kx = -blurSize; kx <= blurSize ; kx++) { if(x+kx+((y+ky)*width) > 0 && x+kx+((y+ky)*width) < width*height) { pixel = (unsigned char*)&(imageData32[(x+kx)+((y+ky)*width)]); total_r += pixel[0]; total_g += pixel[1]; total_b += pixel[2]; total_a += pixel[3]; amt++; } } } // Logger::log("%d / %d = %d\n",total_r, amt, (total_r/amt)); blurImage[((x+(y*width))*4)] = (total_r/amt); blurImage[((x+(y*width))*4)+1] = (total_g / amt); blurImage[((x+(y*width))*4)+2] = (total_b / amt); blurImage[((x+(y*width))*4)+3] = (total_a / amt); } } imageData = (char*)blurImage; // free(imageData32); */ } void Image::swap(int *v1, int *v2) { int tv = *v1; *v1 = *v2; *v2 = tv; } void Image::drawLine(int x0, int y0, int x1, int y1, Color col) { bool steep = abs(y1 - y0) > abs(x1 - x0); if(steep) { swap(&x0, &y0); swap(&x1, &y1); } if(x0 > x1) { swap(&x0, &x1); swap(&y0, &y1); } int deltax = x1 - x0; int deltay = abs(y1 - y0); Number error = 0; Number deltaerr = ((Number)deltay) / ((Number)deltax); int ystep; int y = y0; if(y0 < y1) ystep = 1; else ystep = -1; for(int x=x0; x < x1;x++) { if(steep) { setPixel(y,x,col); } else { setPixel(x,y,col); } error = error + ((Number)deltaerr); if(error >= 0.5) { y = y + ystep; error = error - 1.0; } } } void Image::fill(Color color) { unsigned int val = color.getUint(); unsigned int *imageData32 = (unsigned int*) imageData; for(int i=0; i< width*height; i++) { imageData32[i] = val; } } bool Image::saveImage(const String &fileName) { return savePNG(fileName); } void Image::premultiplyAlpha() { unsigned int *imageData32 = (unsigned int*)imageData; for(int x=0; x < width; x++) { for(int y=0; y < height; y++) { unsigned int hex = imageData32[x+(y*width)]; int ta = (hex >> 24) & 0xFF; int tb = (hex >> 16) & 0xFF; int tg = (hex >> 8) & 0xFF; int tr = (hex ) & 0xFF; Number r = ((Number)tr)/255.0f; Number g = ((Number)tg)/255.0f; Number b = ((Number)tb)/255.0f; Number a = ((Number)ta)/255.0f; r *= a; g *= a; b *= a; unsigned int ir = 255.0f*r; unsigned int ig = 255.0f*g; unsigned int ib = 255.0f*b; unsigned int ia = 255.0f*a; unsigned int newVal = ((ia & 0xFF) << 24) | ((ib & 0xFF) << 16) | ((ig & 0xFF) << 8) | (ir & 0xFF); imageData32[x+(y*width)] = newVal; } } } bool Image::savePNG(const String &fileName) { printf("Saving %dx%d image\n", width, height); FILE *fp; png_structp png_ptr; png_infop info_ptr; fp = fopen(fileName.c_str(), "wb"); if (fp == NULL) return false; png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0); if (png_ptr == NULL) { fclose(fp); return false; } info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) { fclose(fp); png_destroy_write_struct(&png_ptr, NULL); return false; } if (setjmp(png_jmpbuf(png_ptr))) { /* If we get here, we had a problem writing the file */ fclose(fp); png_destroy_write_struct(&png_ptr, &info_ptr); return false; } png_init_io(png_ptr, fp); png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(png_ptr, info_ptr); png_uint_32 k; png_bytep *row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * height); if (height > PNG_UINT_32_MAX/png_sizeof(png_bytep)) png_error (png_ptr, "Image is too tall to process in memory"); for (k = 0; k < height; k++) row_pointers[height-k-1] = (png_byte*)(imageData + k*width*4); /* One of the following output methods is REQUIRED */ png_write_image(png_ptr, row_pointers); free(row_pointers); png_free(png_ptr, 0); png_destroy_write_struct(&png_ptr, &info_ptr); fclose(fp); return true; } bool Image::loadImage(const String& fileName) { return loadPNG(fileName); } bool Image::loadPNG(const String& fileName) { OSFILE *infile; png_structp png_ptr; png_infop info_ptr; char *image_data; char sig[8]; int bit_depth; int color_type; png_uint_32 width; png_uint_32 height; unsigned int rowbytes; image_data = NULL; int i; png_bytepp row_pointers = NULL; infile = OSBasics::open(fileName.c_str(), "rb"); if (!infile) { Logger::log("Error opening png file (\"%s\")\n", fileName.c_str()); return false; } OSBasics::read(sig, 1, 8, infile); if (!png_check_sig((unsigned char *) sig, 8)) { Logger::log("Error reading png signature (\"%s\")\n", fileName.c_str()); OSBasics::close(infile); return false; } png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { Logger::log("Error creating png struct (\"%s\")\n", fileName.c_str()); OSBasics::close(infile); return false; /* out of memory */ } info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { Logger::log("Error creating info struct (\"%s\")\n", fileName.c_str()); png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL); OSBasics::close(infile); return false; /* out of memory */ } if (setjmp(png_jmpbuf(png_ptr))) { Logger::log("Error setting jump thingie (\"%s\")\n", fileName.c_str()); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); OSBasics::close(infile); return false; } //png_init_io(png_ptr, infile); png_set_read_fn(png_ptr, (png_voidp)infile, user_read_data); png_set_sig_bytes(png_ptr, 8); png_read_info(png_ptr, info_ptr); png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL); this->width = width; this->height = height; /* Set up some transforms. */ if (color_type & PNG_COLOR_MASK_ALPHA) { // png_set_strip_alpha(png_ptr); } if (bit_depth > 8) { png_set_strip_16(png_ptr); } if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { png_set_gray_to_rgb(png_ptr); } if (color_type == PNG_COLOR_TYPE_PALETTE) { png_set_palette_to_rgb(png_ptr); } if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_RGB_ALPHA) { png_set_add_alpha(png_ptr, 0xffffff, PNG_FILLER_AFTER); } /* Update the png info struct.*/ png_read_update_info(png_ptr, info_ptr); /* Rowsize in bytes. */ rowbytes = png_get_rowbytes(png_ptr, info_ptr); /* Allocate the image_data buffer. */ if ((image_data = (char *) malloc(rowbytes * height))==NULL) { Logger::log("Error allocating image memory (\"%s\")\n", fileName.c_str()); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return false; } if ((row_pointers = (png_bytepp)malloc(height*sizeof(png_bytep))) == NULL) { Logger::log("Error allocating image memory (\"%s\")\n", fileName.c_str()); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); free(image_data); image_data = NULL; return false; } for (i = 0; i < height; ++i) row_pointers[height - 1 - i] = (png_byte*)image_data + i*rowbytes; png_read_image(png_ptr, row_pointers); free(row_pointers); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); OSBasics::close(infile); imageData = image_data; return true; } void Image::transformCoordinates(int *x, int *y) { *y = this->height - *y - 1; } void Image::transformCoordinates(int *x, int *y, int *w, int *h) { *y = this->height - *h - *y - 1; }
25.700673
122
0.595594
MattDBell
a35433cfb9e84d5dda51a8fdbd1d001686d0fd0f
5,664
hpp
C++
openstudiocore/src/model/RefrigerationGasCoolerAirCooled.hpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
openstudiocore/src/model/RefrigerationGasCoolerAirCooled.hpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
openstudiocore/src/model/RefrigerationGasCoolerAirCooled.hpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2014, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #ifndef MODEL_REFRIGERATIONGASCOOLERAIRCOOLED_HPP #define MODEL_REFRIGERATIONGASCOOLERAIRCOOLED_HPP #include "ModelAPI.hpp" #include "ParentObject.hpp" namespace openstudio { namespace model { class CurveLinear; // class ThermalZone; namespace detail { class RefrigerationGasCoolerAirCooled_Impl; } // detail /** RefrigerationGasCoolerAirCooled is a ParentObject that wraps the OpenStudio IDD object 'OS:Refrigeration:GasCooler:AirCooled'. */ class MODEL_API RefrigerationGasCoolerAirCooled : public ParentObject { public: /** @name Constructors and Destructors */ //@{ explicit RefrigerationGasCoolerAirCooled(const Model& model); virtual ~RefrigerationGasCoolerAirCooled() {} //@} static IddObjectType iddObjectType(); static std::vector<std::string> gasCoolerFanSpeedControlTypeValues(); /** @name Getters */ //@{ boost::optional<CurveLinear> ratedTotalHeatRejectionRateCurve() const; std::string gasCoolerFanSpeedControlType() const; bool isGasCoolerFanSpeedControlTypeDefaulted() const; double ratedFanPower() const; bool isRatedFanPowerDefaulted() const; double minimumFanAirFlowRatio() const; bool isMinimumFanAirFlowRatioDefaulted() const; double transitionTemperature() const; bool isTransitionTemperatureDefaulted() const; double transcriticalApproachTemperature() const; bool isTranscriticalApproachTemperatureDefaulted() const; double subcriticalTemperatureDifference() const; bool isSubcriticalTemperatureDifferenceDefaulted() const; double minimumCondensingTemperature() const; bool isMinimumCondensingTemperatureDefaulted() const; // boost::optional<ThermalZone> airInletNode() const; std::string endUseSubcategory() const; bool isEndUseSubcategoryDefaulted() const; double gasCoolerRefrigerantOperatingChargeInventory() const; bool isGasCoolerRefrigerantOperatingChargeInventoryDefaulted() const; double gasCoolerReceiverRefrigerantInventory() const; bool isGasCoolerReceiverRefrigerantInventoryDefaulted() const; double gasCoolerOutletPipingRefrigerantInventory() const; bool isGasCoolerOutletPipingRefrigerantInventoryDefaulted() const; //@} /** @name Setters */ //@{ bool setRatedTotalHeatRejectionRateCurve(const CurveLinear& curveLinear); void resetRatedTotalHeatRejectionRateCurve(); bool setGasCoolerFanSpeedControlType(std::string gasCoolerFanSpeedControlType); void resetGasCoolerFanSpeedControlType(); bool setRatedFanPower(double ratedFanPower); void resetRatedFanPower(); bool setMinimumFanAirFlowRatio(double minimumFanAirFlowRatio); void resetMinimumFanAirFlowRatio(); void setTransitionTemperature(double transitionTemperature); void resetTransitionTemperature(); void setTranscriticalApproachTemperature(double transcriticalApproachTemperature); void resetTranscriticalApproachTemperature(); void setSubcriticalTemperatureDifference(double subcriticalTemperatureDifference); void resetSubcriticalTemperatureDifference(); void setMinimumCondensingTemperature(double minimumCondensingTemperature); void resetMinimumCondensingTemperature(); // bool setAirInletNode(const ThermalZone& thermalZone); // void resetAirInletNode(); void setEndUseSubcategory(std::string endUseSubcategory); void resetEndUseSubcategory(); void setGasCoolerRefrigerantOperatingChargeInventory(double gasCoolerRefrigerantOperatingChargeInventory); void resetGasCoolerRefrigerantOperatingChargeInventory(); void setGasCoolerReceiverRefrigerantInventory(double gasCoolerReceiverRefrigerantInventory); void resetGasCoolerReceiverRefrigerantInventory(); void setGasCoolerOutletPipingRefrigerantInventory(double gasCoolerOutletPipingRefrigerantInventory); void resetGasCoolerOutletPipingRefrigerantInventory(); //@} /** @name Other */ //@{ //@} protected: /// @cond typedef detail::RefrigerationGasCoolerAirCooled_Impl ImplType; explicit RefrigerationGasCoolerAirCooled(std::shared_ptr<detail::RefrigerationGasCoolerAirCooled_Impl> impl); friend class detail::RefrigerationGasCoolerAirCooled_Impl; friend class Model; friend class IdfObject; friend class openstudio::detail::IdfObject_Impl; /// @endcond private: REGISTER_LOGGER("openstudio.model.RefrigerationGasCoolerAirCooled"); }; /** \relates RefrigerationGasCoolerAirCooled*/ typedef boost::optional<RefrigerationGasCoolerAirCooled> OptionalRefrigerationGasCoolerAirCooled; /** \relates RefrigerationGasCoolerAirCooled*/ typedef std::vector<RefrigerationGasCoolerAirCooled> RefrigerationGasCoolerAirCooledVector; } // model } // openstudio #endif // MODEL_REFRIGERATIONGASCOOLERAIRCOOLED_HPP
29.34715
133
0.783545
zhouchong90
a3563fb3618b9d5064c892e72d0354b40c6c7858
2,932
hpp
C++
S3DTiled/include/S3DTiled/Chunk.hpp
tyanmahou/S3DTiled
4f90ea7e30eed8973ebc92a72a77edfc00ba0f10
[ "MIT" ]
null
null
null
S3DTiled/include/S3DTiled/Chunk.hpp
tyanmahou/S3DTiled
4f90ea7e30eed8973ebc92a72a77edfc00ba0f10
[ "MIT" ]
1
2020-03-22T05:15:36.000Z
2020-04-03T13:40:59.000Z
S3DTiled/include/S3DTiled/Chunk.hpp
tyanmahou/S3DTiled
4f90ea7e30eed8973ebc92a72a77edfc00ba0f10
[ "MIT" ]
1
2020-09-16T06:32:16.000Z
2020-09-16T06:32:16.000Z
#pragma once #include <Siv3D/Grid.hpp> #include <Siv3D/HashTable.hpp> namespace s3dTiled { template<class Type> class Chunk { public: Chunk() = default; Chunk(s3d::int32 chunkSizeX, s3d::int32 chunkSizeY) : Chunk(s3d::Size{ chunkSizeX, chunkSizeY }) {} Chunk(const s3d::Size& chunkSize): m_chunkSize(chunkSize), m_startIndex(0, 0), m_endIndex(chunkSize) {} const Type& operator()(s3d::int32 y, s3d::int32 x) const { const s3d::int32 baseY = y >= 0 ? y / m_chunkSize.y : (y - m_chunkSize.y + 1) / m_chunkSize.y; const s3d::int32 baseX = x >= 0 ? x / m_chunkSize.x : (x - m_chunkSize.x + 1) / m_chunkSize.x; if (!m_chunks.contains(baseX)) { return notfound; } if (!m_chunks.at(baseX).contains(baseY)) { return notfound; } const auto& grid = m_chunks.at(baseX).at(baseY); auto fixY = static_cast<size_t>(y - baseY * m_chunkSize.y); auto fixX = static_cast<size_t>(x - baseX * m_chunkSize.x); if (!grid.inBounds(fixY, fixX)) { return notfound; } return grid[fixY][fixX]; } const s3d::Size& chunkSize() const { return m_chunkSize; } const s3d::Size& startIndex() const { return m_startIndex; } const s3d::Size& endIndex() const { return m_endIndex; } s3d::Size size() const { return m_endIndex - m_startIndex; } s3d::int32 width() const { return m_endIndex.x - m_startIndex.x; } s3d::int32 height() const { return m_endIndex.y - m_startIndex.y; } auto begin() const { return m_chunks.begin(); } auto end() const { return m_chunks.end(); } public: void push(const s3d::Point& pos, s3d::Grid<Type>&& grid) { if (pos.x < m_startIndex.x) { m_startIndex.x = pos.x; } else if (pos.x + m_chunkSize.x > m_endIndex.x) { m_endIndex.x = pos.x + m_chunkSize.x; } if (pos.y < m_startIndex.y) { m_startIndex.y = pos.y; } else if (pos.y + m_chunkSize.y > m_endIndex.y) { m_endIndex.y = pos.y + m_chunkSize.y; } m_chunks[pos.x / m_chunkSize.x][pos.y / m_chunkSize.y] = std::move(grid); } private: s3d::Size m_chunkSize; s3d::Size m_startIndex; s3d::Size m_endIndex; s3d::HashTable<s3d::int32, s3d::HashTable<s3d::int32, s3d::Grid<Type>>> m_chunks; inline static constexpr Type notfound{}; }; } // namespace s3dTiled
30.226804
106
0.501705
tyanmahou
a358ffbe7237a8ad21fb5d9a6cf608646731c6d1
3,258
hpp
C++
include/continuable/detail/operations/async.hpp
Naios/Continue.cpp
ed8310e345b3c930c0810bc27f3e979a479da9b6
[ "MIT" ]
2
2016-01-04T13:02:36.000Z
2016-07-18T04:09:14.000Z
include/continuable/detail/operations/async.hpp
Naios/Continue.cpp
ed8310e345b3c930c0810bc27f3e979a479da9b6
[ "MIT" ]
1
2015-08-13T21:10:11.000Z
2016-04-01T00:58:10.000Z
include/continuable/detail/operations/async.hpp
Naios/Continue.cpp
ed8310e345b3c930c0810bc27f3e979a479da9b6
[ "MIT" ]
null
null
null
/* /~` _ _ _|_. _ _ |_ | _ \_,(_)| | | || ||_|(_||_)|(/_ https://github.com/Naios/continuable v4.2.0 Copyright(c) 2015 - 2022 Denis Blank <denis.blank at outlook dot com> 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 CONTINUABLE_DETAIL_OPERATIONS_ASYNC_HPP_INCLUDED #define CONTINUABLE_DETAIL_OPERATIONS_ASYNC_HPP_INCLUDED #include <continuable/continuable-base.hpp> #include <continuable/detail/core/annotation.hpp> #include <continuable/detail/core/base.hpp> #include <continuable/detail/utility/identity.hpp> namespace cti { namespace detail { namespace operations { template <typename Callable, typename Executor, typename... Args> auto async(Callable&& callable, Executor&& executor, Args&&... args) { using result_t = decltype(util::invoke(std::forward<decltype(callable)>(callable), std::forward<decltype(args)>(args)...)); constexpr auto hint = decltype(base::decoration::invoker_of(identity<result_t>{}))::hint(); auto continuation = [callable = std::forward<decltype(callable)>(callable), executor = std::forward<decltype(executor)>(executor), args = std::make_tuple(std::forward<decltype(args)>( args)...)](auto&& promise) mutable { auto invoker = base::decoration::invoker_of(identity<result_t>{}); using promise_t = decltype(promise); // Invoke the callback traits::unpack( [&](auto&&... args) mutable { // Invoke the promise through the dedicated invoker // and through the given executor base::on_executor(std::move(executor), std::move(invoker), std::move(callable), std::forward<promise_t>(promise), std::forward<decltype(args)>(args)...); }, std::move(args)); }; return base::attorney::create_from(std::move(continuation), // hint, util::ownership{}); } } // namespace operations } // namespace detail } // namespace cti #endif // CONTINUABLE_DETAIL_OPERATIONS_ASYNC_HPP_INCLUDED
40.222222
79
0.65531
Naios
a35e49269c890582da8e04edcb640752836b1822
3,368
cpp
C++
04_FindInPartiallySortedMatrix/FindInPartiallySortedMatrix.cpp
darkkiller123/-offer
a0859f469e5c8caef52d5ff145753ad46eda6aaa
[ "BSD-3-Clause" ]
null
null
null
04_FindInPartiallySortedMatrix/FindInPartiallySortedMatrix.cpp
darkkiller123/-offer
a0859f469e5c8caef52d5ff145753ad46eda6aaa
[ "BSD-3-Clause" ]
null
null
null
04_FindInPartiallySortedMatrix/FindInPartiallySortedMatrix.cpp
darkkiller123/-offer
a0859f469e5c8caef52d5ff145753ad46eda6aaa
[ "BSD-3-Clause" ]
null
null
null
/******************************************************************* Copyright(c) 2016, Harry He All rights reserved. Distributed under the BSD license. (See accompanying file LICENSE.txt at https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt) *******************************************************************/ //================================================================== // ใ€Šๅ‰‘ๆŒ‡Offerโ€”โ€”ๅไผ้ข่ฏ•ๅฎ˜็ฒพ่ฎฒๅ…ธๅž‹็ผ–็จ‹้ข˜ใ€‹ไปฃ็  // ไฝœ่€…๏ผšไฝ•ๆตทๆถ› //================================================================== // ้ข่ฏ•้ข˜4๏ผšไบŒ็ปดๆ•ฐ็ป„ไธญ็š„ๆŸฅๆ‰พ // ้ข˜็›ฎ๏ผšๅœจไธ€ไธชไบŒ็ปดๆ•ฐ็ป„ไธญ๏ผŒๆฏไธ€่กŒ้ƒฝๆŒ‰็…งไปŽๅทฆๅˆฐๅณ้€’ๅขž็š„้กบๅบๆŽ’ๅบ๏ผŒๆฏไธ€ๅˆ—้ƒฝๆŒ‰ // ็…งไปŽไธŠๅˆฐไธ‹้€’ๅขž็š„้กบๅบๆŽ’ๅบใ€‚่ฏทๅฎŒๆˆไธ€ไธชๅ‡ฝๆ•ฐ๏ผŒ่พ“ๅ…ฅ่ฟ™ๆ ท็š„ไธ€ไธชไบŒ็ปดๆ•ฐ็ป„ๅ’Œไธ€ไธช // ๆ•ดๆ•ฐ๏ผŒๅˆคๆ–ญๆ•ฐ็ป„ไธญๆ˜ฏๅฆๅซๆœ‰่ฏฅๆ•ดๆ•ฐใ€‚ // -----> ๅขžๅŠ  // | // | // | ๅขžๅŠ  // | // โ†“ // ๆŸฅๆ‰พไบŒ็ปดๆ•ฐ็ป„ไธญๆ˜ฏๅฆๆœ‰่ฟ™ไธชๆ•ฐๅญ— // 1ใ€ #include <cstdio> // ๆ€็ปดๅ‡บ้—ฎ้ข˜ไบ†๏ผŒ๏ผŒ๏ผŒๅบ”่ฏฅไปŽๅณไธŠ่ง’ๅผ€ๅง‹ๆ‰พใ€‚ใ€‚ใ€‚ๆˆ–่€…ไปŽๅทฆไธ‹่ง’ ๅผ€ๅง‹ๆ‰พ // ่ฏ•ๅ›พๅˆ‡ๆขไบบ็š„ๆ€็ปด~ bool Find(int* matrix, int rows, int columns, int number) { bool found = false; if(matrix != nullptr && rows > 0 && columns > 0) { int row = 0; int column = columns - 1; while(row < rows && column >=0) { if(matrix[row * columns + column] == number) { found = true; break; } else if(matrix[row * columns + column] > number) -- column; else ++ row; } } return found; } // ====================ๆต‹่ฏ•ไปฃ็ ==================== void Test(char* testName, int* matrix, int rows, int columns, int number, bool expected) { if(testName != nullptr) printf("%s begins: ", testName); bool result = Find(matrix, rows, columns, number); if(result == expected) printf("Passed.\n"); else printf("Failed.\n"); } // 1 2 8 9 // 2 4 9 12 // 4 7 10 13 // 6 8 11 15 // ่ฆๆŸฅๆ‰พ็š„ๆ•ฐๅœจๆ•ฐ็ป„ไธญ void Test1() { int matrix[][4] = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}}; Test("Test1", (int*)matrix, 4, 4, 7, true); } // 1 2 8 9 // 2 4 9 12 // 4 7 10 13 // 6 8 11 15 // ่ฆๆŸฅๆ‰พ็š„ๆ•ฐไธๅœจๆ•ฐ็ป„ไธญ void Test2() { int matrix[][4] = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}}; Test("Test2", (int*)matrix, 4, 4, 5, false); } // 1 2 8 9 // 2 4 9 12 // 4 7 10 13 // 6 8 11 15 // ่ฆๆŸฅๆ‰พ็š„ๆ•ฐๆ˜ฏๆ•ฐ็ป„ไธญๆœ€ๅฐ็š„ๆ•ฐๅญ— void Test3() { int matrix[][4] = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}}; Test("Test3", (int*)matrix, 4, 4, 1, true); } // 1 2 8 9 // 2 4 9 12 // 4 7 10 13 // 6 8 11 15 // ่ฆๆŸฅๆ‰พ็š„ๆ•ฐๆ˜ฏๆ•ฐ็ป„ไธญๆœ€ๅคง็š„ๆ•ฐๅญ— void Test4() { int matrix[][4] = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}}; Test("Test4", (int*)matrix, 4, 4, 15, true); } // 1 2 8 9 // 2 4 9 12 // 4 7 10 13 // 6 8 11 15 // ่ฆๆŸฅๆ‰พ็š„ๆ•ฐๆฏ”ๆ•ฐ็ป„ไธญๆœ€ๅฐ็š„ๆ•ฐๅญ—่ฟ˜ๅฐ void Test5() { int matrix[][4] = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}}; Test("Test5", (int*)matrix, 4, 4, 0, false); } // 1 2 8 9 // 2 4 9 12 // 4 7 10 13 // 6 8 11 15 // ่ฆๆŸฅๆ‰พ็š„ๆ•ฐๆฏ”ๆ•ฐ็ป„ไธญๆœ€ๅคง็š„ๆ•ฐๅญ—่ฟ˜ๅคง void Test6() { int matrix[][4] = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}}; Test("Test6", (int*)matrix, 4, 4, 16, false); } // ้ฒๆฃ’ๆ€งๆต‹่ฏ•๏ผŒ่พ“ๅ…ฅ็ฉบๆŒ‡้’ˆ void Test7() { Test("Test7", nullptr, 0, 0, 16, false); } int main(int argc, char* argv[]) { Test1(); Test2(); Test3(); Test4(); Test5(); Test6(); Test7(); return 0; }
21.589744
88
0.437648
darkkiller123
a36250d980acdca5e0a3c8a9818433ed00cc5c0a
759
hpp
C++
extlibs/lua/luapp/User.hpp
ToyAuthor/ToyBoxNote
accc792f5ab2fa8911dc1a70ffbfc6dfd02db9a6
[ "Unlicense" ]
9
2016-05-13T10:58:07.000Z
2022-03-02T20:35:24.000Z
extlibs/lua/luapp/User.hpp
ToyAuthor/ToyBoxNote
accc792f5ab2fa8911dc1a70ffbfc6dfd02db9a6
[ "Unlicense" ]
2
2018-09-19T03:32:28.000Z
2020-03-30T05:39:46.000Z
extlibs/lua/luapp/User.hpp
ToyAuthor/ToyBoxNote
accc792f5ab2fa8911dc1a70ffbfc6dfd02db9a6
[ "Unlicense" ]
7
2016-05-13T10:58:32.000Z
2021-05-10T02:11:23.000Z
#pragma once #include "luapp/Handle.hpp" #include "luapp/Register.hpp" namespace lua{ class User { public: User(){} ~User() { _item = NULL; // Just make sure it released before this->_lua. } void _set(lua::Handle h,lua::Register::Item i) { if ( _lua ) lua::Log<<"warning:why you set handle of function again?"<<lua::End; _item = i; _lua = h; } lua::Register::Item _getItem() { return this->_item; } private: lua::Handle _lua; lua::Register::Item _item; }; inline Var::Var(const lua::User &t):_ptr(0) { this->_ptr = new ::lua::_VarType<lua::User>(t); } inline Var& Var::operator = (const lua::User &t) { this->free_ptr(); this->_ptr = new ::lua::_VarType<lua::User>(t); return *this; } }
14.320755
83
0.602108
ToyAuthor
a363248f55efd0bbd443ac9ee880196450b501c8
1,456
cpp
C++
FGUI/widgets/image.cpp
Jacckii/fgui
668d80b00c8c3e7908f5f67dd42260fe04ac01e4
[ "MIT" ]
null
null
null
FGUI/widgets/image.cpp
Jacckii/fgui
668d80b00c8c3e7908f5f67dd42260fe04ac01e4
[ "MIT" ]
null
null
null
FGUI/widgets/image.cpp
Jacckii/fgui
668d80b00c8c3e7908f5f67dd42260fe04ac01e4
[ "MIT" ]
null
null
null
// // FGUI - feature rich graphical user interface // // library includes #include "image.hpp" namespace FGUI { CImage::CImage() { m_strTitle = "Image"; m_dmSize = { 100, 100 }; m_ulFont = 0; m_nType = static_cast<int>(WIDGET_TYPE::IMAGE); m_nFlags = static_cast<int>(WIDGET_FLAG::DRAWABLE); m_pImage = nullptr; m_fScale = 1.f; m_fRotation = 0.f; m_clColor = { 255, 255, 255, 255 }; m_clBGColor = { 255, 255, 255, 255 }; } void CImage::SetImage(unsigned char* image) { m_pImage = image; } void CImage::SetScale(float scale) { m_fScale = scale; } void CImage::SetRotation(float rotation) { m_fRotation = rotation; } void CImage::SetColor(FGUI::COLOR color) { m_clColor = color; } void CImage::SetBgColor(FGUI::COLOR color) { m_clBGColor = color; } void CImage::Geometry() { // widget's area FGUI::AREA arWidgetRegion = { GetAbsolutePosition().m_iX, GetAbsolutePosition().m_iY, m_dmSize.m_iWidth, m_dmSize.m_iHeight }; // Background color FGUI::RENDER.Rectangle(arWidgetRegion.m_iLeft, arWidgetRegion.m_iTop, arWidgetRegion.m_iRight, arWidgetRegion.m_iBottom, m_clBGColor); // Image clipping depends on the size of the widget if (m_pImage) FGUI::RENDER.Sprite(m_pImage, arWidgetRegion.m_iLeft, arWidgetRegion.m_iTop, arWidgetRegion.m_iRight, arWidgetRegion.m_iBottom, m_fScale, m_fRotation, m_clColor); } void CImage::Update() { } void CImage::Input() { } } // namespace FGUI
21.731343
165
0.701236
Jacckii
a36387191b68063439acfdd8a7bc5aff1bd41d38
11,795
cpp
C++
examples/cpp98/SbeOtfDecoder.cpp
qbm/simple-binary-encoding
f85121528f57c6ffa189672eec6084a50189b072
[ "Apache-2.0" ]
1
2020-12-02T23:00:19.000Z
2020-12-02T23:00:19.000Z
examples/cpp98/SbeOtfDecoder.cpp
qbm/simple-binary-encoding
f85121528f57c6ffa189672eec6084a50189b072
[ "Apache-2.0" ]
null
null
null
examples/cpp98/SbeOtfDecoder.cpp
qbm/simple-binary-encoding
f85121528f57c6ffa189672eec6084a50189b072
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2013 Real Logic Ltd. * * 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. */ #if defined(WIN32) #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #else #include <sys/types.h> #include <sys/uio.h> #include <unistd.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #endif /* WIN32 */ #include <iostream> #include <string> #include "otf_api/Listener.h" #include "otf_api/IrCollection.h" using namespace sbe::on_the_fly; using namespace uk_co_real_logic_sbe_ir_generated; // class to encapsulate Ir repository as well as Ir callback for dispatch class IrRepo : public IrCollection, public Ir::Callback { public: // save a reference to the Listener so we can print out the offset IrRepo(Listener &listener) : listener_(listener) {}; virtual Ir *irForTemplateId(const int templateId, const int templateVersion) { std::cout << "Message lookup id=" << templateId << " version " << templateVersion << " offset " << listener_.bufferOffset() << std::endl; // lookup in IrCollection the IR for the template ID and version return (Ir *)IrCollection::message(templateId, templateVersion); }; private: Listener &listener_; }; // class to encapsulate all the callbacks class CarCallbacks : public OnNext, public OnError, public OnCompleted { public: // save reference to listener for printing offset CarCallbacks(Listener &listener) : listener_(listener) , indent_(0) {}; // callback for when a field is encountered virtual int onNext(const Field &f) { std::cout << "Field name=\"" << f.fieldName() << "\" id=" << f.schemaId(); if (f.isComposite()) { std::cout << ", composite name=\"" << f.compositeName() << "\""; } std::cout << std::endl; if (f.isEnum()) { std::cout << " Enum [" << f.validValue() << "]"; printEncoding(f, 0); // print the encoding. Index is 0. } else if (f.isSet()) { std::cout << " Set "; // print the various names for the bits that are set for (std::vector<std::string>::iterator it = ((std::vector<std::string>&)f.choices()).begin(); it != f.choices().end(); ++it) { std::cout << "[" << *it << "]"; } printEncoding(f, 0); // print the encoding. Index is 0. } else if (f.isVariableData()) { // index 0 is the length field type, value, etc. // index 1 is the actual variable length data std::cout << " Variable Data length=" << f.length(1); char tmp[256]; f.getArray(1, tmp, 0, f.length(1)); // copy the data std::cout << " value=\"" << std::string(tmp, f.length(1)) << "\""; std::cout << " presence=" << presenceStr(f.presence(1)); // printing out meta attributes // std::cout << " epoch=\"" << f.getMetaAttribute(Field::EPOCH, 1) << "\""; // std::cout << " timeUnit=\"" << f.getMetaAttribute(Field::TIME_UNIT, 1) << "\""; // std::cout << " semanticType=\"" << f.getMetaAttribute(Field::SEMANTIC_TYPE, 1) << "\""; std::cout << std::endl; } else // if not enum, set, or var data, then just normal encodings, but could be composite { for (int i = 0, size = f.numEncodings(); i < size; i++) { printEncoding(f, i); } } return 0; }; // callback for when a group is encountered virtual int onNext(const Group &g) { // group started if (g.event() == Group::START) { std::cout << "Group name=\"" << g.name() << "\" id=\"" << g.schemaId() << "\" start ("; std::cout << g.iteration() << "/" << g.numInGroup() - 1 << "):" << "\n"; if (g.iteration() == 1) { indent_++; } } else if (g.event() == Group::END) // group ended { std::cout << "Group name=\"" << g.name() << "\" id=\"" << g.schemaId() << "\" end ("; std::cout << g.iteration() << "/" << g.numInGroup() - 1 << "):" << "\n"; if (g.iteration() == g.numInGroup() - 1) { indent_--; } } return 0; }; // callback for when an error is encountered virtual int onError(const Error &e) { std::cout << "Error " << e.message() << " at offset " << listener_.bufferOffset() << "\n"; return 0; }; // callback for when decoding is completed virtual int onCompleted() { std::cout << "Completed" << "\n"; return 0; }; protected: // print out details of an encoding void printEncoding(const Field &f, int index) { std::cout << " name=\"" << f.encodingName(index) << "\" length=" << f.length(index); switch (f.primitiveType(index)) { case Ir::CHAR: if (f.length(index) == 1) { std::cout << " type=CHAR value=\"" << (char)f.getUInt(index) << "\""; } else { char tmp[1024]; // copy data to temp array and print it out. f.getArray(index, tmp, 0, f.length(index)); std::cout << " type=CHAR value=\"" << std::string(tmp, f.length(index)) << "\""; } break; case Ir::INT8: std::cout << " type=INT8 value=\"" << f.getInt(index) << "\""; break; case Ir::INT16: std::cout << " type=INT16 value=\"" << f.getInt(index) << "\""; break; case Ir::INT32: if (f.length() == 1) { std::cout << " type=INT32 value=\"" << f.getInt(index) << "\""; } else { char tmp[1024]; // copy data to temp array and print it out. f.getArray(index, tmp, 0, f.length(index)); std::cout << " type=INT32 value="; for (int i = 0, size = f.length(index); i < size; i++) { std::cout << "{" << *((int32_t *)(tmp + (sizeof(int32_t) * i))) << "}"; } } break; case Ir::INT64: std::cout << " type=INT64 value=\"" << f.getInt(index) << "\""; break; case Ir::UINT8: std::cout << " type=UINT8 value=\"" << f.getUInt(index) << "\""; break; case Ir::UINT16: std::cout << " type=UINT16 value=\"" << f.getUInt(index) << "\""; break; case Ir::UINT32: std::cout << " type=UINT32 value=\"" << f.getUInt(index) << "\""; break; case Ir::UINT64: std::cout << " type=UINT64 value=\"" << f.getUInt(index) << "\""; break; case Ir::FLOAT: std::cout << " type=FLOAT value=\"" << f.getDouble(index) << "\""; break; case Ir::DOUBLE: std::cout << " type=DOUBLE value=\"" << f.getDouble(index) << "\""; break; default: break; } std::cout << " presence=" << presenceStr(f.presence(index)); // printing out meta attributes for encodings // std::cout << " epoch=\"" << f.getMetaAttribute(Field::EPOCH, index) << "\""; // std::cout << " timeUnit=\"" << f.getMetaAttribute(Field::TIME_UNIT, index) << "\""; // std::cout << " semanticType=\"" << f.getMetaAttribute(Field::SEMANTIC_TYPE, index) << "\""; std::cout << std::endl; } // print presence const char *presenceStr(Ir::TokenPresence presence) { switch (presence) { case Ir::REQUIRED: return "REQUIRED"; break; case Ir::OPTIONAL: return "OPTIONAL"; break; case Ir::CONSTANT: return "CONSTANT"; break; default: return "UNKNOWN"; break; } } private: Listener &listener_; int indent_; }; // helper function to read in file and save to a buffer char *readFileIntoBuffer(const char *filename, int *length) { struct stat fileStat; if (::stat(filename, &fileStat) != 0) { return NULL; } *length = fileStat.st_size; std::cout << "Encoded filename " << filename << " length " << *length << std::endl; char *buffer = new char[*length]; FILE *fptr = ::fopen(filename, "r"); int remaining = *length; if (fptr == NULL) { return NULL; } int fd = fileno(fptr); while (remaining > 0) { int sz = ::read(fd, buffer + (*length - remaining), (4098 < remaining) ? 4098 : remaining); remaining -= sz; if (sz < 0) { break; } } fclose(fptr); return buffer; } void usage(const char *argv0) { std::cout << argv0 << " irFile messageFile" << "\n"; } int main(int argc, char * const argv[]) { Listener listener; IrRepo repo(listener); CarCallbacks carCbs(listener); char *buffer = NULL; int length = 0, ch, justHeader = 0; #if defined(WIN32) int optind = 1; if (strcmp(argv[optind], "-?") == 0) { usage(argv[0]); exit(-1); } else if (strcmp(argv[optind], "-h") == 0) { justHeader++; optind++; } #else while ((ch = ::getopt(argc, argv, "h")) != -1) { switch (ch) { case 'h': justHeader++; break; case '?': default: usage(argv[0]); break; } } #endif /* WIN32 */ // load IR from .sbeir file if (repo.loadFromFile(argv[optind]) < 0) { std::cout << "could not load IR" << std::endl; exit(-1); } // load data from file into a buffer if ((buffer = ::readFileIntoBuffer(argv[optind+1], &length)) == NULL) { std::cout << "could not load encoding" << std::endl; exit(-1); } std::cout << "Decoding..." << std::endl; // if all we want is header, then set up IR for header, decode, and print out offset and header fields if (justHeader) { listener.ir(repo.header()) .resetForDecode(buffer, length) .subscribe(&carCbs, &carCbs, &carCbs); std::cout << "Message starts at offset " << listener.bufferOffset() << "\n"; return 0; } // set up listener and kick off decoding with subscribe listener.dispatchMessageByHeader(repo.header(), &repo) .resetForDecode(buffer, length) .subscribe(&carCbs, &carCbs, &carCbs); std::cout << "Message ends at offset " << listener.bufferOffset() << "\n"; delete[] buffer; return 0; }
30.089286
145
0.496058
qbm
a3644f90541ba6e72d5ab20e6897af175ea4207f
8,064
cpp
C++
libcaf_core/src/actor_pool.cpp
samanbarghi/actor-framework
9fb82f556760e1004e27fb4d303499b603a3fc19
[ "BSL-1.0", "BSD-3-Clause" ]
2
2020-08-25T15:22:08.000Z
2021-03-05T16:29:24.000Z
libcaf_core/src/actor_pool.cpp
wujsy/actor-framework
9fb82f556760e1004e27fb4d303499b603a3fc19
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
libcaf_core/src/actor_pool.cpp
wujsy/actor-framework
9fb82f556760e1004e27fb4d303499b603a3fc19
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2016 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include "caf/actor_pool.hpp" #include <atomic> #include <random> #include "caf/send.hpp" #include "caf/default_attachable.hpp" #include "caf/detail/sync_request_bouncer.hpp" namespace caf { actor_pool::policy actor_pool::round_robin() { struct impl { impl() : pos_(0) { // nop } impl(const impl&) : pos_(0) { // nop } void operator()(actor_system&, uplock& guard, const actor_vec& vec, mailbox_element_ptr& ptr, execution_unit* host) { CAF_ASSERT(!vec.empty()); actor selected = vec[pos_++ % vec.size()]; guard.unlock(); selected->enqueue(std::move(ptr), host); } std::atomic<size_t> pos_; }; return impl{}; } namespace { void broadcast_dispatch(actor_system&, actor_pool::uplock&, const actor_pool::actor_vec& vec, mailbox_element_ptr& ptr, execution_unit* host) { CAF_ASSERT(!vec.empty()); auto msg = ptr->move_content_to_message(); for (auto& worker : vec) worker->enqueue(ptr->sender, ptr->mid, msg, host); } } // namespace <anonymous> actor_pool::policy actor_pool::broadcast() { return broadcast_dispatch; } actor_pool::policy actor_pool::random() { struct impl { impl() : rd_() { // nop } impl(const impl&) : rd_() { // nop } void operator()(actor_system&, uplock& guard, const actor_vec& vec, mailbox_element_ptr& ptr, execution_unit* host) { upgrade_to_unique_lock<detail::shared_spinlock> unique_guard{guard}; auto selected = vec[dis_(rd_, decltype(dis_)::param_type(0, vec.size() - 1))]; unique_guard.unlock(); selected->enqueue(std::move(ptr), host); } std::random_device rd_; std::uniform_int_distribution<size_t> dis_; }; return impl{}; } actor_pool::~actor_pool() { // nop } actor actor_pool::make(execution_unit* eu, policy pol) { CAF_ASSERT(eu); auto& sys = eu->system(); actor_config cfg{eu}; auto res = make_actor<actor_pool, actor>(sys.next_actor_id(), sys.node(), &sys, cfg); auto ptr = static_cast<actor_pool*>(actor_cast<abstract_actor*>(res)); ptr->policy_ = std::move(pol); return res; } actor actor_pool::make(execution_unit* eu, size_t num_workers, const factory& fac, policy pol) { auto res = make(eu, std::move(pol)); auto ptr = static_cast<actor_pool*>(actor_cast<abstract_actor*>(res)); auto res_addr = ptr->address(); for (size_t i = 0; i < num_workers; ++i) { auto worker = fac(); worker->attach(default_attachable::make_monitor(worker.address(), res_addr)); ptr->workers_.push_back(std::move(worker)); } return res; } void actor_pool::enqueue(mailbox_element_ptr what, execution_unit* eu) { upgrade_lock<detail::shared_spinlock> guard{workers_mtx_}; if (filter(guard, what->sender, what->mid, *what, eu)) return; policy_(home_system(), guard, workers_, what, eu); } actor_pool::actor_pool(actor_config& cfg) : monitorable_actor(cfg) { register_at_system(); } void actor_pool::on_cleanup() { // nop } bool actor_pool::filter(upgrade_lock<detail::shared_spinlock>& guard, const strong_actor_ptr& sender, message_id mid, message_view& mv, execution_unit* eu) { auto& content = mv.content(); CAF_LOG_TRACE(CAF_ARG(mid) << CAF_ARG(content)); if (content.match_elements<exit_msg>()) { // acquire second mutex as well std::vector<actor> workers; auto em = content.get_as<exit_msg>(0).reason; if (cleanup(std::move(em), eu)) { auto tmp = mv.move_content_to_message(); // send exit messages *always* to all workers and clear vector afterwards // but first swap workers_ out of the critical section upgrade_to_unique_lock<detail::shared_spinlock> unique_guard{guard}; workers_.swap(workers); unique_guard.unlock(); for (auto& w : workers) anon_send(w, tmp); unregister_from_system(); } return true; } if (content.match_elements<down_msg>()) { // remove failed worker from pool auto& dm = content.get_as<down_msg>(0); upgrade_to_unique_lock<detail::shared_spinlock> unique_guard{guard}; auto last = workers_.end(); auto i = std::find(workers_.begin(), workers_.end(), dm.source); CAF_LOG_DEBUG_IF(i == last, "received down message for an unknown worker"); if (i != last) workers_.erase(i); if (workers_.empty()) { planned_reason_ = exit_reason::out_of_workers; unique_guard.unlock(); quit(eu); } return true; } if (content.match_elements<sys_atom, put_atom, actor>()) { auto& worker = content.get_as<actor>(2); worker->attach(default_attachable::make_monitor(worker.address(), address())); upgrade_to_unique_lock<detail::shared_spinlock> unique_guard{guard}; workers_.push_back(worker); return true; } if (content.match_elements<sys_atom, delete_atom, actor>()) { upgrade_to_unique_lock<detail::shared_spinlock> unique_guard{guard}; auto& what = content.get_as<actor>(2); auto last = workers_.end(); auto i = std::find(workers_.begin(), last, what); if (i != last) { default_attachable::observe_token tk{address(), default_attachable::monitor}; what->detach(tk); workers_.erase(i); } return true; } if (content.match_elements<sys_atom, delete_atom>()) { upgrade_to_unique_lock<detail::shared_spinlock> unique_guard{guard}; for (auto& worker : workers_) { default_attachable::observe_token tk{address(), default_attachable::monitor}; worker->detach(tk); } workers_.clear(); return true; } if (content.match_elements<sys_atom, get_atom>()) { auto cpy = workers_; guard.unlock(); sender->enqueue(nullptr, mid.response_id(), make_message(std::move(cpy)), eu); return true; } if (workers_.empty()) { guard.unlock(); if (sender && mid.valid()) { // tell client we have ignored this sync message by sending // and empty message back sender->enqueue(nullptr, mid.response_id(), message{}, eu); } return true; } return false; } void actor_pool::quit(execution_unit* host) { // we can safely run our cleanup code here without holding // workers_mtx_ because abstract_actor has its own lock if (cleanup(planned_reason_, host)) unregister_from_system(); } } // namespace caf
35.06087
81
0.571925
samanbarghi
a3685a3ea983e350dccc5d77b35a49b1ca9913fc
258
cpp
C++
Hearts Of Greed/Project_HeartsOfGreed/UI_Image.cpp
x-mat-studio/HeartsOfGreed
2582b807627a32d6d73e5940525a1dcd13054636
[ "MIT" ]
3
2020-03-05T10:58:02.000Z
2020-05-15T16:16:17.000Z
Hearts Of Greed/Project_HeartsOfGreed/UI_Image.cpp
x-mat-studio/Project-2
2582b807627a32d6d73e5940525a1dcd13054636
[ "MIT" ]
1
2020-06-15T06:42:33.000Z
2020-06-15T06:42:33.000Z
Hearts Of Greed/Project_HeartsOfGreed/UI_Image.cpp
x-mat-studio/Project-2
2582b807627a32d6d73e5940525a1dcd13054636
[ "MIT" ]
1
2020-05-29T16:06:27.000Z
2020-05-29T16:06:27.000Z
#include "UI_Image.h" UI_Image::UI_Image(float x, float y, UI* parent, SDL_Rect rect, SDL_Texture* texture, bool dragable, bool interactable) : UI({ x, y }, parent, UI_TYPE::IMG, rect, interactable, dragable, texture) {} UI_Image::~UI_Image() {}
23.454545
121
0.686047
x-mat-studio
a36903e6a4140a28a483bbb4ecbe1d6b8b1e1e4f
3,156
cxx
C++
examples/testoled.cxx
rpineau/libSSD1306
bc6da70b886d12936028e4007a21471182dd1dee
[ "MIT" ]
null
null
null
examples/testoled.cxx
rpineau/libSSD1306
bc6da70b886d12936028e4007a21471182dd1dee
[ "MIT" ]
null
null
null
examples/testoled.cxx
rpineau/libSSD1306
bc6da70b886d12936028e4007a21471182dd1dee
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------- // // The MIT License (MIT) // // Copyright (c) 2017 Andrew Duncan // // 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 "OledFont8x16.h" #include "OledI2C.h" #include "LinuxKeys.h" #include <iostream> #include <random> //------------------------------------------------------------------------- int main() { try { SSD1306::OledI2C oled{"/dev/i2c-2", 0x3C}; drawString8x16(SSD1306::OledPoint{32, 24}, "Oled I" "\xFD" "C", SSD1306::PixelStyle::Set, oled); oled.displayUpdate(); //----------------------------------------------------------------- LinuxKeys linuxKeys; LinuxKeys::PressedKey key; //----------------------------------------------------------------- std::random_device randomDevice; std::mt19937 randomGenerator{randomDevice()}; std::uniform_int_distribution<> xDistribution{0, oled.width() - 1}; std::uniform_int_distribution<> yDistribution{0, oled.height() - 1}; //----------------------------------------------------------------- while(key.key != 27) { key = linuxKeys.pressed(); switch (key.key) { case 'i': oled.displayInverse(); break; case 'n': oled.displayNormal(); break; case '+': oled.displayOn(); break; case '-': oled.displayOff(); break; } SSD1306::OledPoint p{xDistribution(randomGenerator), yDistribution(randomGenerator)}; oled.xorPixel(p); oled.displayUpdate(); } oled.clear(); oled.displayUpdate(); } catch (std::exception& e) { std::cerr << e.what() << "\n"; } return 0; }
27.684211
76
0.503802
rpineau
a36c61ddf3eeb510653009ef9da7e84fb3323a79
3,022
hpp
C++
src/stan/lang/generator/write_begin_all_dims_row_maj_loop.hpp
drezap/stan
9b319ed125e2a7d14d0c9c246d2f462dad668537
[ "BSD-3-Clause" ]
null
null
null
src/stan/lang/generator/write_begin_all_dims_row_maj_loop.hpp
drezap/stan
9b319ed125e2a7d14d0c9c246d2f462dad668537
[ "BSD-3-Clause" ]
null
null
null
src/stan/lang/generator/write_begin_all_dims_row_maj_loop.hpp
drezap/stan
9b319ed125e2a7d14d0c9c246d2f462dad668537
[ "BSD-3-Clause" ]
1
2020-07-14T11:36:09.000Z
2020-07-14T11:36:09.000Z
#ifndef STAN_LANG_GENERATOR_WRITE_BEGIN_ALL_DIMS_ROW_MAJ_LOOP_HPP #define STAN_LANG_GENERATOR_WRITE_BEGIN_ALL_DIMS_ROW_MAJ_LOOP_HPP #include <stan/lang/ast.hpp> #include <stan/lang/generator/constants.hpp> #include <stan/lang/generator/generate_expression.hpp> #include <stan/lang/generator/generate_indent.hpp> #include <ostream> #include <string> #include <vector> namespace stan { namespace lang { /** * Generate the openings of a sequence of zero or more for loops * corresponding to all dimensions of a variable, with the * specified indentation level writing to the specified stream. * If specified, declare named size_t variable for each dimension * which avoids re-evaluation of size expression on each iteration. * * Indexing order is row major: array dims 1...N then row, col * * @param[in] var_decl variable declaration * @param[in] declare_size_vars if true, generate size_t var decls * @param[in] indent indentation level * @param[in,out] o stream for generating */ void write_begin_all_dims_row_maj_loop(const block_var_decl& var_decl, bool declare_size_vars, int indent, std::ostream& o) { std::string name(var_decl.name()); expression arg1(var_decl.type().innermost_type().arg1()); expression arg2(var_decl.type().innermost_type().arg2()); std::vector<expression> ar_var_dims = var_decl.type().array_lens(); for (size_t i = 0; i < ar_var_dims.size(); ++i) { generate_indent(indent, o); if (declare_size_vars) o << "size_t "; o << name << "_k_" << i << "_max__ = "; generate_expression(ar_var_dims[i], NOT_USER_FACING, o); o << ";" << EOL; } if (!is_nil(arg1)) { generate_indent(indent, o); if (declare_size_vars) o << "size_t "; o << name << "_j_1_max__ = "; generate_expression(arg1, NOT_USER_FACING, o); o << ";" << EOL; } if (!is_nil(arg2)) { generate_indent(indent, o); if (declare_size_vars) o << "size_t "; o << name << "_j_2_max__ = "; generate_expression(arg2, NOT_USER_FACING, o); o << ";" << EOL; } // nested for stmts open for (size_t i = 0; i < ar_var_dims.size(); ++i) { generate_indent(indent++, o); o << "for (size_t k_" << i << "__ = 0;" << " k_" << i << "__ < " << name << "_k_" << i << "_max__;" << " ++k_" << i << "__) {" << EOL; } if (!is_nil(arg1)) { generate_indent(indent++, o); o << "for (size_t j_1__ = 0; " << "j_1__ < " << name << "_j_1_max__;" << " ++j_1__) {" << EOL; } if (!is_nil(arg2)) { generate_indent(indent++, o); o << "for (size_t j_2__ = 0; " << "j_2__ < " << name << "_j_2_max__;" << " ++j_2__) {" << EOL; } } } } #endif
34.340909
74
0.56221
drezap
a36de87101135531ea505f8b958a45de015d86d6
33,501
cpp
C++
engine/source/Steel/Scripting/ScriptingCallsRegister.cpp
filscorporation/Engine
ff306f2c1129dbc7e3c4baed6bf99494747fa0cc
[ "MIT" ]
null
null
null
engine/source/Steel/Scripting/ScriptingCallsRegister.cpp
filscorporation/Engine
ff306f2c1129dbc7e3c4baed6bf99494747fa0cc
[ "MIT" ]
null
null
null
engine/source/Steel/Scripting/ScriptingCallsRegister.cpp
filscorporation/Engine
ff306f2c1129dbc7e3c4baed6bf99494747fa0cc
[ "MIT" ]
null
null
null
#include "ScriptingCallsRegister.h" #include "ComponentsInternalCalls.h" #include "EntityInternalCalls.h" #include "CoreInternalCalls.h" #include "UIInternalCalls.h" void ScriptingCallsRegister::RegisterInternalCalls() { mono_add_internal_call("Steel.Application::Quit_Internal", (void*)CoreInternalCalls::Application_Quit); mono_add_internal_call("Steel.Application::GetRuntimePath_Internal", (void*)CoreInternalCalls::Application_RuntimePath); mono_add_internal_call("Steel.Application::GetDataPath_Internal", (void*)CoreInternalCalls::Application_DataPath); mono_add_internal_call("Steel.Log::LogDebug_Internal", (void*)CoreInternalCalls::Log_LogDebug); mono_add_internal_call("Steel.Log::LogInfo_Internal", (void*)CoreInternalCalls::Log_LogInfo); mono_add_internal_call("Steel.Log::LogWarning_Internal", (void*)CoreInternalCalls::Log_LogWarning); mono_add_internal_call("Steel.Log::LogError_Internal", (void*)CoreInternalCalls::Log_LogError); mono_add_internal_call("Steel.Time::GetDeltaTime_Internal", (void*)CoreInternalCalls::Time_GetDeltaTime); mono_add_internal_call("Steel.Time::GetTimeScale_Internal", (void*)CoreInternalCalls::Time_GetTimeScale); mono_add_internal_call("Steel.Time::SetTimeScale_Internal", (void*)CoreInternalCalls::Time_SetTimeScale); mono_add_internal_call("Steel.Input::GetMousePosition_Internal", (void*)CoreInternalCalls::Input_GetMousePosition); mono_add_internal_call("Steel.Input::GetMouseScrollDelta_Internal", (void*)CoreInternalCalls::Input_GetMouseScrollDelta); mono_add_internal_call("Steel.Input::IsKeyPressed_Internal", (void*)CoreInternalCalls::Input_IsKeyPressed); mono_add_internal_call("Steel.Input::IsKeyJustPressed_Internal", (void*)CoreInternalCalls::Input_IsKeyJustPressed); mono_add_internal_call("Steel.Input::IsKeyJustReleased_Internal", (void*)CoreInternalCalls::Input_IsKeyJustReleased); mono_add_internal_call("Steel.Input::IsMousePressed_Internal", (void*)CoreInternalCalls::Input_IsMousePressed); mono_add_internal_call("Steel.Input::IsMouseJustPressed_Internal", (void*)CoreInternalCalls::Input_IsMouseJustPressed); mono_add_internal_call("Steel.Input::IsMouseJustReleased_Internal", (void*)CoreInternalCalls::Input_IsMouseJustReleased); mono_add_internal_call("Steel.Screen::GetWidth_Internal", (void*)CoreInternalCalls::Screen_GetWidth); mono_add_internal_call("Steel.Screen::SetWidth_Internal", (void*)CoreInternalCalls::Screen_SetWidth); mono_add_internal_call("Steel.Screen::GetHeight_Internal", (void*)CoreInternalCalls::Screen_GetHeight); mono_add_internal_call("Steel.Screen::SetHeight_Internal", (void*)CoreInternalCalls::Screen_SetHeight); mono_add_internal_call("Steel.Screen::GetFullscreen_Internal", (void*)CoreInternalCalls::Screen_GetFullscreen); mono_add_internal_call("Steel.Screen::SetFullscreen_Internal", (void*)CoreInternalCalls::Screen_SetFullscreen); mono_add_internal_call("Steel.Screen::GetIsMinimized_Internal", (void*)CoreInternalCalls::Screen_GetIsMinimized); mono_add_internal_call("Steel.Screen::GetColor_Internal", (void*)CoreInternalCalls::Screen_GetColor); mono_add_internal_call("Steel.Screen::SetColor_Internal", (void*)CoreInternalCalls::Screen_SetColor); mono_add_internal_call("Steel.Physics::Simulate_Internal", (void*)CoreInternalCalls::Physics_Simulate); mono_add_internal_call("Steel.Physics::PointCast_Internal", (void*)CoreInternalCalls::Physics_PointCast); mono_add_internal_call("Steel.Physics::AABBCast_Internal", (void*)CoreInternalCalls::Physics_AABBCast); mono_add_internal_call("Steel.Physics::LineCast_Internal", (void*)CoreInternalCalls::Physics_LineCast); mono_add_internal_call("Steel.Random::NextFloat_Internal", (void*)CoreInternalCalls::Random_NextFloat); mono_add_internal_call("Steel.Random::NextInt_Internal", (void*)CoreInternalCalls::Random_NextInt); mono_add_internal_call("Steel.Random::PerlinNoise_Internal", (void*)CoreInternalCalls::Random_PerlinNoise); mono_add_internal_call("Steel.ResourcesManager::LoadImage_Internal", (void*)CoreInternalCalls::ResourcesManager_LoadImage); mono_add_internal_call("Steel.ResourcesManager::LoadAsepriteData_Internal", (void*)CoreInternalCalls::ResourcesManager_LoadAsepriteData); mono_add_internal_call("Steel.ResourcesManager::LoadAudioTrack_Internal", (void*)CoreInternalCalls::ResourcesManager_LoadAudioTrack); mono_add_internal_call("Steel.ResourcesManager::LoadShader_Internal", (void*)CoreInternalCalls::ResourcesManager_LoadShader); mono_add_internal_call("Steel.ResourcesManager::CreateMaterial_Internal", (void*)CoreInternalCalls::ResourcesManager_CreateMaterial); mono_add_internal_call("Steel.AudioTrack::GetLength_Internal", (void*)CoreInternalCalls::AudioTrack_GetLength); mono_add_internal_call("Steel.Sprite::SetAsNormal_Internal", (void*)CoreInternalCalls::Sprite_SetAsNormal); mono_add_internal_call("Steel.Sprite::SetAsSpriteSheet_Internal", (void*)CoreInternalCalls::Sprite_SetAsSpriteSheet); mono_add_internal_call("Steel.Sprite::SetAs9Sliced_Internal", (void*)CoreInternalCalls::Sprite_SetAs9Sliced); mono_add_internal_call("Steel.Sprite::SetAs9Sliced_Internal2", (void*)CoreInternalCalls::Sprite_SetAs9Sliced2); mono_add_internal_call("Steel.Sprite::GetTextureID_Internal", (void*)CoreInternalCalls::Sprite_GetTextureID); mono_add_internal_call("Steel.Sprite::GetWidth_Internal", (void*)CoreInternalCalls::Sprite_GetWidth); mono_add_internal_call("Steel.Sprite::GetHeight_Internal", (void*)CoreInternalCalls::Sprite_GetHeight); mono_add_internal_call("Steel.Sprite::GetPixelsPerUnit_Internal", (void*)CoreInternalCalls::Sprite_GetPixelsPerUnit); mono_add_internal_call("Steel.Sprite::SetPixelsPerUnit_Internal", (void*)CoreInternalCalls::Sprite_SetPixelsPerUnit); mono_add_internal_call("Steel.Sprite::GetPivot_Internal", (void*)CoreInternalCalls::Sprite_GetPivot); mono_add_internal_call("Steel.Sprite::SetPivot_Internal", (void*)CoreInternalCalls::Sprite_SetPivot); mono_add_internal_call("Steel.Animation::FromSpriteSheet_Internal", (void*)CoreInternalCalls::Animation_FromSpriteSheet); mono_add_internal_call("Steel.Animation::FromSprites_Internal", (void*)CoreInternalCalls::Animation_FromSprites); mono_add_internal_call("Steel.Animation::GetName_Internal", (void*)CoreInternalCalls::Animation_GetName); mono_add_internal_call("Steel.Animation::SetName_Internal", (void*)CoreInternalCalls::Animation_SetName); mono_add_internal_call("Steel.Animation::GetLoop_Internal", (void*)CoreInternalCalls::Animation_GetLoop); mono_add_internal_call("Steel.Animation::SetLoop_Internal", (void*)CoreInternalCalls::Animation_SetLoop); mono_add_internal_call("Steel.Animation::GetLength_Internal", (void*)CoreInternalCalls::Animation_GetLength); mono_add_internal_call("Steel.Animation::EndWithEmptyFrame_Internal", (void*)CoreInternalCalls::Animation_EndWithEmptyFrame); mono_add_internal_call("Steel.AsepriteData::GetSprites_Internal", (void*)CoreInternalCalls::AsepriteData_GetSprites); mono_add_internal_call("Steel.AsepriteData::GetAnimations_Internal", (void*)CoreInternalCalls::AsepriteData_GetAnimations); mono_add_internal_call("Steel.AsepriteData::CreateEntityFromAsepriteData_Internal", (void*)CoreInternalCalls::AsepriteData_CreateEntityFromAsepriteData); mono_add_internal_call("Steel.Material::GetShader_Internal", (void*)CoreInternalCalls::Material_GetShader); mono_add_internal_call("Steel.Material::SetShader_Internal", (void*)CoreInternalCalls::Material_SetShader); mono_add_internal_call("Steel.Material::GetProperties_Internal", (void*)CoreInternalCalls::Material_GetProperties); mono_add_internal_call("Steel.Material::SetProperties_Internal", (void*)CoreInternalCalls::Material_SetProperties); mono_add_internal_call("Steel.Entity::CreateNewEntity_Internal", (void*)EntityInternalCalls::Entity_CreateNewEntity); mono_add_internal_call("Steel.Entity::CreateNewEntity_Internal2", (void*)EntityInternalCalls::Entity_CreateNewEntity2); mono_add_internal_call("Steel.Entity::CreateNewEntity_Internal3", (void*)EntityInternalCalls::Entity_CreateNewEntity3); mono_add_internal_call("Steel.Entity::DestroyEntity_Internal", (void*)EntityInternalCalls::Entity_DestroyEntity); mono_add_internal_call("Steel.Entity::AddComponent_Internal", (void*)EntityInternalCalls::Entity_AddComponent); mono_add_internal_call("Steel.Entity::AddScriptComponent_Internal", (void*)EntityInternalCalls::Entity_AddScriptComponent); mono_add_internal_call("Steel.Entity::HasComponent_Internal", (void *) EntityInternalCalls::Entity_HasComponent); mono_add_internal_call("Steel.Entity::HasScriptComponent_Internal", (void*)EntityInternalCalls::Entity_HasScriptComponent); mono_add_internal_call("Steel.Entity::GetScriptComponent_Internal", (void*)EntityInternalCalls::Entity_GetScriptComponent); mono_add_internal_call("Steel.Entity::RemoveComponent_Internal", (void*)EntityInternalCalls::Entity_RemoveComponent); mono_add_internal_call("Steel.Entity::RemoveScriptComponent_Internal", (void*)EntityInternalCalls::Entity_RemoveScriptComponent); mono_add_internal_call("Steel.Entity::GetUUID_Internal", (void*)EntityInternalCalls::Entity_GetUUID); mono_add_internal_call("Steel.Entity::GetName_Internal", (void*)EntityInternalCalls::Entity_GetName); mono_add_internal_call("Steel.Entity::SetName_Internal", (void*)EntityInternalCalls::Entity_SetName); mono_add_internal_call("Steel.Entity::GetParent_Internal", (void*)ComponentsInternalCalls::HierarchyNode_GetParent); mono_add_internal_call("Steel.Entity::SetParent_Internal", (void*)ComponentsInternalCalls::HierarchyNode_SetParent); mono_add_internal_call("Steel.Entity::GetChildren_Internal", (void*)ComponentsInternalCalls::HierarchyNode_GetChildren); mono_add_internal_call("Steel.Entity::GetIsActive_Internal", (void*)EntityInternalCalls::Entity_GetIsActive); mono_add_internal_call("Steel.Entity::GetIsActiveSelf_Internal", (void*)EntityInternalCalls::Entity_GetIsActiveSelf); mono_add_internal_call("Steel.Entity::SetIsActiveSelf_Internal", (void*)EntityInternalCalls::Entity_SetIsActiveSelf); mono_add_internal_call("Steel.Entity::IsDestroyed_Internal", (void*)EntityInternalCalls::Entity_IsDestroyed); mono_add_internal_call("Steel.Component::FindAllOfType_Internal", (void*)EntityInternalCalls::Component_FindAllOfType); mono_add_internal_call("Steel.Component::FindAllScriptsOfType_Internal", (void*)EntityInternalCalls::Component_FindAllScriptsOfType); mono_add_internal_call("Steel.Transformation::GetPosition_Internal", (void*)ComponentsInternalCalls::Transformation_GetPosition); mono_add_internal_call("Steel.Transformation::SetPosition_Internal", (void*)ComponentsInternalCalls::Transformation_SetPosition); mono_add_internal_call("Steel.Transformation::GetLocalPosition_Internal", (void*)ComponentsInternalCalls::Transformation_GetLocalPosition); mono_add_internal_call("Steel.Transformation::SetLocalPosition_Internal", (void*)ComponentsInternalCalls::Transformation_SetLocalPosition); mono_add_internal_call("Steel.Transformation::GetRotation_Internal", (void*)ComponentsInternalCalls::Transformation_GetRotation); mono_add_internal_call("Steel.Transformation::SetRotation_Internal", (void*)ComponentsInternalCalls::Transformation_SetRotation); mono_add_internal_call("Steel.Transformation::GetLocalRotation_Internal", (void*)ComponentsInternalCalls::Transformation_GetLocalRotation); mono_add_internal_call("Steel.Transformation::SetLocalRotation_Internal", (void*)ComponentsInternalCalls::Transformation_SetLocalRotation); mono_add_internal_call("Steel.Transformation::GetScale_Internal", (void*)ComponentsInternalCalls::Transformation_GetScale); mono_add_internal_call("Steel.Transformation::SetScale_Internal", (void*)ComponentsInternalCalls::Transformation_SetScale); mono_add_internal_call("Steel.Transformation::GetLocalScale_Internal", (void*)ComponentsInternalCalls::Transformation_GetLocalScale); mono_add_internal_call("Steel.Transformation::SetLocalScale_Internal", (void*)ComponentsInternalCalls::Transformation_SetLocalScale); mono_add_internal_call("Steel.AudioListener::GetVolume_Internal", (void*)ComponentsInternalCalls::AudioListener_GetVolume); mono_add_internal_call("Steel.AudioListener::SetVolume_Internal", (void*)ComponentsInternalCalls::AudioListener_SetVolume); mono_add_internal_call("Steel.AudioSource::GetVolume_Internal", (void*)ComponentsInternalCalls::AudioSource_GetVolume); mono_add_internal_call("Steel.AudioSource::SetVolume_Internal", (void*)ComponentsInternalCalls::AudioSource_SetVolume); mono_add_internal_call("Steel.AudioSource::GetLoop_Internal", (void*)ComponentsInternalCalls::AudioSource_GetLoop); mono_add_internal_call("Steel.AudioSource::SetLoop_Internal", (void*)ComponentsInternalCalls::AudioSource_SetLoop); mono_add_internal_call("Steel.AudioSource::Play_Internal", (void*)ComponentsInternalCalls::AudioSource_Play); mono_add_internal_call("Steel.AudioSource::Stop_Internal", (void*)ComponentsInternalCalls::AudioSource_Stop); mono_add_internal_call("Steel.SpriteRenderer::GetSprite_Internal", (void*)ComponentsInternalCalls::SpriteRenderer_GetSprite); mono_add_internal_call("Steel.SpriteRenderer::SetSprite_Internal", (void*)ComponentsInternalCalls::SpriteRenderer_SetSprite); mono_add_internal_call("Steel.SpriteRenderer::GetMaterial_Internal", (void*)ComponentsInternalCalls::SpriteRenderer_GetMaterial); mono_add_internal_call("Steel.SpriteRenderer::SetMaterial_Internal", (void*)ComponentsInternalCalls::SpriteRenderer_SetMaterial); mono_add_internal_call("Steel.SpriteRenderer::GetCustomMaterialProperties_Internal", (void*)ComponentsInternalCalls::SpriteRenderer_GetCustomMaterialProperties); mono_add_internal_call("Steel.SpriteRenderer::SetCustomMaterialProperties_Internal", (void*)ComponentsInternalCalls::SpriteRenderer_SetCustomMaterialProperties); mono_add_internal_call("Steel.MeshRenderer::GetMesh_Internal", (void*)ComponentsInternalCalls::MeshRenderer_GetMesh); mono_add_internal_call("Steel.MeshRenderer::SetMesh_Internal", (void*)ComponentsInternalCalls::MeshRenderer_SetMesh); mono_add_internal_call("Steel.MeshRenderer::GetMaterial_Internal", (void*)ComponentsInternalCalls::MeshRenderer_GetMaterial); mono_add_internal_call("Steel.MeshRenderer::SetMaterial_Internal", (void*)ComponentsInternalCalls::MeshRenderer_SetMaterial); mono_add_internal_call("Steel.MeshRenderer::GetCustomMaterialProperties_Internal", (void*)ComponentsInternalCalls::MeshRenderer_GetCustomMaterialProperties); mono_add_internal_call("Steel.MeshRenderer::SetCustomMaterialProperties_Internal", (void*)ComponentsInternalCalls::MeshRenderer_SetCustomMaterialProperties); mono_add_internal_call("Steel.Animator::PlayAnimation_Internal", (void*)ComponentsInternalCalls::Animator_PlayAnimation); mono_add_internal_call("Steel.Animator::PlayAnimation_Internal2", (void*)ComponentsInternalCalls::Animator_PlayAnimation2); mono_add_internal_call("Steel.Animator::Play_Internal", (void*)ComponentsInternalCalls::Animator_Play); mono_add_internal_call("Steel.Animator::Pause_Internal", (void*)ComponentsInternalCalls::Animator_Pause); mono_add_internal_call("Steel.Animator::Stop_Internal", (void*)ComponentsInternalCalls::Animator_Stop); mono_add_internal_call("Steel.Animator::Restart_Internal", (void*)ComponentsInternalCalls::Animator_Restart); mono_add_internal_call("Steel.Camera::GetEntityWithMainCamera_Internal", (void *) ComponentsInternalCalls::Camera_GetEntityWithMainCamera); mono_add_internal_call("Steel.Camera::GetWidth_Internal", (void*)ComponentsInternalCalls::Camera_GetWidth); mono_add_internal_call("Steel.Camera::SetWidth_Internal", (void*)ComponentsInternalCalls::Camera_SetWidth); mono_add_internal_call("Steel.Camera::GetHeight_Internal", (void*)ComponentsInternalCalls::Camera_GetHeight); mono_add_internal_call("Steel.Camera::SetHeight_Internal", (void*)ComponentsInternalCalls::Camera_SetHeight); mono_add_internal_call("Steel.Camera::GetNearClippingPlane_Internal", (void*)ComponentsInternalCalls::Camera_GetNearClippingPlane); mono_add_internal_call("Steel.Camera::SetNearClippingPlane_Internal", (void*)ComponentsInternalCalls::Camera_SetNearClippingPlane); mono_add_internal_call("Steel.Camera::GetFarClippingPlane_Internal", (void*)ComponentsInternalCalls::Camera_GetFarClippingPlane); mono_add_internal_call("Steel.Camera::SetFarClippingPlane_Internal", (void*)ComponentsInternalCalls::Camera_SetFarClippingPlane); mono_add_internal_call("Steel.Camera::GetResizingMode_Internal", (void*)ComponentsInternalCalls::Camera_GetResizingMode); mono_add_internal_call("Steel.Camera::SetResizingMode_Internal", (void*)ComponentsInternalCalls::Camera_SetResizingMode); mono_add_internal_call("Steel.Camera::WorldToScreenPoint_Internal", (void*)ComponentsInternalCalls::Camera_WorldToScreenPoint); mono_add_internal_call("Steel.Camera::ScreenToWorldPoint_Internal", (void*)ComponentsInternalCalls::Camera_ScreenToWorldPoint); mono_add_internal_call("Steel.RigidBody::GetRigidBodyType_Internal", (void*)ComponentsInternalCalls::RigidBody_GetRigidBodyType); mono_add_internal_call("Steel.RigidBody::SetRigidBodyType_Internal", (void*)ComponentsInternalCalls::RigidBody_SetRigidBodyType); mono_add_internal_call("Steel.RigidBody::GetMass_Internal", (void*)ComponentsInternalCalls::RigidBody_GetMass); mono_add_internal_call("Steel.RigidBody::SetMass_Internal", (void*)ComponentsInternalCalls::RigidBody_SetMass); mono_add_internal_call("Steel.RigidBody::GetVelocity_Internal", (void*)ComponentsInternalCalls::RigidBody_GetVelocity); mono_add_internal_call("Steel.RigidBody::SetVelocity_Internal", (void*)ComponentsInternalCalls::RigidBody_SetVelocity); mono_add_internal_call("Steel.RigidBody::GetAngularVelocity_Internal", (void*)ComponentsInternalCalls::RigidBody_GetAngularVelocity); mono_add_internal_call("Steel.RigidBody::SetAngularVelocity_Internal", (void*)ComponentsInternalCalls::RigidBody_SetAngularVelocity); mono_add_internal_call("Steel.RigidBody::GetGravityScale_Internal", (void*)ComponentsInternalCalls::RigidBody_GetGravityScale); mono_add_internal_call("Steel.RigidBody::SetGravityScale_Internal", (void*)ComponentsInternalCalls::RigidBody_SetGravityScale); mono_add_internal_call("Steel.RigidBody::GetFriction_Internal", (void*)ComponentsInternalCalls::RigidBody_GetFriction); mono_add_internal_call("Steel.RigidBody::SetFriction_Internal", (void*)ComponentsInternalCalls::RigidBody_SetFriction); mono_add_internal_call("Steel.RigidBody::GetRestitution_Internal", (void*)ComponentsInternalCalls::RigidBody_GetRestitution); mono_add_internal_call("Steel.RigidBody::SetRestitution_Internal", (void*)ComponentsInternalCalls::RigidBody_SetRestitution); mono_add_internal_call("Steel.RigidBody::GetLinearDamping_Internal", (void*)ComponentsInternalCalls::RigidBody_GetLinearDamping); mono_add_internal_call("Steel.RigidBody::SetLinearDamping_Internal", (void*)ComponentsInternalCalls::RigidBody_SetLinearDamping); mono_add_internal_call("Steel.RigidBody::GetAngularDamping_Internal", (void*)ComponentsInternalCalls::RigidBody_GetAngularDamping); mono_add_internal_call("Steel.RigidBody::SetAngularDamping_Internal", (void*)ComponentsInternalCalls::RigidBody_SetAngularDamping); mono_add_internal_call("Steel.RigidBody::GetFixedRotation_Internal", (void*)ComponentsInternalCalls::RigidBody_GetFixedRotation); mono_add_internal_call("Steel.RigidBody::SetFixedRotation_Internal", (void*)ComponentsInternalCalls::RigidBody_SetFixedRotation); mono_add_internal_call("Steel.RigidBody::GetUseContinuousCollisionDetection_Internal", (void*)ComponentsInternalCalls::RigidBody_GetUseContinuousCollisionDetection); mono_add_internal_call("Steel.RigidBody::SetUseContinuousCollisionDetection_Internal", (void*)ComponentsInternalCalls::RigidBody_SetUseContinuousCollisionDetection); mono_add_internal_call("Steel.RigidBody::ApplyForce_Internal", (void*)ComponentsInternalCalls::RigidBody_ApplyForce); mono_add_internal_call("Steel.RigidBody::ApplyForce_Internal2", (void*)ComponentsInternalCalls::RigidBody_ApplyForce2); mono_add_internal_call("Steel.RigidBody::ApplyTorque_Internal", (void*)ComponentsInternalCalls::RigidBody_ApplyTorque); mono_add_internal_call("Steel.RigidBody::ApplyLinearImpulse_Internal", (void*)ComponentsInternalCalls::RigidBody_ApplyLinearImpulse); mono_add_internal_call("Steel.RigidBody::ApplyLinearImpulse_Internal2", (void*)ComponentsInternalCalls::RigidBody_ApplyLinearImpulse2); mono_add_internal_call("Steel.RigidBody::ApplyAngularImpulse_Internal", (void*)ComponentsInternalCalls::RigidBody_ApplyAngularImpulse); mono_add_internal_call("Steel.BoxCollider::GetSize_Internal", (void*)ComponentsInternalCalls::BoxCollider_GetSize); mono_add_internal_call("Steel.BoxCollider::SetSize_Internal", (void*)ComponentsInternalCalls::BoxCollider_SetSize); mono_add_internal_call("Steel.CircleCollider::GetRadius_Internal", (void*)ComponentsInternalCalls::CircleCollider_GetRadius); mono_add_internal_call("Steel.CircleCollider::SetRadius_Internal", (void*)ComponentsInternalCalls::CircleCollider_SetRadius); mono_add_internal_call("Steel.RectTransformation::GetAnchorMin_Internal", (void*)UIInternalCalls::RectTransformation_GetAnchorMin); mono_add_internal_call("Steel.RectTransformation::SetAnchorMin_Internal", (void*)UIInternalCalls::RectTransformation_SetAnchorMin); mono_add_internal_call("Steel.RectTransformation::GetAnchorMax_Internal", (void*)UIInternalCalls::RectTransformation_GetAnchorMax); mono_add_internal_call("Steel.RectTransformation::SetAnchorMax_Internal", (void*)UIInternalCalls::RectTransformation_SetAnchorMax); mono_add_internal_call("Steel.RectTransformation::GetAnchoredPosition_Internal", (void*)UIInternalCalls::RectTransformation_GetAnchoredPosition); mono_add_internal_call("Steel.RectTransformation::SetAnchoredPosition_Internal", (void*)UIInternalCalls::RectTransformation_SetAnchoredPosition); mono_add_internal_call("Steel.RectTransformation::GetOffsetMin_Internal", (void*)UIInternalCalls::RectTransformation_GetOffsetMin); mono_add_internal_call("Steel.RectTransformation::SetOffsetMin_Internal", (void*)UIInternalCalls::RectTransformation_SetOffsetMin); mono_add_internal_call("Steel.RectTransformation::GetOffsetMax_Internal", (void*)UIInternalCalls::RectTransformation_GetOffsetMax); mono_add_internal_call("Steel.RectTransformation::SetOffsetMax_Internal", (void*)UIInternalCalls::RectTransformation_SetOffsetMax); mono_add_internal_call("Steel.RectTransformation::GetPivot_Internal", (void*)UIInternalCalls::RectTransformation_GetPivot); mono_add_internal_call("Steel.RectTransformation::SetPivot_Internal", (void*)UIInternalCalls::RectTransformation_SetPivot); mono_add_internal_call("Steel.RectTransformation::GetSize_Internal", (void*)UIInternalCalls::RectTransformation_GetSize); mono_add_internal_call("Steel.RectTransformation::SetSize_Internal", (void*)UIInternalCalls::RectTransformation_SetSize); mono_add_internal_call("Steel.RectTransformation::GetSortingOrder_Internal", (void*)UIInternalCalls::RectTransformation_GetSortingOrder); mono_add_internal_call("Steel.RectTransformation::GetRotation_Internal", (void*)UIInternalCalls::RectTransformation_GetRotation); mono_add_internal_call("Steel.RectTransformation::SetRotation_Internal", (void*)UIInternalCalls::RectTransformation_SetRotation); mono_add_internal_call("Steel.UIImage::GetSprite_Internal", (void*)UIInternalCalls::UIImage_GetSprite); mono_add_internal_call("Steel.UIImage::SetSprite_Internal", (void*)UIInternalCalls::UIImage_SetSprite); mono_add_internal_call("Steel.UIImage::GetMaterial_Internal", (void*)UIInternalCalls::UIImage_GetMaterial); mono_add_internal_call("Steel.UIImage::SetMaterial_Internal", (void*)UIInternalCalls::UIImage_SetMaterial); mono_add_internal_call("Steel.UIImage::GetColor_Internal", (void*)UIInternalCalls::UIImage_GetColor); mono_add_internal_call("Steel.UIImage::SetColor_Internal", (void*)UIInternalCalls::UIImage_SetColor); mono_add_internal_call("Steel.UIImage::GetConsumeEvents_Internal", (void*)UIInternalCalls::UIImage_GetConsumeEvents); mono_add_internal_call("Steel.UIImage::SetConsumeEvents_Internal", (void*)UIInternalCalls::UIImage_SetConsumeEvents); mono_add_internal_call("Steel.UIImage::GetCustomMaterialProperties_Internal", (void*)UIInternalCalls::UIImage_GetCustomMaterialProperties); mono_add_internal_call("Steel.UIImage::SetCustomMaterialProperties_Internal", (void*)UIInternalCalls::UIImage_SetCustomMaterialProperties); mono_add_internal_call("Steel.UIButton::GetTargetImage_Internal", (void*)UIInternalCalls::UIButton_GetTargetImage); mono_add_internal_call("Steel.UIButton::SetTargetImage_Internal", (void*)UIInternalCalls::UIButton_SetTargetImage); mono_add_internal_call("Steel.UIButton::GetInteractable_Internal", (void*)UIInternalCalls::UIButton_GetInteractable); mono_add_internal_call("Steel.UIButton::SetInteractable_Internal", (void*)UIInternalCalls::UIButton_SetInteractable); mono_add_internal_call("Steel.UIButton::GetTransition_Internal", (void*)UIInternalCalls::UIButton_GetTransition); mono_add_internal_call("Steel.UIButton::SetTransition_Internal", (void*)UIInternalCalls::UIButton_SetTransition); mono_add_internal_call("Steel.UIText::GetText_Internal", (void*)UIInternalCalls::UIText_GetText); mono_add_internal_call("Steel.UIText::SetText_Internal", (void*)UIInternalCalls::UIText_SetText); mono_add_internal_call("Steel.UIText::GetTextSize_Internal", (void*)UIInternalCalls::UIText_GetTextSize); mono_add_internal_call("Steel.UIText::SetTextSize_Internal", (void*)UIInternalCalls::UIText_SetTextSize); mono_add_internal_call("Steel.UIText::GetLineSpacing_Internal", (void*)UIInternalCalls::UIText_GetLineSpacing); mono_add_internal_call("Steel.UIText::SetLineSpacing_Internal", (void*)UIInternalCalls::UIText_SetLineSpacing); mono_add_internal_call("Steel.UIText::GetColor_Internal", (void*)UIInternalCalls::UIText_GetColor); mono_add_internal_call("Steel.UIText::SetColor_Internal", (void*)UIInternalCalls::UIText_SetColor); mono_add_internal_call("Steel.UIText::GetIsTextAutoSize_Internal", (void*)UIInternalCalls::UIButton_GetIsTextAutoSize); mono_add_internal_call("Steel.UIText::SetIsTextAutoSize_Internal", (void*)UIInternalCalls::UIButton_SetIsTextAutoSize); mono_add_internal_call("Steel.UIText::GetTextAlignment_Internal", (void*)UIInternalCalls::UIButton_GetTextAlignment); mono_add_internal_call("Steel.UIText::SetTextAlignment_Internal", (void*)UIInternalCalls::UIButton_SetTextAlignment); mono_add_internal_call("Steel.UIText::GetTextOverflowMode_Internal", (void*)UIInternalCalls::UIButton_GetTextOverflowMode); mono_add_internal_call("Steel.UIText::SetTextOverflowMode_Internal", (void*)UIInternalCalls::UIButton_SetTextOverflowMode); mono_add_internal_call("Steel.UIInputField::GetTargetText_Internal", (void*)UIInternalCalls::UIInputField_GetTargetText); mono_add_internal_call("Steel.UIInputField::SetTargetText_Internal", (void*)UIInternalCalls::UIInputField_SetTargetText); mono_add_internal_call("Steel.UIInputField::GetTargetImage_Internal", (void*)UIInternalCalls::UIInputField_GetTargetImage); mono_add_internal_call("Steel.UIInputField::SetTargetImage_Internal", (void*)UIInternalCalls::UIInputField_SetTargetImage); mono_add_internal_call("Steel.UIInputField::GetInteractable_Internal", (void*)UIInternalCalls::UIInputField_GetInteractable); mono_add_internal_call("Steel.UIInputField::SetInteractable_Internal", (void*)UIInternalCalls::UIInputField_SetInteractable); mono_add_internal_call("Steel.UIInputField::GetCursorWidth_Internal", (void*)UIInternalCalls::UIInputField_GetCursorWidth); mono_add_internal_call("Steel.UIInputField::SetCursorWidth_Internal", (void*)UIInternalCalls::UIInputField_SetCursorWidth); mono_add_internal_call("Steel.UIInputField::GetCursorColor_Internal", (void*)UIInternalCalls::UIInputField_GetCursorColor); mono_add_internal_call("Steel.UIInputField::SetCursorColor_Internal", (void*)UIInternalCalls::UIInputField_SetCursorColor); mono_add_internal_call("Steel.UIInputField::GetCursorAutoColor_Internal", (void*)UIInternalCalls::UIInputField_GetAutoColor); mono_add_internal_call("Steel.UIInputField::SetCursorAutoColor_Internal", (void*)UIInternalCalls::UIInputField_SetAutoColor); mono_add_internal_call("Steel.UIInputField::GetIsMultiline_Internal", (void*)UIInternalCalls::UIInputField_GetIsMultiline); mono_add_internal_call("Steel.UIInputField::SetIsMultiline_Internal", (void*)UIInternalCalls::UIInputField_SetIsMultiline); mono_add_internal_call("Steel.UIInputField::GetTextType_Internal", (void*)UIInternalCalls::UIInputField_GetTextType); mono_add_internal_call("Steel.UIInputField::SetTextType_Internal", (void*)UIInternalCalls::UIInputField_SetTextType); mono_add_internal_call("Steel.UIInputField::GetSelectionColor_Internal", (void*)UIInternalCalls::UIInputField_GetSelectionColor); mono_add_internal_call("Steel.UIInputField::SetSelectionColor_Internal", (void*)UIInternalCalls::UIInputField_SetSelectionColor); mono_add_internal_call("Steel.UICheckBox::GetValue_Internal", (void*)UIInternalCalls::UICheckBox_GetValue); mono_add_internal_call("Steel.UICheckBox::SetValue_Internal", (void*)UIInternalCalls::UICheckBox_SetValue); mono_add_internal_call("Steel.UICheckBox::GetInteractable_Internal", (void*)UIInternalCalls::UICheckBox_GetInteractable); mono_add_internal_call("Steel.UICheckBox::SetInteractable_Internal", (void*)UIInternalCalls::UICheckBox_SetInteractable); mono_add_internal_call("Steel.UICheckBox::GetTransition_Internal", (void*)UIInternalCalls::UICheckBox_GetTransition); mono_add_internal_call("Steel.UICheckBox::SetTransition_Internal", (void*)UIInternalCalls::UICheckBox_SetTransition); mono_add_internal_call("Steel.UITabs::TabsCount_Internal", (void*)UIInternalCalls::UITabs_TabsCount); mono_add_internal_call("Steel.UITabs::GetActiveTab_Internal", (void*)UIInternalCalls::UITabs_GetActiveTab); mono_add_internal_call("Steel.UITabs::SetActiveTab_Internal", (void*)UIInternalCalls::UITabs_SetActiveTab); mono_add_internal_call("Steel.UITabs::GetTab_Internal", (void*)UIInternalCalls::UITabs_GetTab); mono_add_internal_call("Steel.UITabs::AddTab_Internal", (void*)UIInternalCalls::UITabs_AddTab); mono_add_internal_call("Steel.UITabs::RemoveTab_Internal", (void*)UIInternalCalls::UITabs_RemoveTab); mono_add_internal_call("Steel.UILayoutGroup::AddElement_Internal", (void*)UIInternalCalls::UILayoutGroup_AddElement); mono_add_internal_call("Steel.UILayoutGroup::AddElement_Internal2", (void*)UIInternalCalls::UILayoutGroup_AddElement2); mono_add_internal_call("Steel.UI::CreateUIElement_Internal", (void*)UIInternalCalls::UI_CreateUIElement); mono_add_internal_call("Steel.UI::CreateUIElement_Internal2", (void*)UIInternalCalls::UI_CreateUIElement2); mono_add_internal_call("Steel.UI::CreateUIElement_Internal3", (void*)UIInternalCalls::UI_CreateUIElement3); mono_add_internal_call("Steel.UI::CreateUIImage_Internal", (void*)UIInternalCalls::UI_CreateUIImage); mono_add_internal_call("Steel.UI::CreateUIImage_Internal2", (void*)UIInternalCalls::UI_CreateUIImage2); mono_add_internal_call("Steel.UI::CreateUIButton_Internal", (void*)UIInternalCalls::UI_CreateUIButton); mono_add_internal_call("Steel.UI::CreateUIButton_Internal2", (void*)UIInternalCalls::UI_CreateUIButton2); mono_add_internal_call("Steel.UI::CreateUIText_Internal", (void*)UIInternalCalls::UI_CreateUIText); mono_add_internal_call("Steel.UI::CreateUIText_Internal2", (void*)UIInternalCalls::UI_CreateUIText2); mono_add_internal_call("Steel.UI::CreateUIInputField_Internal", (void*)UIInternalCalls::UI_CreateUIInputField); mono_add_internal_call("Steel.UI::CreateUIInputField_Internal2", (void*)UIInternalCalls::UI_CreateUIInputField2); mono_add_internal_call("Steel.UI::CreateUIClipping_Internal", (void*)UIInternalCalls::UI_CreateUIClipping); mono_add_internal_call("Steel.UI::CreateUIClipping_Internal2", (void*)UIInternalCalls::UI_CreateUIClipping2); mono_add_internal_call("Steel.UI::CreateUICheckBox_Internal", (void*)UIInternalCalls::UI_CreateUICheckBox); mono_add_internal_call("Steel.UI::CreateUICheckBox_Internal2", (void*)UIInternalCalls::UI_CreateUICheckBox2); mono_add_internal_call("Steel.UI::CreateUITabs_Internal", (void*)UIInternalCalls::UI_CreateUITabs); mono_add_internal_call("Steel.UI::CreateUITabs_Internal2", (void*)UIInternalCalls::UI_CreateUITabs2); mono_add_internal_call("Steel.UI::CreateUILayoutGroup_Internal", (void*)UIInternalCalls::UI_CreateUILayoutGroup); mono_add_internal_call("Steel.UI::CreateUILayoutGroup_Internal2", (void*)UIInternalCalls::UI_CreateUILayoutGroup2); mono_add_internal_call("Steel.UI::IsPointerOverUI_Internal", (void*)UIInternalCalls::UI_IsPointerOverUI); }
109.839344
169
0.836154
filscorporation
a3717c38574302f0900bcf8ac646379da5edd8d9
1,458
inl
C++
pencil/include/util/geometry/geometry_v_align.inl
awarnke/crystal-facet-uml
89da1452379c53aef473b4dc28501a6b068d66a9
[ "Apache-2.0" ]
1
2021-06-06T05:57:21.000Z
2021-06-06T05:57:21.000Z
pencil/include/util/geometry/geometry_v_align.inl
awarnke/crystal-facet-uml
89da1452379c53aef473b4dc28501a6b068d66a9
[ "Apache-2.0" ]
1
2021-08-30T17:42:27.000Z
2021-08-30T17:42:27.000Z
pencil/include/util/geometry/geometry_v_align.inl
awarnke/crystal-facet-uml
89da1452379c53aef473b4dc28501a6b068d66a9
[ "Apache-2.0" ]
null
null
null
/* File: geometry_v_align.inl; Copyright and License: see below */ #include "trace.h" #include "tslog.h" static inline double geometry_v_align_get_top ( const geometry_v_align_t *this_, double height, double reference_top, double reference_height ) { double top; switch ( *this_ ) { case GEOMETRY_V_ALIGN_TOP: { top = reference_top; } break; case GEOMETRY_V_ALIGN_CENTER: { top = reference_top + 0.5 * ( reference_height - height ); } break; case GEOMETRY_V_ALIGN_BOTTOM: { top = reference_top + reference_height - height; } break; default: { TSLOG_ERROR("unknown geometry_v_align_t in geometry_v_align_get_top()"); assert(0); top = 0.0; } break; } return top; } /* Copyright 2017-2022 Andreas Warnke 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. */
25.137931
143
0.64952
awarnke
a37309f1979e7924aa427d69d3cb6ec2b1942ca1
1,716
cpp
C++
Practice/2018/2018.7.22/UVAlive7041.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
4
2017-10-31T14:25:18.000Z
2018-06-10T16:10:17.000Z
Practice/2018/2018.7.22/UVAlive7041.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
Practice/2018/2018.7.22/UVAlive7041.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; #define ll long long #define mem(Arr,x) memset(Arr,x,sizeof(Arr)) const int maxN=201000; const int maxAlpha=26; const int inf=2147483647; class Node { public: int son[maxAlpha]; int fail,len,cnt; void clear(){ mem(son,0);fail=len=cnt=0;return; } }; class PAM { public: Node S[maxN]; int last,nodecnt,pos; char str[maxN]; void Init(){ mem(str,'\0');pos=0; last=0;nodecnt=1;S[0].clear();S[1].clear(); S[0].len=0;S[1].len=-1; S[0].fail=S[1].fail=1; return; } void Insert(int c){ str[++pos]=c+10; int p=last; while (str[pos-1-S[p].len]!=str[pos]) p=S[p].fail; if (S[p].son[c]==0){ int np=++nodecnt,q=S[p].fail;S[np].clear(); while (str[pos-1-S[q].len]!=str[pos]) q=S[q].fail; S[np].len=S[p].len+2;S[np].fail=S[q].son[c];S[p].son[c]=np; } last=S[p].son[c];S[last].cnt++; return; } void Calc(){ for (int i=nodecnt;i>=2;i--) S[S[i].fail].cnt+=S[i].cnt; S[0].cnt=S[1].cnt=0; return; } }; char str1[maxN],str2[maxN]; PAM P1,P2; ll Ans=0; void dfs(int r1,int r2); int main() { int TTT;scanf("%d",&TTT); for (int ti=1;ti<=TTT;ti++) { P1.Init();P2.Init(); scanf("%s",str1+1); scanf("%s",str2+1); int l1=strlen(str1+1),l2=strlen(str2+1); for (int i=1;i<=l1;i++) P1.Insert(str1[i]-'a'); for (int i=1;i<=l2;i++) P2.Insert(str2[i]-'a'); P1.Calc();P2.Calc(); Ans=0; dfs(0,0); dfs(1,1); printf("Case #%d: %lld\n",ti,Ans); } return 0; } void dfs(int r1,int r2) { Ans=Ans+1ll*P1.S[r1].cnt*P2.S[r2].cnt; for (int i=0;i<maxAlpha;i++) if ((P1.S[r1].son[i])&&(P2.S[r2].son[i])) dfs(P1.S[r1].son[i],P2.S[r2].son[i]); return; }
17.875
81
0.583333
SYCstudio
a374c006818b15b9d458f0220737dad3533a36b4
1,391
cpp
C++
simulator/mips/mips_driver.cpp
Grigonoid/mipt-mips
c5f0bc9780556e668e8aa6e80094e55ecdece192
[ "MIT" ]
1
2019-11-13T15:30:56.000Z
2019-11-13T15:30:56.000Z
simulator/mips/mips_driver.cpp
Grigonoid/mipt-mips
c5f0bc9780556e668e8aa6e80094e55ecdece192
[ "MIT" ]
1
2019-11-13T15:26:28.000Z
2019-11-13T15:26:28.000Z
simulator/mips/mips_driver.cpp
Grigonoid/mipt-mips
c5f0bc9780556e668e8aa6e80094e55ecdece192
[ "MIT" ]
null
null
null
/** * driver.cpp - exception handler * @author Pavel Kryukov * Copyright 2019 MIPT-MIPS */ #include "mips.h" #include "mips_register/mips_register.h" #include <func_sim/driver/driver.h> #include <simulator.h> class DriverMIPS32 : public Driver { public: explicit DriverMIPS32( Simulator* sim) : cpu( sim) { } Trap handle_trap( const Operation& instr) const final { auto trap = instr.trap_type(); if ( trap == Trap::NO_TRAP || trap == Trap::HALT) return trap; auto status = cpu->read_cpu_register( MIPSRegister::status().to_rf_index()); auto cause = cpu->read_cpu_register( MIPSRegister::cause().to_rf_index()); status |= 0x2; cause = (cause & ~(bitmask<uint64>(4) << 2)) | ((trap.to_mips_format() & bitmask<uint64>(4)) << 2); cpu->write_cpu_register( MIPSRegister::status().to_rf_index(), status); cpu->write_cpu_register( MIPSRegister::cause().to_rf_index(), cause); cpu->write_cpu_register( MIPSRegister::epc().to_rf_index(), instr.get_PC()); cpu->set_pc( 0x8'0000'0180); return Trap( Trap::NO_TRAP); } std::unique_ptr<Driver> clone() const final { return std::make_unique<DriverMIPS32>( cpu); } private: Simulator* const cpu = nullptr; }; std::unique_ptr<Driver> create_mips32_driver( Simulator* sim) { return std::make_unique<DriverMIPS32>( sim); }
33.119048
107
0.654925
Grigonoid
a3755382599f1fb1cc591c95c23b3d9d87c15361
5,495
cpp
C++
test/test.cpp
Xwilarg/Colodex
8407888d648f7f512f5402d1c25c1dc582ad48d8
[ "MIT" ]
3
2021-09-08T03:13:07.000Z
2021-11-12T12:01:32.000Z
test/test.cpp
Xwilarg/Colodex
8407888d648f7f512f5402d1c25c1dc582ad48d8
[ "MIT" ]
null
null
null
test/test.cpp
Xwilarg/Colodex
8407888d648f7f512f5402d1c25c1dc582ad48d8
[ "MIT" ]
null
null
null
#define _ITERATOR_DEBUG_LEVEL 0 #include <gtest/gtest.h> extern "C" { #include "colodex/channel.h" #include "colodex/video.h" #include "colodex/client.h" } static char* getToken() { #ifdef _WIN32 char *token; size_t len; errno_t err = _dupenv_s(&token, &len, "HOLODEX_TOKEN"); if (err || token == NULL) { throw std::runtime_error("Token not found in environment"); } return token; #else char* token = getenv("HOLODEX_TOKEN"); if (token == NULL) { throw std::runtime_error("Token not found in environment"); } return token; #endif } TEST(ChannelTest, Basic) { char* token = getToken(); colodex_init(token); channel* ch = colodex_get_channel("UCsUj0dszADCGbF3gNrQEuSQ"); EXPECT_STREQ("UCsUj0dszADCGbF3gNrQEuSQ", ch->id); EXPECT_STREQ("Tsukumo Sana Ch. hololive-EN", ch->name); EXPECT_STREQ("Tsukumo Sana", ch->english_name); EXPECT_EQ(VTUBER, ch->type); EXPECT_STREQ("Hololive", ch->org); EXPECT_STREQ("i English (Council)", ch->suborg); EXPECT_STREQ("tsukumosana", ch->twitter); EXPECT_FALSE(ch->inactive); colodex_free_channel(ch); #ifdef _WIN32 free(token); // getenv() shouldn't be freed #endif colodex_free(); } TEST(VideoTest, Song) { char* token = getToken(); colodex_init(token); video* vid = colodex_get_video_from_id("-AuQZrUHjhg"); EXPECT_STREQ("-AuQZrUHjhg", vid->id); EXPECT_STREQ("[MV] Red - Calliope Mori #HololiveEnglish #HoloMyth", vid->title); EXPECT_EQ(STREAM, vid->type); EXPECT_STREQ("Original_Song", vid->topic_id); EXPECT_EQ(1617543014, vid->published_at); EXPECT_EQ(1617543014, vid->available_at); EXPECT_EQ(223, vid->duration); EXPECT_EQ(PAST, vid->status); EXPECT_EQ(1, vid->songcount); EXPECT_STREQ("UCL_qhgtOy0dy1Agp8vkySQg", vid->channel_info->id); EXPECT_STREQ("Mori Calliope Ch. hololive-EN", vid->channel_info->name); EXPECT_STREQ("Hololive", vid->channel_info->org); EXPECT_EQ(VTUBER, vid->channel_info->type); EXPECT_STREQ("https://yt3.ggpht.com/ytc/AKedOLQi2hR9UdCcWoDLz4sJYqAu9BkaYBGWex_th5ic=s800-c-k-c0x00ffffff-no-rj-mo", vid->channel_info->photo); EXPECT_STREQ("Mori Calliope", vid->channel_info->english_name); colodex_free_video(vid); #ifdef _WIN32 free(token); #endif colodex_free(); } TEST(VideoTest, StreamWithUnicode) { char* token = getToken(); colodex_init(token); video* vid = colodex_get_video_from_id("Lm1k8TI790Y"); EXPECT_STREQ("Lm1k8TI790Y", vid->id); EXPECT_STREQ("ใ€R6Sใ€‘็งใซใ‹ใ‹ใ‚Œใฐ่ฒ ใ‘nใ‚โ€ฆ ใƒผRainbow Six Siegeใ€็…็™ฝใผใŸใ‚“/ใƒ›ใƒญใƒฉใ‚คใƒ–ใ€‘", vid->title); EXPECT_EQ(STREAM, vid->type); EXPECT_STREQ("Rainbow_Six", vid->topic_id); EXPECT_EQ(1600056002, vid->published_at); EXPECT_EQ(1600056002, vid->available_at); EXPECT_EQ(701, vid->duration); EXPECT_EQ(PAST, vid->status); EXPECT_EQ(0, vid->songcount); EXPECT_STREQ("UCUKD-uaobj9jiqB-VXt71mA", vid->channel_info->id); EXPECT_STREQ("Botan Ch.็…็™ฝใผใŸใ‚“", vid->channel_info->name); EXPECT_STREQ("Hololive", vid->channel_info->org); EXPECT_EQ(VTUBER, vid->channel_info->type); EXPECT_STREQ("https://yt3.ggpht.com/ytc/AKedOLQXr6MeUpHI0-yNZIAaGXHvBVowhCWMwGx-zXYs=s800-c-k-c0x00ffffff-no-rj", vid->channel_info->photo); EXPECT_STREQ("Shishiro Botan", vid->channel_info->english_name); colodex_free_video(vid); #ifdef _WIN32 free(token); #endif colodex_free(); } TEST(VideoTest, StreamWithInvalidId) { char* token = getToken(); colodex_init(token); video* vid = colodex_get_video_from_id("0000000000000000"); EXPECT_EQ(nullptr, vid); #ifdef _WIN32 free(token); #endif colodex_free(); } TEST(VideosTest, OnlyUpcomingStreams) { char* token = getToken(); colodex_init(token); query_video* query = new query_video(); query->status = UPCOMING; video** vids = colodex_get_videos_from_channel_id("UCLhUvJ_wO9hOvv_yYENu4fQ", query, STATUS); delete query; for (video **it = vids; *it != NULL; it++) { EXPECT_EQ(UPCOMING, (*it)->status); // Can't really check much here :( } colodex_free_videos(vids); #ifdef _WIN32 free(token); #endif colodex_free(); } // These tests might be redundant with the others but we want to be sure the examples in the README run well! TEST(Readme, GetChannel) { char* token = getToken(); colodex_init(token); channel* ch = colodex_get_channel("UCsUj0dszADCGbF3gNrQEuSQ"); EXPECT_EQ( "The twitter ID of Tsukumo Sana from Hololive is tsukumosana\n", "The twitter ID of " + std::string(ch->english_name) + " from " + std::string(ch->org) + " is " + std::string(ch->twitter) + "\n" ); colodex_free_channel(ch); #ifdef _WIN32 free(token); // getenv() shouldn't be freed #endif colodex_free(); } TEST(Readme, GetUpcomingStreams) { char* token = getToken(); colodex_init(token); query_video* query = (query_video*)malloc(sizeof(query_video)); query->status = UPCOMING; query->type = STREAM; query->order = ASCENDING; query->limit = 5; video** vids = colodex_get_videos(query, (query_video_param)(STATUS | TYPE | ORDER | LIMIT)); free(query); for (video **it = vids; *it != NULL; it++) { EXPECT_EQ(UPCOMING, (*it)->status); // Can't really check much here :( } colodex_free_videos(vids); #ifdef _WIN32 free(token); // getenv() shouldn't be freed #endif colodex_free(); }
28.471503
147
0.672429
Xwilarg
a3757aba00f8f15a870f90741b3b1997025187d6
223
cpp
C++
TouchGFX_Ported_To_ILI9341_STM32F407G/TouchGFX/gui/src/apk2_screen/Apk2Presenter.cpp
trteodor/TouchGFX_Test
cd1abdef7e5a6f161ad35754fd951ea5de076021
[ "MIT" ]
1
2022-02-25T07:20:23.000Z
2022-02-25T07:20:23.000Z
TouchGFX_Ported_To_ILI9341_STM32F407G/TouchGFX/gui/src/apk2_screen/Apk2Presenter.cpp
trteodor/TouchGFX_Test
cd1abdef7e5a6f161ad35754fd951ea5de076021
[ "MIT" ]
null
null
null
TouchGFX_Ported_To_ILI9341_STM32F407G/TouchGFX/gui/src/apk2_screen/Apk2Presenter.cpp
trteodor/TouchGFX_Test
cd1abdef7e5a6f161ad35754fd951ea5de076021
[ "MIT" ]
1
2021-12-26T22:11:21.000Z
2021-12-26T22:11:21.000Z
#include <gui/apk2_screen/Apk2View.hpp> #include <gui/apk2_screen/Apk2Presenter.hpp> Apk2Presenter::Apk2Presenter(Apk2View& v) : view(v) { } void Apk2Presenter::activate() { } void Apk2Presenter::deactivate() { }
11.736842
44
0.721973
trteodor
a37a7db6df4d8de83d88e7e8f4a7569a24e7e233
1,986
hpp
C++
agency/detail/uninitialized.hpp
nerikhman/agency
966ac59101f2fc3561a86b11874fbe8de361d0e4
[ "BSD-3-Clause" ]
129
2016-08-18T23:24:15.000Z
2022-03-25T12:06:05.000Z
agency/detail/uninitialized.hpp
nerikhman/agency
966ac59101f2fc3561a86b11874fbe8de361d0e4
[ "BSD-3-Clause" ]
86
2016-08-19T03:43:33.000Z
2020-07-20T14:27:41.000Z
agency/detail/uninitialized.hpp
nerikhman/agency
966ac59101f2fc3561a86b11874fbe8de361d0e4
[ "BSD-3-Clause" ]
23
2016-08-18T23:52:13.000Z
2022-02-28T16:28:20.000Z
/* * Copyright 2008-2013 NVIDIA Corporation * * 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. */ #pragma once #include <agency/detail/config.hpp> #include <new> #include <type_traits> #include <utility> namespace agency { namespace detail { template<typename T> class uninitialized { private: typename std::aligned_storage< sizeof(T), std::alignment_of<T>::value >::type storage[1]; __AGENCY_ANNOTATION const T* ptr() const { const void *result = storage; return reinterpret_cast<const T*>(result); } __AGENCY_ANNOTATION T* ptr() { void *result = storage; return reinterpret_cast<T*>(result); } public: // copy assignment __AGENCY_ANNOTATION uninitialized<T> &operator=(const T &other) { T& self = *this; self = other; return *this; } __AGENCY_ANNOTATION T& get() { return *ptr(); } __AGENCY_ANNOTATION const T& get() const { return *ptr(); } __AGENCY_ANNOTATION operator T& () { return get(); } __AGENCY_ANNOTATION operator const T&() const { return get(); } template<class... Args> __AGENCY_ANNOTATION void construct(Args&&... args) { ::new(ptr()) T(std::forward<Args>(args)...); } __AGENCY_ANNOTATION void destroy() { T& self = *this; self.~T(); } }; } // end detail } // end agency
18.560748
76
0.618328
nerikhman
a37c803efb9ef9cecbcf302ee0a509417a1b5b8e
243
hpp
C++
include/core/Types.hpp
diego-gt/calvin-engine
8823a4262d243c70331a9b07303878edf81b2528
[ "MIT" ]
null
null
null
include/core/Types.hpp
diego-gt/calvin-engine
8823a4262d243c70331a9b07303878edf81b2528
[ "MIT" ]
null
null
null
include/core/Types.hpp
diego-gt/calvin-engine
8823a4262d243c70331a9b07303878edf81b2528
[ "MIT" ]
null
null
null
#pragma once using u8 = unsigned char; using u16 = unsigned short; using u32 = unsigned int; using u64 = unsigned long long; using i8 = char; using i16 = short; using i32 = int; using i64 = long long; using f32 = float; using f64 = double;
16.2
31
0.703704
diego-gt
a37cab742e514432948435512f8ed65ff2c55784
16,401
cpp
C++
examples/benchmark_matops.cpp
lwhZJU/raptor
cc8a68f1998c180dd696cb4c6b5fb18987fa60df
[ "BSD-2-Clause" ]
1
2019-03-28T08:05:11.000Z
2019-03-28T08:05:11.000Z
examples/benchmark_matops.cpp
lwhZJU/raptor
cc8a68f1998c180dd696cb4c6b5fb18987fa60df
[ "BSD-2-Clause" ]
null
null
null
examples/benchmark_matops.cpp
lwhZJU/raptor
cc8a68f1998c180dd696cb4c6b5fb18987fa60df
[ "BSD-2-Clause" ]
null
null
null
// Copyright (c) 2015-2017, RAPtor Developer Team // License: Simplified BSD, http://opensource.org/licenses/BSD-2-Clause #include <mpi.h> #include <math.h> #include <stdlib.h> #include <iostream> #include <assert.h> #include "clear_cache.hpp" #include "core/par_matrix.hpp" #include "core/par_vector.hpp" #include "core/types.hpp" #include "gallery/par_stencil.hpp" #include "gallery/laplacian27pt.hpp" #include "gallery/diffusion.hpp" #include "gallery/par_matrix_IO.hpp" #include "multilevel/par_multilevel.hpp" #include "ruge_stuben/par_ruge_stuben_solver.hpp" #ifdef USING_MFEM #include "gallery/external/mfem_wrapper.hpp" #endif #define eager_cutoff 1000 #define short_cutoff 62 void fast_waitall(int n_msgs, aligned_vector<MPI_Request>& requests) { if (n_msgs == 0) return; int recv_n, idx; aligned_vector<int> recv_indices(n_msgs); while (n_msgs) { MPI_Waitsome(n_msgs, requests.data(), &recv_n, recv_indices.data(), MPI_STATUSES_IGNORE); for (int i = 0; i < recv_n; i++) { idx = recv_indices[i]; requests[idx] = MPI_REQUEST_NULL; } idx = 0; for (int i = 0; i < n_msgs; i++) { if (requests[i] != MPI_REQUEST_NULL) requests[idx++] = requests[i]; } n_msgs -= recv_n; } return; } int main(int argc, char *argv[]) { MPI_Init(&argc, &argv); int rank, num_procs; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &num_procs); int dim; int n = 5; int system = 0; // Cube topology info int num_nodes = num_procs / 16; int node = rank / 16; int num_dir = cbrt(num_nodes); if (num_dir * num_dir * num_dir < num_nodes) num_dir++; int x_dim = num_dir; int y_dim = x_dim * num_dir; int z_dim = y_dim * num_dir; int x_pos = node % num_dir; int y_pos = (node / x_dim) % num_dir; int z_pos = (node / y_dim) % num_dir; aligned_vector<int> my_cube_pos(3); my_cube_pos[0] = x_pos; my_cube_pos[1] = y_pos; my_cube_pos[2] = z_pos; aligned_vector<int> cube_pos(3*num_procs); MPI_Allgather(my_cube_pos.data(), 3, MPI_INT, cube_pos.data(), 3, MPI_INT, MPI_COMM_WORLD); aligned_vector<int> proc_distances(num_procs); for (int i = 0; i < num_procs; i++) { proc_distances[i] = (fabs(cube_pos[i*3] - x_pos) + fabs(cube_pos[i*3+1] - y_pos) + fabs(cube_pos[i*3+2] - z_pos)); } // Mesh topology info x_dim = 24; y_dim = num_nodes; x_pos = node % 24; y_pos = (node / 24) % 24; my_cube_pos[0] = x_pos; my_cube_pos[1] = y_pos; MPI_Allgather(my_cube_pos.data(), 2, MPI_INT, cube_pos.data(), 2, MPI_INT, MPI_COMM_WORLD); aligned_vector<int> worst_proc_distances(num_procs); for (int i = 0; i < num_procs; i++) { worst_proc_distances[i] = (fabs(cube_pos[i*2] - x_pos) + fabs(cube_pos[i*2+1] - y_pos)); } if (argc > 1) { system = atoi(argv[1]); } ParCSRMatrix* A; ParVector x; ParVector b; double t0, tfinal; double t0_comm, tfinal_comm; int n0, s0; int nfinal, sfinal; double raptor_setup, raptor_solve; int num_variables = 1; relax_t relax_type = SOR; coarsen_t coarsen_type = CLJP; interp_t interp_type = ModClassical; double strong_threshold = 0.25; aligned_vector<double> residuals; if (system < 2) { double* stencil = NULL; aligned_vector<int> grid; if (argc > 2) { n = atoi(argv[2]); } if (system == 0) { dim = 3; grid.resize(dim, n); stencil = laplace_stencil_27pt(); } else if (system == 1) { dim = 2; grid.resize(dim, n); double eps = 0.001; double theta = M_PI/4.0; if (argc > 3) { eps = atof(argv[3]); if (argc > 4) { theta = atof(argv[4]); } } stencil = diffusion_stencil_2d(eps, theta); } A = par_stencil_grid(stencil, grid.data(), dim); delete[] stencil; } #ifdef USING_MFEM else if (system == 2) { const char* mesh_file = argv[2]; int mfem_system = 0; int order = 2; int seq_refines = 1; int par_refines = 1; int max_dofs = 1000000; if (argc > 3) { mfem_system = atoi(argv[3]); if (argc > 4) { order = atoi(argv[4]); if (argc > 5) { seq_refines = atoi(argv[5]); max_dofs = atoi(argv[5]); if (argc > 6) { par_refines = atoi(argv[6]); } } } } coarsen_type = HMIS; interp_type = Extended; strong_threshold = 0.0; switch (mfem_system) { case 0: A = mfem_laplacian(x, b, mesh_file, order, seq_refines, par_refines); break; case 1: A = mfem_grad_div(x, b, mesh_file, order, seq_refines, par_refines); break; case 2: strong_threshold = 0.5; A = mfem_linear_elasticity(x, b, &num_variables, mesh_file, order, seq_refines, par_refines); break; case 3: A = mfem_adaptive_laplacian(x, b, mesh_file, order); x.set_const_value(1.0); A->mult(x, b); x.set_const_value(0.0); break; case 4: A = mfem_dg_diffusion(x, b, mesh_file, order, seq_refines, par_refines); break; case 5: A = mfem_dg_elasticity(x, b, &num_variables, mesh_file, order, seq_refines, par_refines); break; } } #endif else if (system == 3) { const char* file = "../../examples/LFAT5.pm"; A = readParMatrix(file); } if (system != 2) { A->tap_comm = new TAPComm(A->partition, A->off_proc_column_map, A->on_proc_column_map); x = ParVector(A->global_num_cols, A->on_proc_num_cols, A->partition->first_local_col); b = ParVector(A->global_num_rows, A->local_num_rows, A->partition->first_local_row); x.set_rand_values(); A->mult(x, b); } ParMultilevel* ml; // Setup Raptor Hierarchy ml = new ParRugeStubenSolver(strong_threshold, coarsen_type, interp_type, Classical, relax_type); ml->num_variables = num_variables; ml->setup(A); int n_tests = 100; int n_spmv_tests = 1000; CSRMatrix* C; for (int i = 0; i < ml->num_levels - 1; i++) { ParCSRMatrix* Al = ml->levels[i]->A; ParCSRMatrix* Pl = ml->levels[i]->P; if (rank == 0) printf("Level %d\n", i); aligned_vector<int> rowptr(Pl->local_num_rows + 1); int nnz = Pl->on_proc->nnz + Pl->off_proc->nnz; aligned_vector<int> col_indices; aligned_vector<double> values; if (nnz) { col_indices.resize(nnz); values.resize(nnz); } rowptr[0] = 0; for (int j = 0; j < Pl->local_num_rows; j++) { int start = Pl->on_proc->idx1[j]; int end = Pl->on_proc->idx1[j+1]; for (int k = start; k < end; k++) { int col = Pl->on_proc->idx2[k]; double val = Pl->on_proc->vals[k]; col_indices.push_back(Pl->on_proc_column_map[col]); values.push_back(val); } start = Pl->off_proc->idx1[j]; end = Pl->off_proc->idx1[j+1]; for (int k = start; k < end; k++) { int col = Pl->off_proc->idx2[k]; double val = Pl->off_proc->vals[k]; col_indices.push_back(Pl->off_proc_column_map[col]); values.push_back(val); } rowptr[j+1] = col_indices.size(); } // Count Queue int queue_search = 0; MPI_Status status; int msg_s; aligned_vector<int> recv_idx(Al->comm->recv_data->num_msgs, 1); for (int send = 0; send < Al->comm->send_data->num_msgs; send++) { int proc = Al->comm->send_data->procs[send]; int start = Al->comm->send_data->indptr[send]; int end = Al->comm->send_data->indptr[send+1]; MPI_Isend(&Al->comm->send_data->buffer[start], end - start, MPI_DOUBLE, proc, 4938, MPI_COMM_WORLD, &Al->comm->send_data->requests[send]); } for (int recv = 0; recv < Al->comm->recv_data->num_msgs; recv++) { MPI_Probe(MPI_ANY_SOURCE, 4938, MPI_COMM_WORLD, &status); int proc = status.MPI_SOURCE; MPI_Get_count(&status, MPI_DOUBLE, &msg_s); MPI_Recv(&Al->comm->recv_data->buffer[0], msg_s, MPI_DOUBLE, proc, 4938, MPI_COMM_WORLD, &status); for (int idx = 0; idx < Al->comm->recv_data->num_msgs; idx++) { int proc_idx = Al->comm->recv_data->procs[idx]; if (proc == proc_idx) { queue_search++; recv_idx[idx] = 0; break; } queue_search += recv_idx[idx]; } } if (Al->comm->send_data->num_msgs) MPI_Waitall(Al->comm->send_data->num_msgs, Al->comm->send_data->requests.data(), MPI_STATUSES_IGNORE); int max_queue = 0; MPI_Allreduce(&queue_search, &max_queue, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD); int msg_n = 0; if (queue_search == max_queue) msg_n = Al->comm->recv_data->num_msgs; MPI_Allreduce(MPI_IN_PLACE, &msg_n, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD); if (rank == 0) printf("MaxQueueN %d\t MsgN %d\n", max_queue, msg_n); if (rank == 0) printf("A*P:\n"); //Al->print_mult(Pl, proc_distances, worst_proc_distances); int active = 1; int sum_active; if (Al->local_num_rows == 0) active = 0; MPI_Reduce(&active, &sum_active, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); if (rank == 0) printf("Num Active Processes: %d\n", sum_active); C = Al->comm->communicate(rowptr, col_indices, values); delete C; tfinal = 0; for (int test = 0; test < n_tests; test++) { MPI_Barrier(MPI_COMM_WORLD); t0 = MPI_Wtime(); C = Al->comm->communicate(rowptr, col_indices, values); tfinal += (MPI_Wtime() - t0); delete C; } tfinal /= n_tests; MPI_Reduce(&(tfinal), &t0, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD); if (rank == 0) printf("Comm Time: %e\n", t0); /* if (rank == 0) printf("\nP.T*AP:\n"); AP->print_mult_T(Pl_csc, proc_distances, worst_proc_distances); active = 1; if (AP->local_num_rows == 0) active = 0; MPI_Reduce(&active, &sum_active, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); if (rank == 0) printf("Num Active Processes: %d\n", sum_active); C = AP->mult_T(Pl_csc); delete C; AP->spgemm_T_data.time = 0; AP->spgemm_T_data.comm_time = 0; for (int test = 0; test < n_tests; test++) { MPI_Barrier(MPI_COMM_WORLD); C = AP->mult_T(Pl_csc); delete C; } AP->spgemm_T_data.time /= n_tests; AP->spgemm_T_data.comm_time /= n_tests; MPI_Reduce(&(AP->spgemm_T_data.time), &t0, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD); if (rank == 0) printf("Time: %e\n", t0); MPI_Reduce(&(AP->spgemm_T_data.comm_time), &t0, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD); if (rank == 0) printf("Comm Time: %e\n", t0); */ //delete Pl_csc; //delete AP; MPI_Barrier(MPI_COMM_WORLD); ml->levels[i]->x.set_const_value(0.0); if (rank == 0) printf("A*x\n"); //Al->print_mult(proc_distances, worst_proc_distances); active = 1; if (Al->local_num_rows == 0) active = 0; MPI_Reduce(&active, &sum_active, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); if (rank == 0) printf("Num Active Processes: %d\n", sum_active); // Al->comm->communicate(ml->levels[i]->x); if (rank == 0) printf("Using Send + Irecv...\n"); MPI_Barrier(MPI_COMM_WORLD); t0 = MPI_Wtime(); for (int test = 0; test < n_spmv_tests; test++) { // b <- A*x // Al->comm->communicate(ml->levels[i]->x); for (int recv = 0; recv < Al->comm->recv_data->num_msgs; recv++) { int proc = Al->comm->recv_data->procs[recv]; int start = Al->comm->recv_data->indptr[recv]; int end = Al->comm->recv_data->indptr[recv+1]; MPI_Irecv(&Al->comm->recv_data->buffer[start], end - start, MPI_DOUBLE, proc, 93002, MPI_COMM_WORLD, &Al->comm->recv_data->requests[recv]); } for (int send = 0; send < Al->comm->send_data->num_msgs; send++) { int proc = Al->comm->send_data->procs[send]; int start = Al->comm->send_data->indptr[send]; int end = Al->comm->send_data->indptr[send+1]; for (int k = start; k < end; k++) { int index = Al->comm->send_data->indices[k]; Al->comm->send_data->buffer[k] = ml->levels[i]->x[index]; } MPI_Send(&Al->comm->send_data->buffer[start], end - start, MPI_DOUBLE, proc, 93002, MPI_COMM_WORLD); } if (Al->comm->recv_data->num_msgs) MPI_Waitall(Al->comm->recv_data->num_msgs, Al->comm->recv_data->requests.data(), MPI_STATUSES_IGNORE); } tfinal = (MPI_Wtime() - t0) / n_spmv_tests; MPI_Reduce(&(tfinal), &t0, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD); if (rank == 0) printf("Comm Time: %e\n", t0); if (rank == 0) printf("Using Isend/Irecv + MPI_Waitsomes\n"); MPI_Barrier(MPI_COMM_WORLD); t0 = MPI_Wtime(); for (int test = 0; test < n_spmv_tests; test++) { // b <- A*x // Al->comm->communicate(ml->levels[i]->x); for (int send = 0; send < Al->comm->send_data->num_msgs; send++) { int proc = Al->comm->send_data->procs[send]; int start = Al->comm->send_data->indptr[send]; int end = Al->comm->send_data->indptr[send+1]; for (int k = start; k < end; k++) { int index = Al->comm->send_data->indices[k]; Al->comm->send_data->buffer[k] = ml->levels[i]->x[index]; } MPI_Isend(&Al->comm->send_data->buffer[start], end - start, MPI_DOUBLE, proc, 93002, MPI_COMM_WORLD, &Al->comm->send_data->requests[send]); } for (int recv = 0; recv < Al->comm->recv_data->num_msgs; recv++) { int proc = Al->comm->recv_data->procs[recv]; int start = Al->comm->recv_data->indptr[recv]; int end = Al->comm->recv_data->indptr[recv+1]; MPI_Irecv(&Al->comm->recv_data->buffer[start], end - start, MPI_DOUBLE, proc, 93002, MPI_COMM_WORLD, &Al->comm->recv_data->requests[recv]); } fast_waitall(Al->comm->send_data->num_msgs, Al->comm->send_data->requests); fast_waitall(Al->comm->recv_data->num_msgs, Al->comm->recv_data->requests); } tfinal = (MPI_Wtime() - t0) / n_spmv_tests; MPI_Reduce(&(tfinal), &t0, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD); if (rank == 0) printf("Comm Time: %e\n", t0); } // Delete raptor hierarchy delete ml; delete A; MPI_Finalize(); return 0; }
34.097713
105
0.526065
lwhZJU
a38102ff297a7c358fff783e686f4a1f1575a4f6
7,684
cpp
C++
experiments/ros packages/io_lib/src/file_io.cpp
Slifer64/novel-DMP-constraints
cad6727a12642130dc64fd93827099e4cb763ec8
[ "MIT" ]
null
null
null
experiments/ros packages/io_lib/src/file_io.cpp
Slifer64/novel-DMP-constraints
cad6727a12642130dc64fd93827099e4cb763ec8
[ "MIT" ]
null
null
null
experiments/ros packages/io_lib/src/file_io.cpp
Slifer64/novel-DMP-constraints
cad6727a12642130dc64fd93827099e4cb763ec8
[ "MIT" ]
null
null
null
#include <io_lib/file_io.h> namespace as64_ { namespace io_ { const char* FileIO::error_msg[] = { "EMPTY_HEADER", "CORRUPTED_HEADER", "ENTRY DOES NOT EXIST:", "DUPLICATE_ENTRY", "TYPE_MISMATCH", "DIMENSIONS_MISMATCH", "INVALID_OP_FOR_OPENMODE", "UNKNOWN_TYPE" }; const char *FileIO::TypeName[] = { "scalar", "arma::Mat", "Eigen::Matrix", "std::vector" }; const char *FileIO::ScalarTypeName[] = { "bool", "int", "unsigned int", "long", "unsigned long", "long long", "unsigned long long", "float", "double", "N/A" }; FileIO::FileIO(const std::string &filename, int open_mode) { this->header_start = 0; in_flag = open_mode & FileIO::in; out_flag = open_mode & FileIO::out; bool trunc_flag = open_mode & FileIO::trunc; bool file_exist; { // check if file exists std::ifstream in(filename, std::ios::in); file_exist = in.good(); } if (!out_flag) { if (!in_flag) throw std::runtime_error("[FileIO::FileIO]: Open-mode \"in\" and/or \"out\" must be specified!"); if (in_flag && trunc_flag) throw std::runtime_error("[FileIO::FileIO]: Setting only \"in\" and \"trunc\" makes no sense :P ..."); if (in_flag && !file_exist) throw std::runtime_error("[FileIO::FileIO]: Open-mode \"in\" was specified but file \"" + filename + "\" doesn't exist or cannot be accessed..."); } if (trunc_flag && file_exist) { if (std::remove(filename.c_str()) != 0) // or fid.open(filename, ios::out | ios::trunc) ? // if (!std::ofstream(filename, std::ios::out | std::ios::trunc)) // have to also write empty header... throw std::runtime_error("[FileIO::FileIO]: Cannot discard the previous contents of the file \"" + filename + "\"..."); file_exist = false; } if (out_flag && !file_exist) // create the file and add empty header { fid.open(filename, std::ios::out); if (!fid) throw std::runtime_error("[FileIO::FileIO]: Failed to create file \"" + filename + "\"..."); this->writeHeader(); // write empty header fid.close(); } std::ios::openmode op_mode = std::ios::binary; if (in_flag) op_mode |= std::ios::in; if (out_flag) op_mode |= std::ios::out | std::ios::in; // add "in" to avoid overriding previous contents fid.open(filename, op_mode); if (!fid) throw std::ios_base::failure(std::string("[FileIO::FileIO]: Failed to open file \"") + filename + "\". The file " "may not exist or it cannot be accessed...\n"); this->readHeader(); } FileIO::~FileIO() { fid.close(); } void FileIO::printHeader(std::ostream &out) const { int name_len = 0; for (int k=0; k<name.size(); k++) { if (name[k].length() > name_len) name_len = name[k].length(); } name_len += 5; std::vector<std::string> type_name(type.size()); int type_len = 0; for (int k=0; k<type.size(); k++) { type_name[k] = getFullTypeName(type[k], sc_type[k]); if (type[k]==ARMA || type[k]==EIGEN) type_name[k] += getMatDim2str(k); int n = type_name[k].length(); if (n > type_len) type_len = n; } type_len += 5; std::string horiz_line; horiz_line.resize(name_len + type_len + 6); for (int i=0; i<horiz_line.length(); i++) horiz_line[i] = '-'; out << horiz_line << "\n"; out << std::setw(name_len) << std::left << "Name" << std::setw(type_len) << std::left << "Type" << "Pos\n"; out << horiz_line << "\n"; for (int k=0; k<name.size(); k++) { out << std::setw(name_len) << std::left << name[k] << std::setw(type_len) << std::left << type_name[k] << i_pos[k] << "\n"; } } int FileIO::findNameIndex(const std::string &name_) const { auto it = name_map.find(name_); if (it != name_map.end()) return it->second; else return -1; } void FileIO::checkType(int i, enum Type t2, enum ScalarType sc_t2) const { Type t = type[i]; ScalarType sc_t = sc_type[i]; if (t!=t2 | sc_t!=sc_t2) throw std::runtime_error("[FileIO::checkType]: " + getErrMsg(TYPE_MISMATCH) + ": " + getFullTypeName(t,sc_t) + " != " + getFullTypeName(t2,sc_t2)); } std::string FileIO::getMatDim2str(int k) const { fid.seekg(i_pos[k], fid.beg); long_t n_rows; long_t n_cols; FileIO::readScalar_(n_rows, this->fid); FileIO::readScalar_(n_cols, this->fid); std::ostringstream out; out << "(" << n_rows << "," << n_cols << ")"; return out.str(); } void FileIO::writeHeader() const { this->fid.seekp(this->header_start, this->fid.beg); size_t_ i1 = this->fid.tellp(); for (int k=0; k<name.size(); k++) { Type t = type[k]; ScalarType sc_t = sc_type[k]; size_t_ i = i_pos[k]; long_t name_len = name[k].length(); this->fid.write(reinterpret_cast<const char *>(&name_len), sizeof(name_len)); this->fid.write(reinterpret_cast<const char *>(name[k].c_str()), name_len); this->fid.write(reinterpret_cast<const char *>(&t), sizeof(t)); this->fid.write(reinterpret_cast<const char *>(&sc_t), sizeof(sc_t)); this->fid.write(reinterpret_cast<const char *>(&i), sizeof(i)); } size_t_ i2 = this->fid.tellp(); long_t header_len = i2-i1 + sizeof(header_len); this->fid.write(reinterpret_cast<const char *>(&header_len), sizeof(header_len)); this->fid.flush(); } void FileIO::readHeader() { this->name_map.clear(); this->name.clear(); this->type.clear(); this->sc_type.clear(); this->i_pos.clear(); fid.seekg (0, fid.beg); size_t_ i_start = fid.tellg(); fid.seekg (0, fid.end); size_t_ i_end = fid.tellg(); if (i_start == i_end) throw std::runtime_error("[FileIO::readHeader]: " + FileIO::getErrMsg(EMPTY_HEADER)); long_t header_len; this->fid.seekg(-sizeof(header_len), this->fid.end); i_end = this->fid.tellg(); this->fid.read(reinterpret_cast<char *>(&header_len), sizeof(header_len)); if (header_len < 0) throw std::runtime_error("[FileIO::readHeader]: " + FileIO::getErrMsg(CORRUPTED_HEADER)); this->fid.seekg(-header_len, this->fid.end); this->header_start = this->fid.tellg(); while (this->fid.tellg() != i_end) { Type t; ScalarType sc_t; size_t_ i; long_t len; char *name_i; this->fid.read(reinterpret_cast<char *>(&len), sizeof(len)); if (len < 0) throw std::runtime_error("[FileIO::readHeader]: " + FileIO::getErrMsg(CORRUPTED_HEADER)); name_i = new char[len+1]; this->fid.read(reinterpret_cast<char *>(name_i), len); name_i[len] = '\0'; this->fid.read(reinterpret_cast<char *>(&t), sizeof(t)); this->fid.read(reinterpret_cast<char *>(&sc_t), sizeof(sc_t)); this->fid.read(reinterpret_cast<char *>(&i), sizeof(i)); type.push_back(t); sc_type.push_back(sc_t); i_pos.push_back(i); name.push_back(name_i); name_map[name_i] = name.size()-1; delete name_i; } } std::string FileIO::getOpenModeName() const { std::string op_mode; if (in_flag) op_mode = "in"; else if (out_flag) op_mode = "out"; else op_mode = "in|out"; return op_mode; } // ====================================== // ======= STATIC Functions ========== // ====================================== std::string FileIO::getFullTypeName(enum Type type, enum ScalarType sc_type) { return getTypeName(type) + "<" + getScalarTypeName(sc_type) + ">"; } std::string FileIO::getTypeName(enum Type type) { return std::string(FileIO::TypeName[static_cast<int>(type)]); } std::string FileIO::getScalarTypeName(enum ScalarType type) { return std::string(FileIO::ScalarTypeName[static_cast<int>(type)]); } std::string FileIO::getErrMsg(enum Error err_id) { return std::string(FileIO::error_msg[err_id]); } } // namespace as64_ } // namespace io_
27.442857
178
0.617387
Slifer64
a386f74a4909c814bb5bbc3149d768300080750d
459
cpp
C++
pointer_stuff/playing_pointers.cpp
ramchandra94/datastructures_in_cpp
28274ff4f0d9736cfe690ef002b90b9ebbfaf2f7
[ "MIT" ]
null
null
null
pointer_stuff/playing_pointers.cpp
ramchandra94/datastructures_in_cpp
28274ff4f0d9736cfe690ef002b90b9ebbfaf2f7
[ "MIT" ]
null
null
null
pointer_stuff/playing_pointers.cpp
ramchandra94/datastructures_in_cpp
28274ff4f0d9736cfe690ef002b90b9ebbfaf2f7
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main(){ int a = 5; char ch = 'a'; char * p = &ch; cout << "directly printing character " << ch << endl; cout << "printing character through pointer " << *p << endl; cout << "printing the pointer itself " << p << endl; cout << "printing the 0th index of pointer " << p[0] << endl; ch++; cout << "printing the dereference of pointer after incrementing the character " << *p << endl; return 0; }
17
95
0.614379
ramchandra94
a388cef4bdc2719128dbdf12f46c083ccd4f4166
1,010
cc
C++
lib/generic/read_csv.test.cc
itko/scanbox
9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3
[ "BSD-3-Clause" ]
1
2020-01-09T09:30:23.000Z
2020-01-09T09:30:23.000Z
lib/generic/read_csv.test.cc
itko/scanbox
9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3
[ "BSD-3-Clause" ]
23
2018-03-19T20:54:52.000Z
2018-05-16T12:36:59.000Z
lib/generic/read_csv.test.cc
itko/scanbox
9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3
[ "BSD-3-Clause" ]
1
2018-03-14T20:00:43.000Z
2018-03-14T20:00:43.000Z
/// \file /// Maintainer: Felice Serena /// /// #include "read_csv.h" #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE( read_csv_all ) { // Note: make sure to run ./lib/tests to pass this test (from the build directory which in turn is located in the project root) const std::vector<std::vector<std::string>> content = MouseTrack::read_csv("../lib/generic/read_csv.test.example1.csv"); std::vector<std::vector<std::string>> expected; expected.push_back(std::vector<std::string>{"a" ,"", "b", "c"}); expected.push_back(std::vector<std::string>{"e" ,"h", "", "j"}); expected.push_back(std::vector<std::string>{"f" ,"g", "d", "k"}); BOOST_CHECK( expected.size() == content.size() ); for(size_t i = 0; i < content.size(); i += 1) { BOOST_CHECK(expected[i].size() == content[i].size()); for(size_t j = 0; j < content[i].size(); j += 1) { BOOST_CHECK_MESSAGE(expected[i][j] == content[i][j], "Found unexpected element."); } } }
33.666667
131
0.612871
itko
a388fe0b1c93d614172e7ac985a7a78e9ef1743d
509
cpp
C++
partition-array-into-three-parts-with-equal-sum/partition-array-into-three-parts-with-equal-sum.cpp
sharmishtha2401/leetcode
0c7389877afb64b3ff277f075ed9c87b24cb587b
[ "MIT" ]
1
2022-02-14T07:57:07.000Z
2022-02-14T07:57:07.000Z
partition-array-into-three-parts-with-equal-sum/partition-array-into-three-parts-with-equal-sum.cpp
sharmishtha2401/leetcode
0c7389877afb64b3ff277f075ed9c87b24cb587b
[ "MIT" ]
null
null
null
partition-array-into-three-parts-with-equal-sum/partition-array-into-three-parts-with-equal-sum.cpp
sharmishtha2401/leetcode
0c7389877afb64b3ff277f075ed9c87b24cb587b
[ "MIT" ]
null
null
null
class Solution { public: bool canThreePartsEqualSum(vector<int>& arr) { int sum=0; for(int i=0; i<arr.size(); i++) { sum+=arr[i]; } cout<<sum<<endl; if(sum%3!=0) return false; int s1=0; int count=0; for(int i=0; i<arr.size(); i++) { s1+=arr[i]; if(s1==sum/3) { count++; s1=0; } } return count>=3; } };
20.36
50
0.357564
sharmishtha2401
a389ac74a37930657c4914bad515945b2f480012
8,297
hpp
C++
src/ocl/ref_pooling.hpp
igor-byel/mkl-dnn
b03ea18e2c3a7576052c52e6c9aca7baa66d44af
[ "Apache-2.0" ]
null
null
null
src/ocl/ref_pooling.hpp
igor-byel/mkl-dnn
b03ea18e2c3a7576052c52e6c9aca7baa66d44af
[ "Apache-2.0" ]
null
null
null
src/ocl/ref_pooling.hpp
igor-byel/mkl-dnn
b03ea18e2c3a7576052c52e6c9aca7baa66d44af
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2019 Intel Corporation * * 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 OCL_REF_POOLING_HPP #define OCL_REF_POOLING_HPP #include <assert.h> #include "common/c_types_map.hpp" #include "compute/compute.hpp" #include "ocl/jit_ref_pooling_common_kernel.hpp" #include "ocl/ocl_pooling_pd.hpp" #include "ocl/ocl_stream.hpp" #include "ocl/ocl_utils.hpp" extern const char *ref_pooling_kernel; namespace dnnl { namespace impl { namespace ocl { struct ref_pooling_fwd_t : public primitive_impl_t { struct pd_t : public ocl_pooling_fwd_pd_t { pd_t(engine_t *engine, const pooling_desc_t *adesc, const primitive_attr_t *attr, const pooling_fwd_pd_t *hint_fwd_pd) : ocl_pooling_fwd_pd_t(engine, adesc, attr, hint_fwd_pd) , jpp_() , jit_off_() {} DECLARE_COMMON_PD_T("ocl:ref", ref_pooling_fwd_t); status_t init() { using namespace data_type; using namespace prop_kind; using namespace alg_kind; assert(engine()->kind() == engine_kind::gpu); auto *compute_engine = utils::downcast<compute::compute_engine_t *>(engine()); auto src_data_t = src_md()->data_type; auto dst_data_t = dst_md()->data_type; auto acc_data_t = desc()->accum_data_type; bool ok = true && set_default_params() == status::success && utils::one_of(desc()->prop_kind, forward_training, forward_inference) && utils::one_of(desc()->alg_kind, pooling_max, pooling_avg_include_padding, pooling_avg_exclude_padding) && (utils::everyone_is( f32, src_data_t, dst_data_t, acc_data_t) || utils::everyone_is( f16, src_data_t, dst_data_t, acc_data_t) || utils::everyone_is(bf16, src_data_t, dst_data_t) || utils::everyone_is(u8, src_data_t, dst_data_t) || utils::everyone_is(s8, src_data_t, dst_data_t)) && IMPLICATION(utils::one_of(src_data_t, f16), desc()->prop_kind == forward_inference) && IMPLICATION(src_data_t == u8 || src_data_t == s8, desc()->accum_data_type == s32) && attr()->has_default_values() && compute_engine->mayiuse( compute::device_ext_t::intel_subgroups) && IMPLICATION(src_data_t == f16, true && compute_engine->mayiuse( compute::device_ext_t::khr_fp16) && compute_engine->mayiuse( compute::device_ext_t:: intel_subgroups_short)); if (!ok) return status::unimplemented; bool is_training = desc_.prop_kind == forward_training; if (desc()->alg_kind == pooling_max && is_training) init_default_ws(s32); return jit_ref_pooling_fwd_kernel::init_conf( jpp_, desc_, src_md(), dst_md(), jit_off_); } jit_pool_conf_t jpp_; jit_offsets jit_off_; }; status_t init() override { auto *compute_engine = utils::downcast<compute::compute_engine_t *>(engine()); compute::kernel_ctx_t kernel_ctx; jit_ref_pooling_fwd_kernel::init_const_def( kernel_ctx, pd()->jpp_, pd()->jit_off_); compute_engine->create_kernel( &kernel_, "ref_pooling_fwd_kernel", kernel_ctx); if (!kernel_) return status::runtime_error; return status::success; } ref_pooling_fwd_t(const pd_t *apd) : primitive_impl_t(apd) { ker_ = new jit_ref_pooling_fwd_kernel(pd()->jpp_); } ~ref_pooling_fwd_t() { delete ker_; } virtual status_t execute(const exec_ctx_t &ctx) const override { return execute_forward(ctx); } private: status_t execute_forward(const exec_ctx_t &ctx) const; const pd_t *pd() const { return (const pd_t *)primitive_impl_t::pd(); } jit_ref_pooling_fwd_kernel *ker_; compute::kernel_t kernel_; }; struct ref_pooling_bwd_t : public primitive_impl_t { struct pd_t : public ocl_pooling_bwd_pd_t { pd_t(engine_t *engine, const pooling_desc_t *adesc, const primitive_attr_t *attr, const pooling_fwd_pd_t *hint_fwd_pd) : ocl_pooling_bwd_pd_t(engine, adesc, attr, hint_fwd_pd) , jpp_() , jit_off_() {} DECLARE_COMMON_PD_T("ocl:ref:any", ref_pooling_bwd_t); status_t init() { using namespace prop_kind; using namespace alg_kind; assert(engine()->kind() == engine_kind::gpu); auto *compute_engine = utils::downcast<compute::compute_engine_t *>(engine()); bool ok = true && set_default_params() == status::success && utils::one_of(desc()->prop_kind, backward_data) && utils::one_of(desc()->alg_kind, pooling_max, pooling_avg_include_padding, pooling_avg_exclude_padding) && (utils::everyone_is(data_type::f32, diff_dst_md()->data_type, diff_src_md()->data_type) || utils::everyone_is(data_type::bf16, diff_dst_md()->data_type, diff_src_md()->data_type)) && attr()->has_default_values() && compute_engine->mayiuse( compute::device_ext_t::intel_subgroups); if (!ok) return status::unimplemented; if (desc()->alg_kind == pooling_max) { init_default_ws(data_type::s32); if (!compare_ws(hint_fwd_pd_)) return status::unimplemented; } return jit_ref_pooling_fwd_kernel::init_conf( jpp_, desc_, diff_src_md(), diff_dst_md(), jit_off_); } jit_pool_conf_t jpp_; jit_offsets jit_off_; }; status_t init() override { auto *compute_engine = utils::downcast<compute::compute_engine_t *>(engine()); compute::kernel_ctx_t kernel_ctx; jit_ref_pooling_fwd_kernel::init_const_def( kernel_ctx, pd()->jpp_, pd()->jit_off_); compute_engine->create_kernel( &kernel_, "ref_pooling_bwd_kernel", kernel_ctx); if (!kernel_) return status::runtime_error; return status::success; } ref_pooling_bwd_t(const pd_t *apd) : primitive_impl_t(apd) { ker_ = new jit_ref_pooling_fwd_kernel(pd()->jpp_); } ~ref_pooling_bwd_t() { delete ker_; } virtual status_t execute(const exec_ctx_t &ctx) const override { return execute_backward(ctx); } private: status_t execute_backward(const exec_ctx_t &ctx) const; const pd_t *pd() const { return (const pd_t *)primitive_impl_t::pd(); } jit_ref_pooling_fwd_kernel *ker_; compute::kernel_t kernel_; }; } // namespace ocl } // namespace impl } // namespace dnnl #endif // vim: et ts=4 sw=4 cindent cino+=l0,\:4,N-s
39.136792
80
0.562372
igor-byel
a38a0c80b5df96edacb2bd70ff5f78585ad7c214
5,845
cpp
C++
Code/src/bcg_ver5/Projection.cpp
amihashemi/cs294project
7d0f67a40f72cd58a86fb7d7fcb3ed40f5ddc1ec
[ "MIT" ]
null
null
null
Code/src/bcg_ver5/Projection.cpp
amihashemi/cs294project
7d0f67a40f72cd58a86fb7d7fcb3ed40f5ddc1ec
[ "MIT" ]
null
null
null
Code/src/bcg_ver5/Projection.cpp
amihashemi/cs294project
7d0f67a40f72cd58a86fb7d7fcb3ed40f5ddc1ec
[ "MIT" ]
null
null
null
/* * Author: Johnny Lee * SVN Login: itzfx */ #include <cstdio> #include <iostream> #include <cassert> #include <cmath> #include <vector> #include "DBox.H" #include "RectMDArray.H" #include "FFT1D.H" #include "FFTMD.H" #include "FieldData.H" #include "DeltaVelocity.H" #include "PoissonSolver.H" #include "Projection.H" #include "WriteRectMDArray.H" using namespace std; Projection::Projection(std::shared_ptr<FFT1D> a_fft1dPtr) { // create the solver m_solver = PoissonSolver(a_fft1dPtr); // store N m_N = a_fft1dPtr->getN(); } void Projection::applyProjection(FieldData& a_velocity) { // this is const so it should only modify a_velocity /* * From the project handout, we have: * P = I - grad(DELTA^-1)div * * Discretized, we have: * P^h = I - (grad^h)((DELTA^h)^-1)div^h * (DELTA^h)(phi^h)_i = (1/(4h^2))(-4phi_i + phi_(i+e^0) + phi_(i-e^0) + phi_(i+e^1) + phi_(i-e^1)) * * After some conversation, it seems we will use: * DBox vBox(a_velocity.m_grid) * RectMDArray<double> R(vBox) <---- prepare for divergence calculation * divergence(R, a_velocity) <---- stores divergence in R * m_solver.solve(R) <---- gives (DELTA^-1 div) in R * RectMDArray<double> Rghost(vBox.grow(1)) <---- prepare for gradient calculation * R.copyTo(Rghost) <---- set the data in Rghost * DeltaVelocity dv; <---- prepare for gradient * dv.init(a_velocity) <---- prepare for gradient * gradient(dv, Rghost) <---- get the gradient * * Now we have grad(DELTA^-1)div * We need to subtract this from the identity matrix. * Another way to put this is that we need to go through each index in dv and * perform 1-dv_element if the index is on the standard diagonal. * * This is slightly tricky since the indexing is a bit strange. */ // create a box that's the same as the one in a_velocity for use DBox vBox(a_velocity.m_grid); // a_velocity.fillGhosts(); // Create an MDArray for div, and get the divergence RectMDArray<double> R(vBox); a_velocity.setBoundaries(); divergence(R, a_velocity); //R.setBoundaries(); // Get DELTA^-1 div using the PoissonSolver m_solver.solve(R); // now create a ghosted box for the gradient RectMDArray<double> Rghost(vBox.grow(1)); // and copy over DELTA^-1 div R.copyTo(Rghost); // need to fill ghosts on Rghost // a_velocity.fillGhosts(Rghost); // And finally, get the gradient DeltaVelocity dv; a_velocity.setBoundaries(); dv.init(a_velocity); gradient(dv, Rghost); //a_velocity[0] -= dv[0]; //a_velocity[1] -= dv[1]; a_velocity.setBoundaries(); a_velocity.increment(-1.0, dv); a_velocity.setBoundaries(); // MDWrite(dv[0]); } void Projection::gradient(DeltaVelocity& a_vector, const RectMDArray<double>& a_scalar) const { // http://en.wikipedia.org/wiki/Gradient /* * From the project handout, we have: * grad(phi) = (delta(p)/delta(x_0), ..., delta(p)/delta(x_(D-1))) * Discretized, we have: * grad^h(phi^h)_i = ((1/2h)(phi_(i+e^0) - phi_(i-e^0)), (phi_(i+e^1) - phi_(i-e^0))) */ // attempt: // the low corner of the box // int lowCorner[DIM]; Point lowCorner = a_vector.m_grid.getLowCorner(); // the high corner of the box // int highCorner[DIM]; Point highCorner = a_vector.m_grid.getHighCorner(); // this is mesh spacing double h = 1.0 / m_N; DBox bx = a_vector.m_grid; // TODO is this right??? // I'm going to assume DIM = 2 since we're working in 2-d space for(Point pt = bx.getLowCorner(); bx.notDone(pt); bx.increment(pt)) // for (int k = 0; k < bx.sizeOf();k++) { // int index[2]; // bx.tupleIndex(k,index); int i = pt[0]; int j = pt[1]; int plusE0[2] = {i+1, j}; // i+e^0 (right side) int minusE0[2] = {i-1, j}; // i-e^0 (left side) int plusE1[2] = {i, j+1}; // i+e^1 (top side) int minusE1[2] = {i, j-1}; // i-e^1 (bottom side) // figure out the x portion and save it a_vector.m_data(pt, 0) = (a_scalar[Point(plusE0)] - a_scalar[Point(minusE0)])/(2 * h); // and the y portion and save it a_vector.m_data(pt, 1) = (a_scalar[Point(plusE1)] - a_scalar[Point(minusE1)])/(2 * h); } } void Projection::divergence(RectMDArray<double>& a_scalar, const FieldData& a_vector) const { // http://en.wikipedia.org/wiki/Divergence /* * From the project handout, we have: * div(w) = sum(d=0 to D-1, delta(w_d)/delta(x_d)) * Discretized, we have: * div^h(w^h)_i = (1/2h)((u_0)_(i+e^0) - (u_0)_(i-e^0)) + (1/2h)((u_1)_(i+e^1) - (u_1)_(i-e^1)) * Note: * w^h = {u_0,u_1}, e^0 = {1,0} , e^1 = {0,1} */ // ghosts have already been filled // the low corner of the box DBox bx = a_vector.m_grid; // fix the corners // this is mesh spacing double h = 1.0 / a_vector.m_N; // TODO is this right??? // go through every element in a_vector which should be w^h // I'm going to assume DIM = 2 since we're working in 2-d space for(Point pt = bx.getLowCorner(); bx.notDone(pt); bx.increment(pt)) // for (int k = 0; k < bx.sizeOf();k++) { // int index[2]; // bx.tupleIndex(k,index); int i = pt[0]; int j = pt[1]; int plusE0[2] = {i+1, j}; // i+e^0 (right side) int minusE0[2] = {i-1, j}; // i-e^0 (left side) int plusE1[2] = {i, j+1}; // i+e^1 (top side) int minusE1[2] = {i, j-1}; // i-e^1 (bottom side) // figure out the x portion double xPortion = a_vector.m_data(Point(plusE0), 0) - a_vector.m_data(Point(minusE0), 0); // and the y portion double yPortion = a_vector.m_data(Point(plusE1), 1) - a_vector.m_data(Point(minusE1), 1); // save the result which is 1/2h(xPortion + yPortion) a_scalar[pt] = (xPortion + yPortion)/(2 * h); } }
32.472222
101
0.614029
amihashemi
a38f9560bc5a3656d3677ec60eb6feabd15de94d
1,347
cpp
C++
codeforces/1536B.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1536B.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1536B.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
// B. Prinzessin der Verurteilung #include <iostream> #include <string> #include <algorithm> #include <set> using namespace std; // With default comparator it will be a, aa, ..., b, ba, ... (size doesn't matter) // In the below comparator size does matter: it will be a, b, ..., aa, ... ba, .. struct sComp { bool operator() (const string& a, const string& b) const { if (a.size() < b.size()) { return true; } return a < b; } }; int main() { string alphabet = "abcdefghijklmnopqrstuvwxyz"; set<string, sComp> dp; // See in editorial why 3 levels only // Editorial - https://codeforces.com/blog/entry/91520 for (int i = 0; i < 26; ++i) { string s1(1, alphabet[i]); dp.insert(s1); for (int j = 0; j < 26; ++j) { string s2(1, alphabet[j]); dp.insert(s1 + s2); for (int k = 0; k < 26; ++k) { string s3(1, alphabet[k]); dp.insert(s1 + s2 + s3); } } } int t; cin >> t; while (t--) { int n; cin >> n; string s; getline(cin >> ws, s); for (auto &el: dp) { if (s.find(el) == string::npos) { cout << el << endl; break; } } } return 0; }
21.380952
82
0.467706
sgrade
a3906eca250dd6f5b7a9aaedb0a2799bd4d5e6df
1,735
cxx
C++
contrib/Netxx-0.3.2/tests/io/stream_client.cxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
1
2019-04-15T14:10:58.000Z
2019-04-15T14:10:58.000Z
contrib/Netxx-0.3.2/tests/io/stream_client.cxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
null
null
null
contrib/Netxx-0.3.2/tests/io/stream_client.cxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
2
2019-10-31T09:11:09.000Z
2021-09-17T01:00:49.000Z
#include <Netxx/Stream.h> #include <Netxx/Timeout.h> #include <iostream> #include <fstream> #include <sstream> #include <stdexcept> #include <exception> #include <cstring> #include <cstdlib> int main (int argc, char *argv[]) { if (argc != 4) { std::cerr << "Usage: " << argv[0] << " address file size\n"; return 1; } try { Netxx::Stream client(argv[1], 0, Netxx::Timeout(2)); std::ifstream file(argv[2]); if (!file) throw std::runtime_error("failed to open input file"); Netxx::size_type buffer_size = std::atoi(argv[3]); char *buffer = new char[buffer_size]; char *return_buffer = new char[buffer_size]; file.read(buffer, buffer_size); if (!file || file.gcount() != buffer_size) { std::ostringstream error; error << "read from file did not give the correct byte count, "; error << "gcount said: " << file.gcount(); error << " but I expected: " << buffer_size; throw std::runtime_error(error.str()); } if (client.write(buffer, buffer_size) != buffer_size) throw std::runtime_error("write to server did not send the correct byte count"); Netxx::signed_size_type bytes_read=0, buffer_aval=buffer_size; char *bufptr = return_buffer; while (buffer_aval) { if ( (bytes_read = client.read(bufptr, buffer_aval)) <= 0) throw std::runtime_error("read from server was less than or equal to 0"); bufptr += bytes_read; buffer_aval -= bytes_read; } if (std::memcmp(buffer, return_buffer, buffer_size) != 0) throw std::runtime_error("buffer mismatch"); } catch (std::exception &e) { std::cerr << e.what() << std::endl; return 1; } catch ( ... ) { std::cerr << "an unknown exception was caught" << std::endl; return 1; } return 0; }
25.895522
85
0.651297
dulton
a391152d8435e9b991a4cc554ced8695f18568b3
10,698
cpp
C++
src/MIT_alice/AUIComboWidget.cpp
midasitdev/aliceui
3693018021892bcccbc66f29b931d9736db6f9dc
[ "MIT" ]
10
2019-02-21T13:07:06.000Z
2019-09-21T02:56:37.000Z
src/MIT_alice/AUIComboWidget.cpp
midasitdev/aliceui
3693018021892bcccbc66f29b931d9736db6f9dc
[ "MIT" ]
5
2019-02-28T03:11:50.000Z
2019-03-08T00:16:17.000Z
src/MIT_alice/AUIComboWidget.cpp
midasitdev/aliceui
3693018021892bcccbc66f29b931d9736db6f9dc
[ "MIT" ]
5
2019-02-25T00:53:08.000Z
2019-07-05T01:50:34.000Z
#include "pch.h" #include "AUIComboWidget.h" #include "AUIComboPopupWidget.h" #include "AUIComboDefaultValue.h" #include "AUIWidgetManager.h" #include "AUIComboAdapter.h" #include "AUIStateDrawable.h" #include "AUILayerDrawable.h" #include "AUIShapeDrawable.h" #include "AUIRectShape.h" #include "AUITriangleShape.h" #include "AUIApplication.h" #include "AUIJsonDrawableParser.h" #include "AUIDrawableWidget.h" namespace { std::shared_ptr< AUIDrawable > GetComboDrawable() { AUIJsonDrawableParser parser; if (auto refDrawable = parser.LoadFromPathByResource(L"drawable/mp_btn.json")) return *refDrawable; auto pDefaultBG = std::make_shared< AUIShapeDrawable >( std::make_shared< AUIRectShape >() ); pDefaultBG->SetColor( SkColorSetRGB( 253, 253, 253 ) ); auto pHoverBG = std::make_shared< AUIShapeDrawable >( std::make_shared< AUIRectShape >() ); pHoverBG->SetColor( SkColorSetRGB( 245, 245, 245 ) ); auto pPressBG = std::make_shared< AUIShapeDrawable >( std::make_shared< AUIRectShape >() ); pPressBG->SetColor( SkColorSetRGB( 234, 238, 244 ) ); auto pDisableBG = std::make_shared< AUIShapeDrawable >( std::make_shared< AUIRectShape >() ); pDisableBG->SetColor( SkColorSetRGB( 221, 221, 221 ) ); auto pCheckBG = std::make_shared< AUIShapeDrawable >( std::make_shared< AUIRectShape >() ); pCheckBG->SetColor( SkColorSetRGB( 234, 238, 244 ) ); auto pOutline = std::make_shared< AUIShapeDrawable >( std::make_shared< AUIRectShape >() ); pOutline->SetColor( SkColorSetRGB( 177, 177, 177 ) ); pOutline->SetStrokeStyle( SkPaint::kStroke_Style ); auto pHoverOutline = std::make_shared< AUIShapeDrawable >( std::make_shared< AUIRectShape >() ); pHoverOutline->SetColor( SkColorSetRGB( 130, 186, 255 ) ); pHoverOutline->SetStrokeStyle( SkPaint::kStroke_Style ); pHoverOutline->SetStrokeWidth( 2.0f ); auto pPressOutline = std::make_shared< AUIShapeDrawable >( std::make_shared< AUIRectShape >() ); pPressOutline->SetColor( SkColorSetRGB( 130, 186, 255 ) ); pPressOutline->SetStrokeStyle( SkPaint::kStroke_Style ); pPressOutline->SetStrokeWidth( 2.0f ); auto pCheckOutline = std::make_shared< AUIShapeDrawable >( std::make_shared< AUIRectShape >() ); pCheckOutline->SetColor( SkColorSetRGB( 161, 174, 194 ) ); pCheckOutline->SetStrokeStyle( SkPaint::kStroke_Style ); pCheckOutline->SetStrokeWidth( 2.0f ); auto pDisableOutline = std::make_shared< AUIShapeDrawable >( std::make_shared< AUIRectShape >() ); pDisableOutline->SetColor( SkColorSetRGB( 204, 204, 204 ) ); pDisableOutline->SetStrokeStyle( SkPaint::kStroke_Style ); pDisableOutline->SetStrokeWidth( 2.0f ); auto pBackground = std::make_shared< AUILayerDrawable >(); pBackground->InsertLayer( pDefaultBG ); pBackground->InsertLayer( pOutline ); auto pHoverBackground = std::make_shared< AUILayerDrawable >(); pHoverBackground->InsertLayer( pHoverBG ); pHoverBackground->InsertLayer( pHoverOutline ); auto pPressBackground = std::make_shared< AUILayerDrawable >(); pPressBackground->InsertLayer( pPressBG ); pPressBackground->InsertLayer( pPressOutline ); auto pDisabledBackground = std::make_shared< AUILayerDrawable >(); pDisabledBackground->InsertLayer( pDisableBG ); pDisabledBackground->InsertLayer( pDisableOutline ); auto pCheckBackground = std::make_shared< AUILayerDrawable >(); pCheckBackground->InsertLayer( pCheckBG ); pCheckBackground->InsertLayer( pCheckOutline ); auto pStateDrawable = std::make_shared< AUIStateDrawable >(); pStateDrawable->SetTrueStateDrawable( AUIState::kDefault, pBackground ); pStateDrawable->SetTrueStateDrawable( AUIState::kMouseHovered, pHoverBackground ); pStateDrawable->SetTrueStateDrawable( AUIState::kPressed, pPressBackground ); pStateDrawable->SetTrueStateDrawable( AUIState::kDisabled, pDisabledBackground ); pStateDrawable->SetTrueStateDrawable( AUIState::kChecked, pCheckBackground ); return pStateDrawable; } } size_t AUIComboWidget::InvalidPos = (std::numeric_limits< size_t >::max)(); AUIComboWidget::AUIComboWidget() : m_pPopup( std::make_shared< AUIComboPopupWidget >() ) , m_curPos( InvalidPos ) , m_PopupMaxHeight( -1.0f ) , m_bUsePopuptHitRect(false) , m_bArrowDirection(true) { SetSizePolicy(AUISizePolicy::kFixed, AUISizePolicy::kFixed); SetDefaultSize( COMBO::kDefaultWidth, COMBO::kDefaultHeight ); SetPopupWidget( m_pPopup ); Connect( ComboPopupSignal, this, &AUIComboWidget::OnClickPopup ); Connect( m_pPopup->PopupFocusLostSignal, this, &AUIComboWidget::OnPopupFocusLost ); Connect(AUIApplication::Instance().MouseWheelSignal, [&](AUIWidgetManager* _pWM, int, int, float) { if (auto _pTargetWM = this->GetWidgetManager()) { if (_pTargetWM == _pWM) this->Dismiss(); } }); SetBackgroundDrawable( ::GetComboDrawable() ); } void AUIComboWidget::OnDraw( SkCanvas* const canvas ) { SuperWidget::OnDraw( canvas ); const auto rect = GetDrawBound(); const auto triOffsetY = rect.height() * 0.5f - COMBO::ARROW::kComboArrowSize * 0.5f; // TOOD : Designed shape static auto pTriShape = std::make_shared< AUITriangleShape >(); static auto pTriangle = std::make_shared< AUIShapeDrawable >( pTriShape ); if (GetArrowDirection()) pTriShape->SetAngle( 180.0f ); pTriangle->SetUseAA( true ); pTriangle->SetDrawBound( SkRect::MakeWH(COMBO::ARROW::kComboArrowSize, COMBO::ARROW::kComboArrowSize) ); pTriangle->SetColor( COMBO::ARROW::kComboArrowColor ); canvas->translate( GetWidth() - COMBO::ARROW::kComboArrowSize - COMBO::ARROW::kComboArrowOffset, triOffsetY ); pTriangle->Draw( canvas ); } void AUIComboWidget::OnAfterMeasureSize(SkScalar width, SkScalar height) { const auto trioffsetleft = 5.0f; SetPopupHitRect(SkRect::MakeLTRB(width - COMBO::ARROW::kComboArrowSize - COMBO::ARROW::kComboArrowOffset - trioffsetleft, 0.0f, width, height)); } void AUIComboWidget::OnMouseEnter() { SuperWidget::OnMouseEnter(); Invalidate(); } void AUIComboWidget::OnMouseHover() { SuperWidget::OnMouseHover(); Invalidate(); } void AUIComboWidget::OnMouseLeave() { SuperWidget::OnMouseLeave(); Invalidate(); } bool AUIComboWidget::OnMouseLBtnUp( MAUIMouseEvent::EventFlag flag ) { SuperWidget::OnMouseLBtnUp( flag ); if ( false == IsDisabled() ) { if (false == IsUsePopupHitRect()) ComboPopupSignal.Send(this); else { // Check Hit Test if (m_PopupHitRect.isEmpty() || AUISkiaUtil::IsInRect(m_PopupHitRect, GetMouseLocPos())) ComboPopupSignal.Send(this); else ComboClickSignal.Send(this); } } return true; } void AUIComboWidget::OnDestroy() { SuperWidget::OnDestroy(); if (IsInvoked()) Dismiss(); } void AUIComboWidget::SetAdapter( const std::shared_ptr< AUIComboAdapter >& pAdapter ) { if ( m_pPopup->GetAdapter() == pAdapter ) return; m_spoolItemClick.DisconnectAll(); m_spoolDataChange.DisconnectAll(); AUIAssert( pAdapter ); m_spoolItemClick.Connect(pAdapter->ClickItemSignal, this, &AUIComboWidget::OnItemClicked ); m_spoolDataChange.Connect(pAdapter->DataChangedSignal, this, &AUIComboWidget::OnAdapterDataChanged ); // Reset m_curPos = InvalidPos; m_pPopup->SetAdapter( pAdapter ); RefreshLabel(); } std::shared_ptr< AUIComboAdapter > AUIComboWidget::GetAdapter() const { return m_pPopup->GetAdapter(); } void AUIComboWidget::OnAdapterDataChanged(AUIComboAdapter* pAdapter ) { //if ( InvalidPos == GetCurPos() ) RefreshLabel(); } void AUIComboWidget::OnClickPopup( AUIComboWidget* const ) { if ( m_PopupMaxHeight > 0 ) { m_pPopup->SetMaximumHeight( m_PopupMaxHeight ); m_pPopup->SetDefaultHeight( m_PopupMaxHeight ); } m_pPopup->SetDefaultWidth( GetWidth() ); AUIAssert( IsCreated() ); if ( IsInvoked() ) { Dismiss(); } else { SetPopupPosition( glm::vec3( 0.0f, GetHeight(), 0.0f ) ); Invoke(GetWidgetManager(), shared_from_this(), GetPopupOpt()); } } void AUIComboWidget::OnItemClicked(AUIComboAdapter*, size_t pos ) { SetCurPos( pos ); Dismiss(); } void AUIComboWidget::OnPopupFocusLost() { SetCurPos( GetCurPos() ); Dismiss(); } void AUIComboWidget::RefreshLabel() { auto pAdapter = GetAdapter(); if (pAdapter && pAdapter->GetCount() != 0 && InvalidPos != GetCurPos()) { auto pNewLabel = pAdapter->GetWidget( GetCurPos(), GetLabel(), shared_from_this() ); SetLabel( pNewLabel ); } else { SetLabel(nullptr); } } void AUIComboWidget::SetLabel( const std::shared_ptr< AUIWidget >& pLabel ) { if (GetLabel() && GetLabel() == pLabel ) { GetLabel()->SetSizePolicy(AUISizePolicy::kParent, AUISizePolicy::kParent); GetLabel()->SetPosition( 0.0f, 0.0f ); GetLabel()->SetDefaultSize( GetDefaultSize() ); UpdateSize(); UpdateChildPosition(); return; } if (GetLabel()) { DelChild(GetLabel()); } m_pLabel = pLabel; if (GetLabel()) { GetLabel()->Freeze(); GetLabel()->SetSizePolicy(AUISizePolicy::kParent, AUISizePolicy::kParent); GetLabel()->SetPosition( 0.0f, 0.0f ); GetLabel()->SetDefaultSize( GetDefaultSize() ); AddChild(GetLabel()); } else { auto _tmplabel = std::make_shared<AUIDrawableWidget>(); m_pLabel = _tmplabel; _tmplabel->Freeze(); _tmplabel->SetSizePolicy(AUISizePolicy::kParent, AUISizePolicy::kParent); _tmplabel->SetPosition(0.0f, 0.0f); _tmplabel->SetDefaultSize(GetDefaultSize()); AddChild(_tmplabel); } UpdateSize(); UpdateChildPosition(); } void AUIComboWidget::SetCurPos( size_t pos ) { m_curPos = pos; RefreshLabel(); } void AUIComboWidget::OnSetDefaultSize( const AUIScalar2& size ) { AUIFrameLayoutWidget::OnSetDefaultSize( size ); if (GetLabel()) GetLabel()->SetDefaultSize( size ); m_pPopup->SetDefaultWidth( size.fX ); } void AUIComboWidget::SetUseMarquee( bool val ) { m_pPopup->SetUseMarquee( val ); } bool AUIComboWidget::IsUseMarquee() const { return m_pPopup->IsUseMarquee(); }
31.934328
114
0.670219
midasitdev
a391790aefbe5c1ee66ec31ca8f8e152c4a1c8ee
51,179
cc
C++
Digit_Example/opt_two_step/gen/opt/J_d1y_time_RightStance.cc
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
Digit_Example/opt_two_step/gen/opt/J_d1y_time_RightStance.cc
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
Digit_Example/opt_two_step/gen/opt/J_d1y_time_RightStance.cc
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
/* * Automatically Generated from Mathematica. * Fri 5 Nov 2021 16:18:14 GMT-04:00 */ #ifdef MATLAB_MEX_FILE #include <stdexcept> #include <cmath> #include<math.h> /** * Copied from Wolfram Mathematica C Definitions file mdefs.hpp * Changed marcos to inline functions (Eric Cousineau) */ inline double Power(double x, double y) { return pow(x, y); } inline double Sqrt(double x) { return sqrt(x); } inline double Abs(double x) { return fabs(x); } inline double Exp(double x) { return exp(x); } inline double Log(double x) { return log(x); } inline double Sin(double x) { return sin(x); } inline double Cos(double x) { return cos(x); } inline double Tan(double x) { return tan(x); } inline double ArcSin(double x) { return asin(x); } inline double ArcCos(double x) { return acos(x); } inline double ArcTan(double x) { return atan(x); } /* update ArcTan function to use atan2 instead. */ inline double ArcTan(double x, double y) { return atan2(y,x); } inline double Sinh(double x) { return sinh(x); } inline double Cosh(double x) { return cosh(x); } inline double Tanh(double x) { return tanh(x); } const double E = 2.71828182845904523536029; const double Pi = 3.14159265358979323846264; const double Degree = 0.01745329251994329576924; inline double Sec(double x) { return 1/cos(x); } inline double Csc(double x) { return 1/sin(x); } #endif /* * Sub functions */ static void output1(double *p_output1,const double *var1,const double *var2,const double *var3,const double *var4,const double *var5,const double *var6,const double *var7) { double t318; double t239; double t247; double t268; double t273; double t312; double t325; double t326; double t336; double t337; double t346; double t347; double t349; double t363; double t367; double t369; double t370; double t375; double t391; double t397; double t402; double t403; double t454; double t477; double t485; double t1064; double t1259; double t457; double t460; double t463; double t464; double t467; double t468; double t469; double t470; double t471; double t472; double t480; double t481; double t482; double t484; t318 = -1.*var5[1]; t239 = -1. + var6[0]; t247 = -1. + var7[0]; t268 = 1/t247; t273 = -1.*t239*t268; t312 = 1. + t273; t325 = var5[0] + t318; t326 = Power(t325,-5); t336 = -1.*var1[0]; t337 = t336 + var1[1]; t346 = t239*t268*t337; t347 = t318 + var1[0] + t346; t349 = Power(t347,3); t363 = Power(t325,-4); t367 = Power(t347,2); t369 = 1/t325; t370 = -1.*t369*t347; t375 = 1. + t370; t391 = Power(t325,-3); t397 = Power(t375,2); t402 = Power(t325,-2); t403 = Power(t375,3); t454 = Power(t375,4); t477 = Power(t347,4); t485 = Power(t325,-6); t1064 = -1.*t402*t347; t1259 = t369 + t1064; t457 = 5.*t369*t454; t460 = 20.*t402*t347*t403; t463 = -5.*t369*t454; t464 = t460 + t463; t467 = 30.*t391*t367*t397; t468 = -20.*t402*t347*t403; t469 = t467 + t468; t470 = 20.*t363*t349*t375; t471 = -30.*t391*t367*t397; t472 = t470 + t471; t480 = 5.*t326*t477; t481 = -20.*t363*t349*t375; t482 = t480 + t481; t484 = -5.*t326*t477; p_output1[0]=-20.*t312*t402*t403*var4[0] - 60.*t312*t347*t391*t397*var4[20] + 40.*t312*t402*t403*var4[20] - 60.*t312*t363*t367*t375*var4[40] + 120.*t312*t347*t391*t397*var4[40] - 20.*t312*t402*t403*var4[40] - 20.*t312*t326*t349*var4[60] + 120.*t312*t363*t367*t375*var4[60] - 60.*t312*t347*t391*t397*var4[60] + 40.*t312*t326*t349*var4[80] - 60.*t312*t363*t367*t375*var4[80] - 20.*t312*t326*t349*var4[100]; p_output1[1]=-20.*t239*t268*t402*t403*var4[0] - 60.*t239*t268*t347*t391*t397*var4[20] + 40.*t239*t268*t402*t403*var4[20] - 60.*t239*t268*t363*t367*t375*var4[40] + 120.*t239*t268*t347*t391*t397*var4[40] - 20.*t239*t268*t402*t403*var4[40] - 20.*t239*t268*t326*t349*var4[60] + 120.*t239*t268*t363*t367*t375*var4[60] - 60.*t239*t268*t347*t391*t397*var4[60] + 40.*t239*t268*t326*t349*var4[80] - 60.*t239*t268*t363*t367*t375*var4[80] - 20.*t239*t268*t326*t349*var4[100]; p_output1[2]=1.; p_output1[3]=t457; p_output1[4]=t464; p_output1[5]=t469; p_output1[6]=t472; p_output1[7]=t482; p_output1[8]=t484; p_output1[9]=20.*t347*t391*t403*var4[0] - 5.*t402*t454*var4[0] + 60.*t363*t367*t397*var4[20] - 60.*t347*t391*t403*var4[20] + 5.*t402*t454*var4[20] + 60.*t326*t349*t375*var4[40] - 150.*t363*t367*t397*var4[40] + 40.*t347*t391*t403*var4[40] - 140.*t326*t349*t375*var4[60] + 90.*t363*t367*t397*var4[60] + 20.*t477*t485*var4[60] + 80.*t326*t349*t375*var4[80] - 45.*t477*t485*var4[80] + 25.*t477*t485*var4[100]; p_output1[10]=20.*t1259*t369*t403*var4[0] + 5.*t402*t454*var4[0] + 60.*t1259*t347*t397*t402*var4[20] - 20.*t1259*t369*t403*var4[20] + 40.*t347*t391*t403*var4[20] - 20.*t402*t403*var4[20] - 5.*t402*t454*var4[20] + 60.*t1259*t367*t375*t391*var4[40] + 90.*t363*t367*t397*var4[40] - 60.*t347*t391*t397*var4[40] - 60.*t1259*t347*t397*t402*var4[40] - 40.*t347*t391*t403*var4[40] + 20.*t402*t403*var4[40] + 20.*t1259*t349*t363*var4[60] + 80.*t326*t349*t375*var4[60] - 60.*t363*t367*t375*var4[60] - 60.*t1259*t367*t375*t391*var4[60] - 90.*t363*t367*t397*var4[60] + 60.*t347*t391*t397*var4[60] - 20.*t326*t349*var4[80] - 20.*t1259*t349*t363*var4[80] - 80.*t326*t349*t375*var4[80] + 60.*t363*t367*t375*var4[80] + 25.*t477*t485*var4[80] + 20.*t326*t349*var4[100] - 25.*t477*t485*var4[100]; p_output1[11]=-20.*t312*t402*t403*var4[1] - 60.*t312*t347*t391*t397*var4[21] + 40.*t312*t402*t403*var4[21] - 60.*t312*t363*t367*t375*var4[41] + 120.*t312*t347*t391*t397*var4[41] - 20.*t312*t402*t403*var4[41] - 20.*t312*t326*t349*var4[61] + 120.*t312*t363*t367*t375*var4[61] - 60.*t312*t347*t391*t397*var4[61] + 40.*t312*t326*t349*var4[81] - 60.*t312*t363*t367*t375*var4[81] - 20.*t312*t326*t349*var4[101]; p_output1[12]=-20.*t239*t268*t402*t403*var4[1] - 60.*t239*t268*t347*t391*t397*var4[21] + 40.*t239*t268*t402*t403*var4[21] - 60.*t239*t268*t363*t367*t375*var4[41] + 120.*t239*t268*t347*t391*t397*var4[41] - 20.*t239*t268*t402*t403*var4[41] - 20.*t239*t268*t326*t349*var4[61] + 120.*t239*t268*t363*t367*t375*var4[61] - 60.*t239*t268*t347*t391*t397*var4[61] + 40.*t239*t268*t326*t349*var4[81] - 60.*t239*t268*t363*t367*t375*var4[81] - 20.*t239*t268*t326*t349*var4[101]; p_output1[13]=1.; p_output1[14]=t457; p_output1[15]=t464; p_output1[16]=t469; p_output1[17]=t472; p_output1[18]=t482; p_output1[19]=t484; p_output1[20]=20.*t347*t391*t403*var4[1] - 5.*t402*t454*var4[1] + 60.*t363*t367*t397*var4[21] - 60.*t347*t391*t403*var4[21] + 5.*t402*t454*var4[21] + 60.*t326*t349*t375*var4[41] - 150.*t363*t367*t397*var4[41] + 40.*t347*t391*t403*var4[41] - 140.*t326*t349*t375*var4[61] + 90.*t363*t367*t397*var4[61] + 20.*t477*t485*var4[61] + 80.*t326*t349*t375*var4[81] - 45.*t477*t485*var4[81] + 25.*t477*t485*var4[101]; p_output1[21]=20.*t1259*t369*t403*var4[1] + 5.*t402*t454*var4[1] + 60.*t1259*t347*t397*t402*var4[21] - 20.*t1259*t369*t403*var4[21] + 40.*t347*t391*t403*var4[21] - 20.*t402*t403*var4[21] - 5.*t402*t454*var4[21] + 60.*t1259*t367*t375*t391*var4[41] + 90.*t363*t367*t397*var4[41] - 60.*t347*t391*t397*var4[41] - 60.*t1259*t347*t397*t402*var4[41] - 40.*t347*t391*t403*var4[41] + 20.*t402*t403*var4[41] + 20.*t1259*t349*t363*var4[61] + 80.*t326*t349*t375*var4[61] - 60.*t363*t367*t375*var4[61] - 60.*t1259*t367*t375*t391*var4[61] - 90.*t363*t367*t397*var4[61] + 60.*t347*t391*t397*var4[61] - 20.*t326*t349*var4[81] - 20.*t1259*t349*t363*var4[81] - 80.*t326*t349*t375*var4[81] + 60.*t363*t367*t375*var4[81] + 25.*t477*t485*var4[81] + 20.*t326*t349*var4[101] - 25.*t477*t485*var4[101]; p_output1[22]=-20.*t312*t402*t403*var4[2] - 60.*t312*t347*t391*t397*var4[22] + 40.*t312*t402*t403*var4[22] - 60.*t312*t363*t367*t375*var4[42] + 120.*t312*t347*t391*t397*var4[42] - 20.*t312*t402*t403*var4[42] - 20.*t312*t326*t349*var4[62] + 120.*t312*t363*t367*t375*var4[62] - 60.*t312*t347*t391*t397*var4[62] + 40.*t312*t326*t349*var4[82] - 60.*t312*t363*t367*t375*var4[82] - 20.*t312*t326*t349*var4[102]; p_output1[23]=-20.*t239*t268*t402*t403*var4[2] - 60.*t239*t268*t347*t391*t397*var4[22] + 40.*t239*t268*t402*t403*var4[22] - 60.*t239*t268*t363*t367*t375*var4[42] + 120.*t239*t268*t347*t391*t397*var4[42] - 20.*t239*t268*t402*t403*var4[42] - 20.*t239*t268*t326*t349*var4[62] + 120.*t239*t268*t363*t367*t375*var4[62] - 60.*t239*t268*t347*t391*t397*var4[62] + 40.*t239*t268*t326*t349*var4[82] - 60.*t239*t268*t363*t367*t375*var4[82] - 20.*t239*t268*t326*t349*var4[102]; p_output1[24]=1.; p_output1[25]=t457; p_output1[26]=t464; p_output1[27]=t469; p_output1[28]=t472; p_output1[29]=t482; p_output1[30]=t484; p_output1[31]=20.*t347*t391*t403*var4[2] - 5.*t402*t454*var4[2] + 60.*t363*t367*t397*var4[22] - 60.*t347*t391*t403*var4[22] + 5.*t402*t454*var4[22] + 60.*t326*t349*t375*var4[42] - 150.*t363*t367*t397*var4[42] + 40.*t347*t391*t403*var4[42] - 140.*t326*t349*t375*var4[62] + 90.*t363*t367*t397*var4[62] + 20.*t477*t485*var4[62] + 80.*t326*t349*t375*var4[82] - 45.*t477*t485*var4[82] + 25.*t477*t485*var4[102]; p_output1[32]=20.*t1259*t369*t403*var4[2] + 5.*t402*t454*var4[2] + 60.*t1259*t347*t397*t402*var4[22] - 20.*t1259*t369*t403*var4[22] + 40.*t347*t391*t403*var4[22] - 20.*t402*t403*var4[22] - 5.*t402*t454*var4[22] + 60.*t1259*t367*t375*t391*var4[42] + 90.*t363*t367*t397*var4[42] - 60.*t347*t391*t397*var4[42] - 60.*t1259*t347*t397*t402*var4[42] - 40.*t347*t391*t403*var4[42] + 20.*t402*t403*var4[42] + 20.*t1259*t349*t363*var4[62] + 80.*t326*t349*t375*var4[62] - 60.*t363*t367*t375*var4[62] - 60.*t1259*t367*t375*t391*var4[62] - 90.*t363*t367*t397*var4[62] + 60.*t347*t391*t397*var4[62] - 20.*t326*t349*var4[82] - 20.*t1259*t349*t363*var4[82] - 80.*t326*t349*t375*var4[82] + 60.*t363*t367*t375*var4[82] + 25.*t477*t485*var4[82] + 20.*t326*t349*var4[102] - 25.*t477*t485*var4[102]; p_output1[33]=-20.*t312*t402*t403*var4[3] - 60.*t312*t347*t391*t397*var4[23] + 40.*t312*t402*t403*var4[23] - 60.*t312*t363*t367*t375*var4[43] + 120.*t312*t347*t391*t397*var4[43] - 20.*t312*t402*t403*var4[43] - 20.*t312*t326*t349*var4[63] + 120.*t312*t363*t367*t375*var4[63] - 60.*t312*t347*t391*t397*var4[63] + 40.*t312*t326*t349*var4[83] - 60.*t312*t363*t367*t375*var4[83] - 20.*t312*t326*t349*var4[103]; p_output1[34]=-20.*t239*t268*t402*t403*var4[3] - 60.*t239*t268*t347*t391*t397*var4[23] + 40.*t239*t268*t402*t403*var4[23] - 60.*t239*t268*t363*t367*t375*var4[43] + 120.*t239*t268*t347*t391*t397*var4[43] - 20.*t239*t268*t402*t403*var4[43] - 20.*t239*t268*t326*t349*var4[63] + 120.*t239*t268*t363*t367*t375*var4[63] - 60.*t239*t268*t347*t391*t397*var4[63] + 40.*t239*t268*t326*t349*var4[83] - 60.*t239*t268*t363*t367*t375*var4[83] - 20.*t239*t268*t326*t349*var4[103]; p_output1[35]=1.; p_output1[36]=t457; p_output1[37]=t464; p_output1[38]=t469; p_output1[39]=t472; p_output1[40]=t482; p_output1[41]=t484; p_output1[42]=20.*t347*t391*t403*var4[3] - 5.*t402*t454*var4[3] + 60.*t363*t367*t397*var4[23] - 60.*t347*t391*t403*var4[23] + 5.*t402*t454*var4[23] + 60.*t326*t349*t375*var4[43] - 150.*t363*t367*t397*var4[43] + 40.*t347*t391*t403*var4[43] - 140.*t326*t349*t375*var4[63] + 90.*t363*t367*t397*var4[63] + 20.*t477*t485*var4[63] + 80.*t326*t349*t375*var4[83] - 45.*t477*t485*var4[83] + 25.*t477*t485*var4[103]; p_output1[43]=20.*t1259*t369*t403*var4[3] + 5.*t402*t454*var4[3] + 60.*t1259*t347*t397*t402*var4[23] - 20.*t1259*t369*t403*var4[23] + 40.*t347*t391*t403*var4[23] - 20.*t402*t403*var4[23] - 5.*t402*t454*var4[23] + 60.*t1259*t367*t375*t391*var4[43] + 90.*t363*t367*t397*var4[43] - 60.*t347*t391*t397*var4[43] - 60.*t1259*t347*t397*t402*var4[43] - 40.*t347*t391*t403*var4[43] + 20.*t402*t403*var4[43] + 20.*t1259*t349*t363*var4[63] + 80.*t326*t349*t375*var4[63] - 60.*t363*t367*t375*var4[63] - 60.*t1259*t367*t375*t391*var4[63] - 90.*t363*t367*t397*var4[63] + 60.*t347*t391*t397*var4[63] - 20.*t326*t349*var4[83] - 20.*t1259*t349*t363*var4[83] - 80.*t326*t349*t375*var4[83] + 60.*t363*t367*t375*var4[83] + 25.*t477*t485*var4[83] + 20.*t326*t349*var4[103] - 25.*t477*t485*var4[103]; p_output1[44]=-20.*t312*t402*t403*var4[4] - 60.*t312*t347*t391*t397*var4[24] + 40.*t312*t402*t403*var4[24] - 60.*t312*t363*t367*t375*var4[44] + 120.*t312*t347*t391*t397*var4[44] - 20.*t312*t402*t403*var4[44] - 20.*t312*t326*t349*var4[64] + 120.*t312*t363*t367*t375*var4[64] - 60.*t312*t347*t391*t397*var4[64] + 40.*t312*t326*t349*var4[84] - 60.*t312*t363*t367*t375*var4[84] - 20.*t312*t326*t349*var4[104]; p_output1[45]=-20.*t239*t268*t402*t403*var4[4] - 60.*t239*t268*t347*t391*t397*var4[24] + 40.*t239*t268*t402*t403*var4[24] - 60.*t239*t268*t363*t367*t375*var4[44] + 120.*t239*t268*t347*t391*t397*var4[44] - 20.*t239*t268*t402*t403*var4[44] - 20.*t239*t268*t326*t349*var4[64] + 120.*t239*t268*t363*t367*t375*var4[64] - 60.*t239*t268*t347*t391*t397*var4[64] + 40.*t239*t268*t326*t349*var4[84] - 60.*t239*t268*t363*t367*t375*var4[84] - 20.*t239*t268*t326*t349*var4[104]; p_output1[46]=1.; p_output1[47]=t457; p_output1[48]=t464; p_output1[49]=t469; p_output1[50]=t472; p_output1[51]=t482; p_output1[52]=t484; p_output1[53]=20.*t347*t391*t403*var4[4] - 5.*t402*t454*var4[4] + 60.*t363*t367*t397*var4[24] - 60.*t347*t391*t403*var4[24] + 5.*t402*t454*var4[24] + 60.*t326*t349*t375*var4[44] - 150.*t363*t367*t397*var4[44] + 40.*t347*t391*t403*var4[44] - 140.*t326*t349*t375*var4[64] + 90.*t363*t367*t397*var4[64] + 20.*t477*t485*var4[64] + 80.*t326*t349*t375*var4[84] - 45.*t477*t485*var4[84] + 25.*t477*t485*var4[104]; p_output1[54]=20.*t1259*t369*t403*var4[4] + 5.*t402*t454*var4[4] + 60.*t1259*t347*t397*t402*var4[24] - 20.*t1259*t369*t403*var4[24] + 40.*t347*t391*t403*var4[24] - 20.*t402*t403*var4[24] - 5.*t402*t454*var4[24] + 60.*t1259*t367*t375*t391*var4[44] + 90.*t363*t367*t397*var4[44] - 60.*t347*t391*t397*var4[44] - 60.*t1259*t347*t397*t402*var4[44] - 40.*t347*t391*t403*var4[44] + 20.*t402*t403*var4[44] + 20.*t1259*t349*t363*var4[64] + 80.*t326*t349*t375*var4[64] - 60.*t363*t367*t375*var4[64] - 60.*t1259*t367*t375*t391*var4[64] - 90.*t363*t367*t397*var4[64] + 60.*t347*t391*t397*var4[64] - 20.*t326*t349*var4[84] - 20.*t1259*t349*t363*var4[84] - 80.*t326*t349*t375*var4[84] + 60.*t363*t367*t375*var4[84] + 25.*t477*t485*var4[84] + 20.*t326*t349*var4[104] - 25.*t477*t485*var4[104]; p_output1[55]=-20.*t312*t402*t403*var4[5] - 60.*t312*t347*t391*t397*var4[25] + 40.*t312*t402*t403*var4[25] - 60.*t312*t363*t367*t375*var4[45] + 120.*t312*t347*t391*t397*var4[45] - 20.*t312*t402*t403*var4[45] - 20.*t312*t326*t349*var4[65] + 120.*t312*t363*t367*t375*var4[65] - 60.*t312*t347*t391*t397*var4[65] + 40.*t312*t326*t349*var4[85] - 60.*t312*t363*t367*t375*var4[85] - 20.*t312*t326*t349*var4[105]; p_output1[56]=-20.*t239*t268*t402*t403*var4[5] - 60.*t239*t268*t347*t391*t397*var4[25] + 40.*t239*t268*t402*t403*var4[25] - 60.*t239*t268*t363*t367*t375*var4[45] + 120.*t239*t268*t347*t391*t397*var4[45] - 20.*t239*t268*t402*t403*var4[45] - 20.*t239*t268*t326*t349*var4[65] + 120.*t239*t268*t363*t367*t375*var4[65] - 60.*t239*t268*t347*t391*t397*var4[65] + 40.*t239*t268*t326*t349*var4[85] - 60.*t239*t268*t363*t367*t375*var4[85] - 20.*t239*t268*t326*t349*var4[105]; p_output1[57]=1.; p_output1[58]=t457; p_output1[59]=t464; p_output1[60]=t469; p_output1[61]=t472; p_output1[62]=t482; p_output1[63]=t484; p_output1[64]=20.*t347*t391*t403*var4[5] - 5.*t402*t454*var4[5] + 60.*t363*t367*t397*var4[25] - 60.*t347*t391*t403*var4[25] + 5.*t402*t454*var4[25] + 60.*t326*t349*t375*var4[45] - 150.*t363*t367*t397*var4[45] + 40.*t347*t391*t403*var4[45] - 140.*t326*t349*t375*var4[65] + 90.*t363*t367*t397*var4[65] + 20.*t477*t485*var4[65] + 80.*t326*t349*t375*var4[85] - 45.*t477*t485*var4[85] + 25.*t477*t485*var4[105]; p_output1[65]=20.*t1259*t369*t403*var4[5] + 5.*t402*t454*var4[5] + 60.*t1259*t347*t397*t402*var4[25] - 20.*t1259*t369*t403*var4[25] + 40.*t347*t391*t403*var4[25] - 20.*t402*t403*var4[25] - 5.*t402*t454*var4[25] + 60.*t1259*t367*t375*t391*var4[45] + 90.*t363*t367*t397*var4[45] - 60.*t347*t391*t397*var4[45] - 60.*t1259*t347*t397*t402*var4[45] - 40.*t347*t391*t403*var4[45] + 20.*t402*t403*var4[45] + 20.*t1259*t349*t363*var4[65] + 80.*t326*t349*t375*var4[65] - 60.*t363*t367*t375*var4[65] - 60.*t1259*t367*t375*t391*var4[65] - 90.*t363*t367*t397*var4[65] + 60.*t347*t391*t397*var4[65] - 20.*t326*t349*var4[85] - 20.*t1259*t349*t363*var4[85] - 80.*t326*t349*t375*var4[85] + 60.*t363*t367*t375*var4[85] + 25.*t477*t485*var4[85] + 20.*t326*t349*var4[105] - 25.*t477*t485*var4[105]; p_output1[66]=-20.*t312*t402*t403*var4[6] - 60.*t312*t347*t391*t397*var4[26] + 40.*t312*t402*t403*var4[26] - 60.*t312*t363*t367*t375*var4[46] + 120.*t312*t347*t391*t397*var4[46] - 20.*t312*t402*t403*var4[46] - 20.*t312*t326*t349*var4[66] + 120.*t312*t363*t367*t375*var4[66] - 60.*t312*t347*t391*t397*var4[66] + 40.*t312*t326*t349*var4[86] - 60.*t312*t363*t367*t375*var4[86] - 20.*t312*t326*t349*var4[106]; p_output1[67]=-20.*t239*t268*t402*t403*var4[6] - 60.*t239*t268*t347*t391*t397*var4[26] + 40.*t239*t268*t402*t403*var4[26] - 60.*t239*t268*t363*t367*t375*var4[46] + 120.*t239*t268*t347*t391*t397*var4[46] - 20.*t239*t268*t402*t403*var4[46] - 20.*t239*t268*t326*t349*var4[66] + 120.*t239*t268*t363*t367*t375*var4[66] - 60.*t239*t268*t347*t391*t397*var4[66] + 40.*t239*t268*t326*t349*var4[86] - 60.*t239*t268*t363*t367*t375*var4[86] - 20.*t239*t268*t326*t349*var4[106]; p_output1[68]=1.; p_output1[69]=t457; p_output1[70]=t464; p_output1[71]=t469; p_output1[72]=t472; p_output1[73]=t482; p_output1[74]=t484; p_output1[75]=20.*t347*t391*t403*var4[6] - 5.*t402*t454*var4[6] + 60.*t363*t367*t397*var4[26] - 60.*t347*t391*t403*var4[26] + 5.*t402*t454*var4[26] + 60.*t326*t349*t375*var4[46] - 150.*t363*t367*t397*var4[46] + 40.*t347*t391*t403*var4[46] - 140.*t326*t349*t375*var4[66] + 90.*t363*t367*t397*var4[66] + 20.*t477*t485*var4[66] + 80.*t326*t349*t375*var4[86] - 45.*t477*t485*var4[86] + 25.*t477*t485*var4[106]; p_output1[76]=20.*t1259*t369*t403*var4[6] + 5.*t402*t454*var4[6] + 60.*t1259*t347*t397*t402*var4[26] - 20.*t1259*t369*t403*var4[26] + 40.*t347*t391*t403*var4[26] - 20.*t402*t403*var4[26] - 5.*t402*t454*var4[26] + 60.*t1259*t367*t375*t391*var4[46] + 90.*t363*t367*t397*var4[46] - 60.*t347*t391*t397*var4[46] - 60.*t1259*t347*t397*t402*var4[46] - 40.*t347*t391*t403*var4[46] + 20.*t402*t403*var4[46] + 20.*t1259*t349*t363*var4[66] + 80.*t326*t349*t375*var4[66] - 60.*t363*t367*t375*var4[66] - 60.*t1259*t367*t375*t391*var4[66] - 90.*t363*t367*t397*var4[66] + 60.*t347*t391*t397*var4[66] - 20.*t326*t349*var4[86] - 20.*t1259*t349*t363*var4[86] - 80.*t326*t349*t375*var4[86] + 60.*t363*t367*t375*var4[86] + 25.*t477*t485*var4[86] + 20.*t326*t349*var4[106] - 25.*t477*t485*var4[106]; p_output1[77]=-20.*t312*t402*t403*var4[7] - 60.*t312*t347*t391*t397*var4[27] + 40.*t312*t402*t403*var4[27] - 60.*t312*t363*t367*t375*var4[47] + 120.*t312*t347*t391*t397*var4[47] - 20.*t312*t402*t403*var4[47] - 20.*t312*t326*t349*var4[67] + 120.*t312*t363*t367*t375*var4[67] - 60.*t312*t347*t391*t397*var4[67] + 40.*t312*t326*t349*var4[87] - 60.*t312*t363*t367*t375*var4[87] - 20.*t312*t326*t349*var4[107]; p_output1[78]=-20.*t239*t268*t402*t403*var4[7] - 60.*t239*t268*t347*t391*t397*var4[27] + 40.*t239*t268*t402*t403*var4[27] - 60.*t239*t268*t363*t367*t375*var4[47] + 120.*t239*t268*t347*t391*t397*var4[47] - 20.*t239*t268*t402*t403*var4[47] - 20.*t239*t268*t326*t349*var4[67] + 120.*t239*t268*t363*t367*t375*var4[67] - 60.*t239*t268*t347*t391*t397*var4[67] + 40.*t239*t268*t326*t349*var4[87] - 60.*t239*t268*t363*t367*t375*var4[87] - 20.*t239*t268*t326*t349*var4[107]; p_output1[79]=1.; p_output1[80]=t457; p_output1[81]=t464; p_output1[82]=t469; p_output1[83]=t472; p_output1[84]=t482; p_output1[85]=t484; p_output1[86]=20.*t347*t391*t403*var4[7] - 5.*t402*t454*var4[7] + 60.*t363*t367*t397*var4[27] - 60.*t347*t391*t403*var4[27] + 5.*t402*t454*var4[27] + 60.*t326*t349*t375*var4[47] - 150.*t363*t367*t397*var4[47] + 40.*t347*t391*t403*var4[47] - 140.*t326*t349*t375*var4[67] + 90.*t363*t367*t397*var4[67] + 20.*t477*t485*var4[67] + 80.*t326*t349*t375*var4[87] - 45.*t477*t485*var4[87] + 25.*t477*t485*var4[107]; p_output1[87]=20.*t1259*t369*t403*var4[7] + 5.*t402*t454*var4[7] + 60.*t1259*t347*t397*t402*var4[27] - 20.*t1259*t369*t403*var4[27] + 40.*t347*t391*t403*var4[27] - 20.*t402*t403*var4[27] - 5.*t402*t454*var4[27] + 60.*t1259*t367*t375*t391*var4[47] + 90.*t363*t367*t397*var4[47] - 60.*t347*t391*t397*var4[47] - 60.*t1259*t347*t397*t402*var4[47] - 40.*t347*t391*t403*var4[47] + 20.*t402*t403*var4[47] + 20.*t1259*t349*t363*var4[67] + 80.*t326*t349*t375*var4[67] - 60.*t363*t367*t375*var4[67] - 60.*t1259*t367*t375*t391*var4[67] - 90.*t363*t367*t397*var4[67] + 60.*t347*t391*t397*var4[67] - 20.*t326*t349*var4[87] - 20.*t1259*t349*t363*var4[87] - 80.*t326*t349*t375*var4[87] + 60.*t363*t367*t375*var4[87] + 25.*t477*t485*var4[87] + 20.*t326*t349*var4[107] - 25.*t477*t485*var4[107]; p_output1[88]=-20.*t312*t402*t403*var4[8] - 60.*t312*t347*t391*t397*var4[28] + 40.*t312*t402*t403*var4[28] - 60.*t312*t363*t367*t375*var4[48] + 120.*t312*t347*t391*t397*var4[48] - 20.*t312*t402*t403*var4[48] - 20.*t312*t326*t349*var4[68] + 120.*t312*t363*t367*t375*var4[68] - 60.*t312*t347*t391*t397*var4[68] + 40.*t312*t326*t349*var4[88] - 60.*t312*t363*t367*t375*var4[88] - 20.*t312*t326*t349*var4[108]; p_output1[89]=-20.*t239*t268*t402*t403*var4[8] - 60.*t239*t268*t347*t391*t397*var4[28] + 40.*t239*t268*t402*t403*var4[28] - 60.*t239*t268*t363*t367*t375*var4[48] + 120.*t239*t268*t347*t391*t397*var4[48] - 20.*t239*t268*t402*t403*var4[48] - 20.*t239*t268*t326*t349*var4[68] + 120.*t239*t268*t363*t367*t375*var4[68] - 60.*t239*t268*t347*t391*t397*var4[68] + 40.*t239*t268*t326*t349*var4[88] - 60.*t239*t268*t363*t367*t375*var4[88] - 20.*t239*t268*t326*t349*var4[108]; p_output1[90]=1.; p_output1[91]=t457; p_output1[92]=t464; p_output1[93]=t469; p_output1[94]=t472; p_output1[95]=t482; p_output1[96]=t484; p_output1[97]=20.*t347*t391*t403*var4[8] - 5.*t402*t454*var4[8] + 60.*t363*t367*t397*var4[28] - 60.*t347*t391*t403*var4[28] + 5.*t402*t454*var4[28] + 60.*t326*t349*t375*var4[48] - 150.*t363*t367*t397*var4[48] + 40.*t347*t391*t403*var4[48] - 140.*t326*t349*t375*var4[68] + 90.*t363*t367*t397*var4[68] + 20.*t477*t485*var4[68] + 80.*t326*t349*t375*var4[88] - 45.*t477*t485*var4[88] + 25.*t477*t485*var4[108]; p_output1[98]=20.*t1259*t369*t403*var4[8] + 5.*t402*t454*var4[8] + 60.*t1259*t347*t397*t402*var4[28] - 20.*t1259*t369*t403*var4[28] + 40.*t347*t391*t403*var4[28] - 20.*t402*t403*var4[28] - 5.*t402*t454*var4[28] + 60.*t1259*t367*t375*t391*var4[48] + 90.*t363*t367*t397*var4[48] - 60.*t347*t391*t397*var4[48] - 60.*t1259*t347*t397*t402*var4[48] - 40.*t347*t391*t403*var4[48] + 20.*t402*t403*var4[48] + 20.*t1259*t349*t363*var4[68] + 80.*t326*t349*t375*var4[68] - 60.*t363*t367*t375*var4[68] - 60.*t1259*t367*t375*t391*var4[68] - 90.*t363*t367*t397*var4[68] + 60.*t347*t391*t397*var4[68] - 20.*t326*t349*var4[88] - 20.*t1259*t349*t363*var4[88] - 80.*t326*t349*t375*var4[88] + 60.*t363*t367*t375*var4[88] + 25.*t477*t485*var4[88] + 20.*t326*t349*var4[108] - 25.*t477*t485*var4[108]; p_output1[99]=-20.*t312*t402*t403*var4[9] - 60.*t312*t347*t391*t397*var4[29] + 40.*t312*t402*t403*var4[29] - 60.*t312*t363*t367*t375*var4[49] + 120.*t312*t347*t391*t397*var4[49] - 20.*t312*t402*t403*var4[49] - 20.*t312*t326*t349*var4[69] + 120.*t312*t363*t367*t375*var4[69] - 60.*t312*t347*t391*t397*var4[69] + 40.*t312*t326*t349*var4[89] - 60.*t312*t363*t367*t375*var4[89] - 20.*t312*t326*t349*var4[109]; p_output1[100]=-20.*t239*t268*t402*t403*var4[9] - 60.*t239*t268*t347*t391*t397*var4[29] + 40.*t239*t268*t402*t403*var4[29] - 60.*t239*t268*t363*t367*t375*var4[49] + 120.*t239*t268*t347*t391*t397*var4[49] - 20.*t239*t268*t402*t403*var4[49] - 20.*t239*t268*t326*t349*var4[69] + 120.*t239*t268*t363*t367*t375*var4[69] - 60.*t239*t268*t347*t391*t397*var4[69] + 40.*t239*t268*t326*t349*var4[89] - 60.*t239*t268*t363*t367*t375*var4[89] - 20.*t239*t268*t326*t349*var4[109]; p_output1[101]=1.; p_output1[102]=t457; p_output1[103]=t464; p_output1[104]=t469; p_output1[105]=t472; p_output1[106]=t482; p_output1[107]=t484; p_output1[108]=20.*t347*t391*t403*var4[9] - 5.*t402*t454*var4[9] + 60.*t363*t367*t397*var4[29] - 60.*t347*t391*t403*var4[29] + 5.*t402*t454*var4[29] + 60.*t326*t349*t375*var4[49] - 150.*t363*t367*t397*var4[49] + 40.*t347*t391*t403*var4[49] - 140.*t326*t349*t375*var4[69] + 90.*t363*t367*t397*var4[69] + 20.*t477*t485*var4[69] + 80.*t326*t349*t375*var4[89] - 45.*t477*t485*var4[89] + 25.*t477*t485*var4[109]; p_output1[109]=20.*t1259*t369*t403*var4[9] + 5.*t402*t454*var4[9] + 60.*t1259*t347*t397*t402*var4[29] - 20.*t1259*t369*t403*var4[29] + 40.*t347*t391*t403*var4[29] - 20.*t402*t403*var4[29] - 5.*t402*t454*var4[29] + 60.*t1259*t367*t375*t391*var4[49] + 90.*t363*t367*t397*var4[49] - 60.*t347*t391*t397*var4[49] - 60.*t1259*t347*t397*t402*var4[49] - 40.*t347*t391*t403*var4[49] + 20.*t402*t403*var4[49] + 20.*t1259*t349*t363*var4[69] + 80.*t326*t349*t375*var4[69] - 60.*t363*t367*t375*var4[69] - 60.*t1259*t367*t375*t391*var4[69] - 90.*t363*t367*t397*var4[69] + 60.*t347*t391*t397*var4[69] - 20.*t326*t349*var4[89] - 20.*t1259*t349*t363*var4[89] - 80.*t326*t349*t375*var4[89] + 60.*t363*t367*t375*var4[89] + 25.*t477*t485*var4[89] + 20.*t326*t349*var4[109] - 25.*t477*t485*var4[109]; p_output1[110]=-20.*t312*t402*t403*var4[10] - 60.*t312*t347*t391*t397*var4[30] + 40.*t312*t402*t403*var4[30] - 60.*t312*t363*t367*t375*var4[50] + 120.*t312*t347*t391*t397*var4[50] - 20.*t312*t402*t403*var4[50] - 20.*t312*t326*t349*var4[70] + 120.*t312*t363*t367*t375*var4[70] - 60.*t312*t347*t391*t397*var4[70] + 40.*t312*t326*t349*var4[90] - 60.*t312*t363*t367*t375*var4[90] - 20.*t312*t326*t349*var4[110]; p_output1[111]=-20.*t239*t268*t402*t403*var4[10] - 60.*t239*t268*t347*t391*t397*var4[30] + 40.*t239*t268*t402*t403*var4[30] - 60.*t239*t268*t363*t367*t375*var4[50] + 120.*t239*t268*t347*t391*t397*var4[50] - 20.*t239*t268*t402*t403*var4[50] - 20.*t239*t268*t326*t349*var4[70] + 120.*t239*t268*t363*t367*t375*var4[70] - 60.*t239*t268*t347*t391*t397*var4[70] + 40.*t239*t268*t326*t349*var4[90] - 60.*t239*t268*t363*t367*t375*var4[90] - 20.*t239*t268*t326*t349*var4[110]; p_output1[112]=1.; p_output1[113]=t457; p_output1[114]=t464; p_output1[115]=t469; p_output1[116]=t472; p_output1[117]=t482; p_output1[118]=t484; p_output1[119]=20.*t347*t391*t403*var4[10] - 5.*t402*t454*var4[10] + 60.*t363*t367*t397*var4[30] - 60.*t347*t391*t403*var4[30] + 5.*t402*t454*var4[30] + 60.*t326*t349*t375*var4[50] - 150.*t363*t367*t397*var4[50] + 40.*t347*t391*t403*var4[50] - 140.*t326*t349*t375*var4[70] + 90.*t363*t367*t397*var4[70] + 20.*t477*t485*var4[70] + 80.*t326*t349*t375*var4[90] - 45.*t477*t485*var4[90] + 25.*t477*t485*var4[110]; p_output1[120]=20.*t1259*t369*t403*var4[10] + 5.*t402*t454*var4[10] + 60.*t1259*t347*t397*t402*var4[30] - 20.*t1259*t369*t403*var4[30] + 40.*t347*t391*t403*var4[30] - 20.*t402*t403*var4[30] - 5.*t402*t454*var4[30] + 60.*t1259*t367*t375*t391*var4[50] + 90.*t363*t367*t397*var4[50] - 60.*t347*t391*t397*var4[50] - 60.*t1259*t347*t397*t402*var4[50] - 40.*t347*t391*t403*var4[50] + 20.*t402*t403*var4[50] + 20.*t1259*t349*t363*var4[70] + 80.*t326*t349*t375*var4[70] - 60.*t363*t367*t375*var4[70] - 60.*t1259*t367*t375*t391*var4[70] - 90.*t363*t367*t397*var4[70] + 60.*t347*t391*t397*var4[70] - 20.*t326*t349*var4[90] - 20.*t1259*t349*t363*var4[90] - 80.*t326*t349*t375*var4[90] + 60.*t363*t367*t375*var4[90] + 25.*t477*t485*var4[90] + 20.*t326*t349*var4[110] - 25.*t477*t485*var4[110]; p_output1[121]=-20.*t312*t402*t403*var4[11] - 60.*t312*t347*t391*t397*var4[31] + 40.*t312*t402*t403*var4[31] - 60.*t312*t363*t367*t375*var4[51] + 120.*t312*t347*t391*t397*var4[51] - 20.*t312*t402*t403*var4[51] - 20.*t312*t326*t349*var4[71] + 120.*t312*t363*t367*t375*var4[71] - 60.*t312*t347*t391*t397*var4[71] + 40.*t312*t326*t349*var4[91] - 60.*t312*t363*t367*t375*var4[91] - 20.*t312*t326*t349*var4[111]; p_output1[122]=-20.*t239*t268*t402*t403*var4[11] - 60.*t239*t268*t347*t391*t397*var4[31] + 40.*t239*t268*t402*t403*var4[31] - 60.*t239*t268*t363*t367*t375*var4[51] + 120.*t239*t268*t347*t391*t397*var4[51] - 20.*t239*t268*t402*t403*var4[51] - 20.*t239*t268*t326*t349*var4[71] + 120.*t239*t268*t363*t367*t375*var4[71] - 60.*t239*t268*t347*t391*t397*var4[71] + 40.*t239*t268*t326*t349*var4[91] - 60.*t239*t268*t363*t367*t375*var4[91] - 20.*t239*t268*t326*t349*var4[111]; p_output1[123]=1.; p_output1[124]=t457; p_output1[125]=t464; p_output1[126]=t469; p_output1[127]=t472; p_output1[128]=t482; p_output1[129]=t484; p_output1[130]=20.*t347*t391*t403*var4[11] - 5.*t402*t454*var4[11] + 60.*t363*t367*t397*var4[31] - 60.*t347*t391*t403*var4[31] + 5.*t402*t454*var4[31] + 60.*t326*t349*t375*var4[51] - 150.*t363*t367*t397*var4[51] + 40.*t347*t391*t403*var4[51] - 140.*t326*t349*t375*var4[71] + 90.*t363*t367*t397*var4[71] + 20.*t477*t485*var4[71] + 80.*t326*t349*t375*var4[91] - 45.*t477*t485*var4[91] + 25.*t477*t485*var4[111]; p_output1[131]=20.*t1259*t369*t403*var4[11] + 5.*t402*t454*var4[11] + 60.*t1259*t347*t397*t402*var4[31] - 20.*t1259*t369*t403*var4[31] + 40.*t347*t391*t403*var4[31] - 20.*t402*t403*var4[31] - 5.*t402*t454*var4[31] + 60.*t1259*t367*t375*t391*var4[51] + 90.*t363*t367*t397*var4[51] - 60.*t347*t391*t397*var4[51] - 60.*t1259*t347*t397*t402*var4[51] - 40.*t347*t391*t403*var4[51] + 20.*t402*t403*var4[51] + 20.*t1259*t349*t363*var4[71] + 80.*t326*t349*t375*var4[71] - 60.*t363*t367*t375*var4[71] - 60.*t1259*t367*t375*t391*var4[71] - 90.*t363*t367*t397*var4[71] + 60.*t347*t391*t397*var4[71] - 20.*t326*t349*var4[91] - 20.*t1259*t349*t363*var4[91] - 80.*t326*t349*t375*var4[91] + 60.*t363*t367*t375*var4[91] + 25.*t477*t485*var4[91] + 20.*t326*t349*var4[111] - 25.*t477*t485*var4[111]; p_output1[132]=-20.*t312*t402*t403*var4[12] - 60.*t312*t347*t391*t397*var4[32] + 40.*t312*t402*t403*var4[32] - 60.*t312*t363*t367*t375*var4[52] + 120.*t312*t347*t391*t397*var4[52] - 20.*t312*t402*t403*var4[52] - 20.*t312*t326*t349*var4[72] + 120.*t312*t363*t367*t375*var4[72] - 60.*t312*t347*t391*t397*var4[72] + 40.*t312*t326*t349*var4[92] - 60.*t312*t363*t367*t375*var4[92] - 20.*t312*t326*t349*var4[112]; p_output1[133]=-20.*t239*t268*t402*t403*var4[12] - 60.*t239*t268*t347*t391*t397*var4[32] + 40.*t239*t268*t402*t403*var4[32] - 60.*t239*t268*t363*t367*t375*var4[52] + 120.*t239*t268*t347*t391*t397*var4[52] - 20.*t239*t268*t402*t403*var4[52] - 20.*t239*t268*t326*t349*var4[72] + 120.*t239*t268*t363*t367*t375*var4[72] - 60.*t239*t268*t347*t391*t397*var4[72] + 40.*t239*t268*t326*t349*var4[92] - 60.*t239*t268*t363*t367*t375*var4[92] - 20.*t239*t268*t326*t349*var4[112]; p_output1[134]=1.; p_output1[135]=t457; p_output1[136]=t464; p_output1[137]=t469; p_output1[138]=t472; p_output1[139]=t482; p_output1[140]=t484; p_output1[141]=20.*t347*t391*t403*var4[12] - 5.*t402*t454*var4[12] + 60.*t363*t367*t397*var4[32] - 60.*t347*t391*t403*var4[32] + 5.*t402*t454*var4[32] + 60.*t326*t349*t375*var4[52] - 150.*t363*t367*t397*var4[52] + 40.*t347*t391*t403*var4[52] - 140.*t326*t349*t375*var4[72] + 90.*t363*t367*t397*var4[72] + 20.*t477*t485*var4[72] + 80.*t326*t349*t375*var4[92] - 45.*t477*t485*var4[92] + 25.*t477*t485*var4[112]; p_output1[142]=20.*t1259*t369*t403*var4[12] + 5.*t402*t454*var4[12] + 60.*t1259*t347*t397*t402*var4[32] - 20.*t1259*t369*t403*var4[32] + 40.*t347*t391*t403*var4[32] - 20.*t402*t403*var4[32] - 5.*t402*t454*var4[32] + 60.*t1259*t367*t375*t391*var4[52] + 90.*t363*t367*t397*var4[52] - 60.*t347*t391*t397*var4[52] - 60.*t1259*t347*t397*t402*var4[52] - 40.*t347*t391*t403*var4[52] + 20.*t402*t403*var4[52] + 20.*t1259*t349*t363*var4[72] + 80.*t326*t349*t375*var4[72] - 60.*t363*t367*t375*var4[72] - 60.*t1259*t367*t375*t391*var4[72] - 90.*t363*t367*t397*var4[72] + 60.*t347*t391*t397*var4[72] - 20.*t326*t349*var4[92] - 20.*t1259*t349*t363*var4[92] - 80.*t326*t349*t375*var4[92] + 60.*t363*t367*t375*var4[92] + 25.*t477*t485*var4[92] + 20.*t326*t349*var4[112] - 25.*t477*t485*var4[112]; p_output1[143]=-20.*t312*t402*t403*var4[13] - 60.*t312*t347*t391*t397*var4[33] + 40.*t312*t402*t403*var4[33] - 60.*t312*t363*t367*t375*var4[53] + 120.*t312*t347*t391*t397*var4[53] - 20.*t312*t402*t403*var4[53] - 20.*t312*t326*t349*var4[73] + 120.*t312*t363*t367*t375*var4[73] - 60.*t312*t347*t391*t397*var4[73] + 40.*t312*t326*t349*var4[93] - 60.*t312*t363*t367*t375*var4[93] - 20.*t312*t326*t349*var4[113]; p_output1[144]=-20.*t239*t268*t402*t403*var4[13] - 60.*t239*t268*t347*t391*t397*var4[33] + 40.*t239*t268*t402*t403*var4[33] - 60.*t239*t268*t363*t367*t375*var4[53] + 120.*t239*t268*t347*t391*t397*var4[53] - 20.*t239*t268*t402*t403*var4[53] - 20.*t239*t268*t326*t349*var4[73] + 120.*t239*t268*t363*t367*t375*var4[73] - 60.*t239*t268*t347*t391*t397*var4[73] + 40.*t239*t268*t326*t349*var4[93] - 60.*t239*t268*t363*t367*t375*var4[93] - 20.*t239*t268*t326*t349*var4[113]; p_output1[145]=1.; p_output1[146]=t457; p_output1[147]=t464; p_output1[148]=t469; p_output1[149]=t472; p_output1[150]=t482; p_output1[151]=t484; p_output1[152]=20.*t347*t391*t403*var4[13] - 5.*t402*t454*var4[13] + 60.*t363*t367*t397*var4[33] - 60.*t347*t391*t403*var4[33] + 5.*t402*t454*var4[33] + 60.*t326*t349*t375*var4[53] - 150.*t363*t367*t397*var4[53] + 40.*t347*t391*t403*var4[53] - 140.*t326*t349*t375*var4[73] + 90.*t363*t367*t397*var4[73] + 20.*t477*t485*var4[73] + 80.*t326*t349*t375*var4[93] - 45.*t477*t485*var4[93] + 25.*t477*t485*var4[113]; p_output1[153]=20.*t1259*t369*t403*var4[13] + 5.*t402*t454*var4[13] + 60.*t1259*t347*t397*t402*var4[33] - 20.*t1259*t369*t403*var4[33] + 40.*t347*t391*t403*var4[33] - 20.*t402*t403*var4[33] - 5.*t402*t454*var4[33] + 60.*t1259*t367*t375*t391*var4[53] + 90.*t363*t367*t397*var4[53] - 60.*t347*t391*t397*var4[53] - 60.*t1259*t347*t397*t402*var4[53] - 40.*t347*t391*t403*var4[53] + 20.*t402*t403*var4[53] + 20.*t1259*t349*t363*var4[73] + 80.*t326*t349*t375*var4[73] - 60.*t363*t367*t375*var4[73] - 60.*t1259*t367*t375*t391*var4[73] - 90.*t363*t367*t397*var4[73] + 60.*t347*t391*t397*var4[73] - 20.*t326*t349*var4[93] - 20.*t1259*t349*t363*var4[93] - 80.*t326*t349*t375*var4[93] + 60.*t363*t367*t375*var4[93] + 25.*t477*t485*var4[93] + 20.*t326*t349*var4[113] - 25.*t477*t485*var4[113]; p_output1[154]=-20.*t312*t402*t403*var4[14] - 60.*t312*t347*t391*t397*var4[34] + 40.*t312*t402*t403*var4[34] - 60.*t312*t363*t367*t375*var4[54] + 120.*t312*t347*t391*t397*var4[54] - 20.*t312*t402*t403*var4[54] - 20.*t312*t326*t349*var4[74] + 120.*t312*t363*t367*t375*var4[74] - 60.*t312*t347*t391*t397*var4[74] + 40.*t312*t326*t349*var4[94] - 60.*t312*t363*t367*t375*var4[94] - 20.*t312*t326*t349*var4[114]; p_output1[155]=-20.*t239*t268*t402*t403*var4[14] - 60.*t239*t268*t347*t391*t397*var4[34] + 40.*t239*t268*t402*t403*var4[34] - 60.*t239*t268*t363*t367*t375*var4[54] + 120.*t239*t268*t347*t391*t397*var4[54] - 20.*t239*t268*t402*t403*var4[54] - 20.*t239*t268*t326*t349*var4[74] + 120.*t239*t268*t363*t367*t375*var4[74] - 60.*t239*t268*t347*t391*t397*var4[74] + 40.*t239*t268*t326*t349*var4[94] - 60.*t239*t268*t363*t367*t375*var4[94] - 20.*t239*t268*t326*t349*var4[114]; p_output1[156]=1.; p_output1[157]=t457; p_output1[158]=t464; p_output1[159]=t469; p_output1[160]=t472; p_output1[161]=t482; p_output1[162]=t484; p_output1[163]=20.*t347*t391*t403*var4[14] - 5.*t402*t454*var4[14] + 60.*t363*t367*t397*var4[34] - 60.*t347*t391*t403*var4[34] + 5.*t402*t454*var4[34] + 60.*t326*t349*t375*var4[54] - 150.*t363*t367*t397*var4[54] + 40.*t347*t391*t403*var4[54] - 140.*t326*t349*t375*var4[74] + 90.*t363*t367*t397*var4[74] + 20.*t477*t485*var4[74] + 80.*t326*t349*t375*var4[94] - 45.*t477*t485*var4[94] + 25.*t477*t485*var4[114]; p_output1[164]=20.*t1259*t369*t403*var4[14] + 5.*t402*t454*var4[14] + 60.*t1259*t347*t397*t402*var4[34] - 20.*t1259*t369*t403*var4[34] + 40.*t347*t391*t403*var4[34] - 20.*t402*t403*var4[34] - 5.*t402*t454*var4[34] + 60.*t1259*t367*t375*t391*var4[54] + 90.*t363*t367*t397*var4[54] - 60.*t347*t391*t397*var4[54] - 60.*t1259*t347*t397*t402*var4[54] - 40.*t347*t391*t403*var4[54] + 20.*t402*t403*var4[54] + 20.*t1259*t349*t363*var4[74] + 80.*t326*t349*t375*var4[74] - 60.*t363*t367*t375*var4[74] - 60.*t1259*t367*t375*t391*var4[74] - 90.*t363*t367*t397*var4[74] + 60.*t347*t391*t397*var4[74] - 20.*t326*t349*var4[94] - 20.*t1259*t349*t363*var4[94] - 80.*t326*t349*t375*var4[94] + 60.*t363*t367*t375*var4[94] + 25.*t477*t485*var4[94] + 20.*t326*t349*var4[114] - 25.*t477*t485*var4[114]; p_output1[165]=-20.*t312*t402*t403*var4[15] - 60.*t312*t347*t391*t397*var4[35] + 40.*t312*t402*t403*var4[35] - 60.*t312*t363*t367*t375*var4[55] + 120.*t312*t347*t391*t397*var4[55] - 20.*t312*t402*t403*var4[55] - 20.*t312*t326*t349*var4[75] + 120.*t312*t363*t367*t375*var4[75] - 60.*t312*t347*t391*t397*var4[75] + 40.*t312*t326*t349*var4[95] - 60.*t312*t363*t367*t375*var4[95] - 20.*t312*t326*t349*var4[115]; p_output1[166]=-20.*t239*t268*t402*t403*var4[15] - 60.*t239*t268*t347*t391*t397*var4[35] + 40.*t239*t268*t402*t403*var4[35] - 60.*t239*t268*t363*t367*t375*var4[55] + 120.*t239*t268*t347*t391*t397*var4[55] - 20.*t239*t268*t402*t403*var4[55] - 20.*t239*t268*t326*t349*var4[75] + 120.*t239*t268*t363*t367*t375*var4[75] - 60.*t239*t268*t347*t391*t397*var4[75] + 40.*t239*t268*t326*t349*var4[95] - 60.*t239*t268*t363*t367*t375*var4[95] - 20.*t239*t268*t326*t349*var4[115]; p_output1[167]=1.; p_output1[168]=t457; p_output1[169]=t464; p_output1[170]=t469; p_output1[171]=t472; p_output1[172]=t482; p_output1[173]=t484; p_output1[174]=20.*t347*t391*t403*var4[15] - 5.*t402*t454*var4[15] + 60.*t363*t367*t397*var4[35] - 60.*t347*t391*t403*var4[35] + 5.*t402*t454*var4[35] + 60.*t326*t349*t375*var4[55] - 150.*t363*t367*t397*var4[55] + 40.*t347*t391*t403*var4[55] - 140.*t326*t349*t375*var4[75] + 90.*t363*t367*t397*var4[75] + 20.*t477*t485*var4[75] + 80.*t326*t349*t375*var4[95] - 45.*t477*t485*var4[95] + 25.*t477*t485*var4[115]; p_output1[175]=20.*t1259*t369*t403*var4[15] + 5.*t402*t454*var4[15] + 60.*t1259*t347*t397*t402*var4[35] - 20.*t1259*t369*t403*var4[35] + 40.*t347*t391*t403*var4[35] - 20.*t402*t403*var4[35] - 5.*t402*t454*var4[35] + 60.*t1259*t367*t375*t391*var4[55] + 90.*t363*t367*t397*var4[55] - 60.*t347*t391*t397*var4[55] - 60.*t1259*t347*t397*t402*var4[55] - 40.*t347*t391*t403*var4[55] + 20.*t402*t403*var4[55] + 20.*t1259*t349*t363*var4[75] + 80.*t326*t349*t375*var4[75] - 60.*t363*t367*t375*var4[75] - 60.*t1259*t367*t375*t391*var4[75] - 90.*t363*t367*t397*var4[75] + 60.*t347*t391*t397*var4[75] - 20.*t326*t349*var4[95] - 20.*t1259*t349*t363*var4[95] - 80.*t326*t349*t375*var4[95] + 60.*t363*t367*t375*var4[95] + 25.*t477*t485*var4[95] + 20.*t326*t349*var4[115] - 25.*t477*t485*var4[115]; p_output1[176]=-20.*t312*t402*t403*var4[16] - 60.*t312*t347*t391*t397*var4[36] + 40.*t312*t402*t403*var4[36] - 60.*t312*t363*t367*t375*var4[56] + 120.*t312*t347*t391*t397*var4[56] - 20.*t312*t402*t403*var4[56] - 20.*t312*t326*t349*var4[76] + 120.*t312*t363*t367*t375*var4[76] - 60.*t312*t347*t391*t397*var4[76] + 40.*t312*t326*t349*var4[96] - 60.*t312*t363*t367*t375*var4[96] - 20.*t312*t326*t349*var4[116]; p_output1[177]=-20.*t239*t268*t402*t403*var4[16] - 60.*t239*t268*t347*t391*t397*var4[36] + 40.*t239*t268*t402*t403*var4[36] - 60.*t239*t268*t363*t367*t375*var4[56] + 120.*t239*t268*t347*t391*t397*var4[56] - 20.*t239*t268*t402*t403*var4[56] - 20.*t239*t268*t326*t349*var4[76] + 120.*t239*t268*t363*t367*t375*var4[76] - 60.*t239*t268*t347*t391*t397*var4[76] + 40.*t239*t268*t326*t349*var4[96] - 60.*t239*t268*t363*t367*t375*var4[96] - 20.*t239*t268*t326*t349*var4[116]; p_output1[178]=1.; p_output1[179]=t457; p_output1[180]=t464; p_output1[181]=t469; p_output1[182]=t472; p_output1[183]=t482; p_output1[184]=t484; p_output1[185]=20.*t347*t391*t403*var4[16] - 5.*t402*t454*var4[16] + 60.*t363*t367*t397*var4[36] - 60.*t347*t391*t403*var4[36] + 5.*t402*t454*var4[36] + 60.*t326*t349*t375*var4[56] - 150.*t363*t367*t397*var4[56] + 40.*t347*t391*t403*var4[56] - 140.*t326*t349*t375*var4[76] + 90.*t363*t367*t397*var4[76] + 20.*t477*t485*var4[76] + 80.*t326*t349*t375*var4[96] - 45.*t477*t485*var4[96] + 25.*t477*t485*var4[116]; p_output1[186]=20.*t1259*t369*t403*var4[16] + 5.*t402*t454*var4[16] + 60.*t1259*t347*t397*t402*var4[36] - 20.*t1259*t369*t403*var4[36] + 40.*t347*t391*t403*var4[36] - 20.*t402*t403*var4[36] - 5.*t402*t454*var4[36] + 60.*t1259*t367*t375*t391*var4[56] + 90.*t363*t367*t397*var4[56] - 60.*t347*t391*t397*var4[56] - 60.*t1259*t347*t397*t402*var4[56] - 40.*t347*t391*t403*var4[56] + 20.*t402*t403*var4[56] + 20.*t1259*t349*t363*var4[76] + 80.*t326*t349*t375*var4[76] - 60.*t363*t367*t375*var4[76] - 60.*t1259*t367*t375*t391*var4[76] - 90.*t363*t367*t397*var4[76] + 60.*t347*t391*t397*var4[76] - 20.*t326*t349*var4[96] - 20.*t1259*t349*t363*var4[96] - 80.*t326*t349*t375*var4[96] + 60.*t363*t367*t375*var4[96] + 25.*t477*t485*var4[96] + 20.*t326*t349*var4[116] - 25.*t477*t485*var4[116]; p_output1[187]=-20.*t312*t402*t403*var4[17] - 60.*t312*t347*t391*t397*var4[37] + 40.*t312*t402*t403*var4[37] - 60.*t312*t363*t367*t375*var4[57] + 120.*t312*t347*t391*t397*var4[57] - 20.*t312*t402*t403*var4[57] - 20.*t312*t326*t349*var4[77] + 120.*t312*t363*t367*t375*var4[77] - 60.*t312*t347*t391*t397*var4[77] + 40.*t312*t326*t349*var4[97] - 60.*t312*t363*t367*t375*var4[97] - 20.*t312*t326*t349*var4[117]; p_output1[188]=-20.*t239*t268*t402*t403*var4[17] - 60.*t239*t268*t347*t391*t397*var4[37] + 40.*t239*t268*t402*t403*var4[37] - 60.*t239*t268*t363*t367*t375*var4[57] + 120.*t239*t268*t347*t391*t397*var4[57] - 20.*t239*t268*t402*t403*var4[57] - 20.*t239*t268*t326*t349*var4[77] + 120.*t239*t268*t363*t367*t375*var4[77] - 60.*t239*t268*t347*t391*t397*var4[77] + 40.*t239*t268*t326*t349*var4[97] - 60.*t239*t268*t363*t367*t375*var4[97] - 20.*t239*t268*t326*t349*var4[117]; p_output1[189]=1.; p_output1[190]=t457; p_output1[191]=t464; p_output1[192]=t469; p_output1[193]=t472; p_output1[194]=t482; p_output1[195]=t484; p_output1[196]=20.*t347*t391*t403*var4[17] - 5.*t402*t454*var4[17] + 60.*t363*t367*t397*var4[37] - 60.*t347*t391*t403*var4[37] + 5.*t402*t454*var4[37] + 60.*t326*t349*t375*var4[57] - 150.*t363*t367*t397*var4[57] + 40.*t347*t391*t403*var4[57] - 140.*t326*t349*t375*var4[77] + 90.*t363*t367*t397*var4[77] + 20.*t477*t485*var4[77] + 80.*t326*t349*t375*var4[97] - 45.*t477*t485*var4[97] + 25.*t477*t485*var4[117]; p_output1[197]=20.*t1259*t369*t403*var4[17] + 5.*t402*t454*var4[17] + 60.*t1259*t347*t397*t402*var4[37] - 20.*t1259*t369*t403*var4[37] + 40.*t347*t391*t403*var4[37] - 20.*t402*t403*var4[37] - 5.*t402*t454*var4[37] + 60.*t1259*t367*t375*t391*var4[57] + 90.*t363*t367*t397*var4[57] - 60.*t347*t391*t397*var4[57] - 60.*t1259*t347*t397*t402*var4[57] - 40.*t347*t391*t403*var4[57] + 20.*t402*t403*var4[57] + 20.*t1259*t349*t363*var4[77] + 80.*t326*t349*t375*var4[77] - 60.*t363*t367*t375*var4[77] - 60.*t1259*t367*t375*t391*var4[77] - 90.*t363*t367*t397*var4[77] + 60.*t347*t391*t397*var4[77] - 20.*t326*t349*var4[97] - 20.*t1259*t349*t363*var4[97] - 80.*t326*t349*t375*var4[97] + 60.*t363*t367*t375*var4[97] + 25.*t477*t485*var4[97] + 20.*t326*t349*var4[117] - 25.*t477*t485*var4[117]; p_output1[198]=-20.*t312*t402*t403*var4[18] - 60.*t312*t347*t391*t397*var4[38] + 40.*t312*t402*t403*var4[38] - 60.*t312*t363*t367*t375*var4[58] + 120.*t312*t347*t391*t397*var4[58] - 20.*t312*t402*t403*var4[58] - 20.*t312*t326*t349*var4[78] + 120.*t312*t363*t367*t375*var4[78] - 60.*t312*t347*t391*t397*var4[78] + 40.*t312*t326*t349*var4[98] - 60.*t312*t363*t367*t375*var4[98] - 20.*t312*t326*t349*var4[118]; p_output1[199]=-20.*t239*t268*t402*t403*var4[18] - 60.*t239*t268*t347*t391*t397*var4[38] + 40.*t239*t268*t402*t403*var4[38] - 60.*t239*t268*t363*t367*t375*var4[58] + 120.*t239*t268*t347*t391*t397*var4[58] - 20.*t239*t268*t402*t403*var4[58] - 20.*t239*t268*t326*t349*var4[78] + 120.*t239*t268*t363*t367*t375*var4[78] - 60.*t239*t268*t347*t391*t397*var4[78] + 40.*t239*t268*t326*t349*var4[98] - 60.*t239*t268*t363*t367*t375*var4[98] - 20.*t239*t268*t326*t349*var4[118]; p_output1[200]=1.; p_output1[201]=t457; p_output1[202]=t464; p_output1[203]=t469; p_output1[204]=t472; p_output1[205]=t482; p_output1[206]=t484; p_output1[207]=20.*t347*t391*t403*var4[18] - 5.*t402*t454*var4[18] + 60.*t363*t367*t397*var4[38] - 60.*t347*t391*t403*var4[38] + 5.*t402*t454*var4[38] + 60.*t326*t349*t375*var4[58] - 150.*t363*t367*t397*var4[58] + 40.*t347*t391*t403*var4[58] - 140.*t326*t349*t375*var4[78] + 90.*t363*t367*t397*var4[78] + 20.*t477*t485*var4[78] + 80.*t326*t349*t375*var4[98] - 45.*t477*t485*var4[98] + 25.*t477*t485*var4[118]; p_output1[208]=20.*t1259*t369*t403*var4[18] + 5.*t402*t454*var4[18] + 60.*t1259*t347*t397*t402*var4[38] - 20.*t1259*t369*t403*var4[38] + 40.*t347*t391*t403*var4[38] - 20.*t402*t403*var4[38] - 5.*t402*t454*var4[38] + 60.*t1259*t367*t375*t391*var4[58] + 90.*t363*t367*t397*var4[58] - 60.*t347*t391*t397*var4[58] - 60.*t1259*t347*t397*t402*var4[58] - 40.*t347*t391*t403*var4[58] + 20.*t402*t403*var4[58] + 20.*t1259*t349*t363*var4[78] + 80.*t326*t349*t375*var4[78] - 60.*t363*t367*t375*var4[78] - 60.*t1259*t367*t375*t391*var4[78] - 90.*t363*t367*t397*var4[78] + 60.*t347*t391*t397*var4[78] - 20.*t326*t349*var4[98] - 20.*t1259*t349*t363*var4[98] - 80.*t326*t349*t375*var4[98] + 60.*t363*t367*t375*var4[98] + 25.*t477*t485*var4[98] + 20.*t326*t349*var4[118] - 25.*t477*t485*var4[118]; p_output1[209]=-20.*t312*t402*t403*var4[19] - 60.*t312*t347*t391*t397*var4[39] + 40.*t312*t402*t403*var4[39] - 60.*t312*t363*t367*t375*var4[59] + 120.*t312*t347*t391*t397*var4[59] - 20.*t312*t402*t403*var4[59] - 20.*t312*t326*t349*var4[79] + 120.*t312*t363*t367*t375*var4[79] - 60.*t312*t347*t391*t397*var4[79] + 40.*t312*t326*t349*var4[99] - 60.*t312*t363*t367*t375*var4[99] - 20.*t312*t326*t349*var4[119]; p_output1[210]=-20.*t239*t268*t402*t403*var4[19] - 60.*t239*t268*t347*t391*t397*var4[39] + 40.*t239*t268*t402*t403*var4[39] - 60.*t239*t268*t363*t367*t375*var4[59] + 120.*t239*t268*t347*t391*t397*var4[59] - 20.*t239*t268*t402*t403*var4[59] - 20.*t239*t268*t326*t349*var4[79] + 120.*t239*t268*t363*t367*t375*var4[79] - 60.*t239*t268*t347*t391*t397*var4[79] + 40.*t239*t268*t326*t349*var4[99] - 60.*t239*t268*t363*t367*t375*var4[99] - 20.*t239*t268*t326*t349*var4[119]; p_output1[211]=1.; p_output1[212]=t457; p_output1[213]=t464; p_output1[214]=t469; p_output1[215]=t472; p_output1[216]=t482; p_output1[217]=t484; p_output1[218]=20.*t347*t391*t403*var4[19] - 5.*t402*t454*var4[19] + 60.*t363*t367*t397*var4[39] - 60.*t347*t391*t403*var4[39] + 5.*t402*t454*var4[39] + 60.*t326*t349*t375*var4[59] - 150.*t363*t367*t397*var4[59] + 40.*t347*t391*t403*var4[59] - 140.*t326*t349*t375*var4[79] + 90.*t363*t367*t397*var4[79] + 20.*t477*t485*var4[79] + 80.*t326*t349*t375*var4[99] - 45.*t477*t485*var4[99] + 25.*t477*t485*var4[119]; p_output1[219]=20.*t1259*t369*t403*var4[19] + 5.*t402*t454*var4[19] + 60.*t1259*t347*t397*t402*var4[39] - 20.*t1259*t369*t403*var4[39] + 40.*t347*t391*t403*var4[39] - 20.*t402*t403*var4[39] - 5.*t402*t454*var4[39] + 60.*t1259*t367*t375*t391*var4[59] + 90.*t363*t367*t397*var4[59] - 60.*t347*t391*t397*var4[59] - 60.*t1259*t347*t397*t402*var4[59] - 40.*t347*t391*t403*var4[59] + 20.*t402*t403*var4[59] + 20.*t1259*t349*t363*var4[79] + 80.*t326*t349*t375*var4[79] - 60.*t363*t367*t375*var4[79] - 60.*t1259*t367*t375*t391*var4[79] - 90.*t363*t367*t397*var4[79] + 60.*t347*t391*t397*var4[79] - 20.*t326*t349*var4[99] - 20.*t1259*t349*t363*var4[99] - 80.*t326*t349*t375*var4[99] + 60.*t363*t367*t375*var4[99] + 25.*t477*t485*var4[99] + 20.*t326*t349*var4[119] - 25.*t477*t485*var4[119]; } #ifdef MATLAB_MEX_FILE #include "mex.h" /* * Main function */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { size_t mrows, ncols; double *var1,*var2,*var3,*var4,*var5,*var6,*var7; double *p_output1; /* Check for proper number of arguments. */ if( nrhs != 7) { mexErrMsgIdAndTxt("MATLAB:MShaped:invalidNumInputs", "Seven input(s) required (var1,var2,var3,var4,var5,var6,var7)."); } else if( nlhs > 1) { mexErrMsgIdAndTxt("MATLAB:MShaped:maxlhs", "Too many output arguments."); } /* The input must be a noncomplex double vector or scaler. */ mrows = mxGetM(prhs[0]); ncols = mxGetN(prhs[0]); if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || ( !(mrows == 2 && ncols == 1) && !(mrows == 1 && ncols == 2))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var1 is wrong."); } mrows = mxGetM(prhs[1]); ncols = mxGetN(prhs[1]); if( !mxIsDouble(prhs[1]) || mxIsComplex(prhs[1]) || ( !(mrows == 36 && ncols == 1) && !(mrows == 1 && ncols == 36))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var2 is wrong."); } mrows = mxGetM(prhs[2]); ncols = mxGetN(prhs[2]); if( !mxIsDouble(prhs[2]) || mxIsComplex(prhs[2]) || ( !(mrows == 36 && ncols == 1) && !(mrows == 1 && ncols == 36))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var3 is wrong."); } mrows = mxGetM(prhs[3]); ncols = mxGetN(prhs[3]); if( !mxIsDouble(prhs[3]) || mxIsComplex(prhs[3]) || ( !(mrows == 120 && ncols == 1) && !(mrows == 1 && ncols == 120))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var4 is wrong."); } mrows = mxGetM(prhs[4]); ncols = mxGetN(prhs[4]); if( !mxIsDouble(prhs[4]) || mxIsComplex(prhs[4]) || ( !(mrows == 2 && ncols == 1) && !(mrows == 1 && ncols == 2))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var5 is wrong."); } mrows = mxGetM(prhs[5]); ncols = mxGetN(prhs[5]); if( !mxIsDouble(prhs[5]) || mxIsComplex(prhs[5]) || ( !(mrows == 1 && ncols == 1) && !(mrows == 1 && ncols == 1))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var6 is wrong."); } mrows = mxGetM(prhs[6]); ncols = mxGetN(prhs[6]); if( !mxIsDouble(prhs[6]) || mxIsComplex(prhs[6]) || ( !(mrows == 1 && ncols == 1) && !(mrows == 1 && ncols == 1))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var7 is wrong."); } /* Assign pointers to each input. */ var1 = mxGetPr(prhs[0]); var2 = mxGetPr(prhs[1]); var3 = mxGetPr(prhs[2]); var4 = mxGetPr(prhs[3]); var5 = mxGetPr(prhs[4]); var6 = mxGetPr(prhs[5]); var7 = mxGetPr(prhs[6]); /* Create matrices for return arguments. */ plhs[0] = mxCreateDoubleMatrix((mwSize) 220, (mwSize) 1, mxREAL); p_output1 = mxGetPr(plhs[0]); /* Call the calculation subroutine. */ output1(p_output1,var1,var2,var3,var4,var5,var6,var7); } #else // MATLAB_MEX_FILE #include "J_d1y_time_RightStance.hh" namespace RightStance { void J_d1y_time_RightStance_raw(double *p_output1, const double *var1,const double *var2,const double *var3,const double *var4,const double *var5,const double *var6,const double *var7) { // Call Subroutines output1(p_output1, var1, var2, var3, var4, var5, var6, var7); } } #endif // MATLAB_MEX_FILE
106.845511
783
0.668341
prem-chand
a391a1cc6233aeae94567c880af2bcdf7b321a4d
4,346
cpp
C++
CLR/Libraries/CorLib/corlib_native_System_Text_UTF8Encoding.cpp
valoni/STM32F103
75f0cb8be593ca287a08f5992d1f5d3c3bb12bfc
[ "Apache-2.0" ]
1
2020-06-09T02:16:43.000Z
2020-06-09T02:16:43.000Z
CLR/Libraries/CorLib/corlib_native_System_Text_UTF8Encoding.cpp
valoni/STM32F103
75f0cb8be593ca287a08f5992d1f5d3c3bb12bfc
[ "Apache-2.0" ]
null
null
null
CLR/Libraries/CorLib/corlib_native_System_Text_UTF8Encoding.cpp
valoni/STM32F103
75f0cb8be593ca287a08f5992d1f5d3c3bb12bfc
[ "Apache-2.0" ]
1
2019-12-03T05:37:43.000Z
2019-12-03T05:37:43.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "CorLib.h" HRESULT Library_corlib_native_System_Text_UTF8Encoding::GetBytes___SZARRAY_U1__STRING( CLR_RT_StackFrame& stack ) { NATIVE_PROFILE_CLR_CORE(); TINYCLR_HEADER(); size_t cBytes; CLR_RT_HeapBlock_Array* arr; LPCSTR str; CLR_RT_HeapBlock& ret = stack.PushValueAndClear(); str = stack.Arg1().RecoverString(); FAULT_ON_NULL(str); cBytes = hal_strlen_s(str); TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Array::CreateInstance( ret, (CLR_UINT32)cBytes, g_CLR_RT_WellKnownTypes.m_UInt8 )); arr = ret.DereferenceArray(); memcpy( arr->GetFirstElement(), str, cBytes ); TINYCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_Text_UTF8Encoding::GetBytes___I4__STRING__I4__I4__SZARRAY_U1__I4( CLR_RT_StackFrame& stack ) { NATIVE_PROFILE_CLR_CORE(); TINYCLR_HEADER(); size_t cMaxBytes; LPCSTR str = stack.Arg1().RecoverString(); CLR_INT32 strIdx = stack.Arg2().NumericByRef().s4; CLR_INT32 strCnt = stack.Arg3().NumericByRef().s4; CLR_RT_HeapBlock_Array* pArrayBytes = stack.Arg4().DereferenceArray(); CLR_INT32 byteIdx = stack.Arg5().NumericByRef().s4; FAULT_ON_NULL(str); FAULT_ON_NULL(pArrayBytes); cMaxBytes = hal_strlen_s(str); if((strIdx + strCnt) > (CLR_INT32)cMaxBytes ) TINYCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE); if((byteIdx + strCnt) > (CLR_INT32)pArrayBytes->m_numOfElements) TINYCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE); memcpy(pArrayBytes->GetElement(byteIdx), &str[strIdx], strCnt); stack.SetResult_I4(strCnt); TINYCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_Text_UTF8Encoding::Helper__GetChars(CLR_RT_StackFrame& stack, bool fIndexed) { NATIVE_PROFILE_CLR_CORE(); TINYCLR_HEADER(); LPSTR szText; CLR_RT_HeapBlock ref; ref.SetObjectReference( NULL ); CLR_RT_ProtectFromGC gc( ref ); CLR_RT_HeapBlock_Array* pArrayBytes = stack.Arg1().DereferenceArray(); CLR_INT32 byteIdx = fIndexed ? stack.Arg2().NumericByRef().s4 : 0; CLR_INT32 byteCnt = fIndexed ? stack.Arg3().NumericByRef().s4 : pArrayBytes->m_numOfElements; CLR_RT_HeapBlock_Array* pArrayBytesCopy; CLR_RT_HeapBlock_Array* arrTmp; int cBytesCopy; FAULT_ON_NULL(pArrayBytes); _ASSERTE(pArrayBytes->m_typeOfElement == DATATYPE_U1); if((byteIdx + byteCnt) > (CLR_INT32)pArrayBytes->m_numOfElements) TINYCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE); cBytesCopy = byteCnt+1; /* Copy the array to a temporary buffer to create a zero-terminated string */ TINYCLR_CHECK_HRESULT( CLR_RT_HeapBlock_Array::CreateInstance( ref, cBytesCopy, g_CLR_RT_WellKnownTypes.m_UInt8 )); pArrayBytesCopy = ref.DereferenceArray(); szText = (LPSTR)pArrayBytesCopy->GetFirstElement(); hal_strncpy_s( szText, cBytesCopy, (LPSTR)pArrayBytes->GetElement(byteIdx), byteCnt ); TINYCLR_CHECK_HRESULT(Library_corlib_native_System_String::ConvertToCharArray( szText, stack.PushValueAndClear(), arrTmp, 0, -1 )); TINYCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_Text_UTF8Encoding::GetChars___SZARRAY_CHAR__SZARRAY_U1( CLR_RT_StackFrame& stack ) { NATIVE_PROFILE_CLR_CORE(); TINYCLR_HEADER(); TINYCLR_CHECK_HRESULT(Helper__GetChars( stack, false )); TINYCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_Text_UTF8Encoding::GetChars___SZARRAY_CHAR__SZARRAY_U1__I4__I4( CLR_RT_StackFrame& stack ) { NATIVE_PROFILE_CLR_CORE(); TINYCLR_HEADER(); TINYCLR_CHECK_HRESULT(Helper__GetChars( stack, true )); TINYCLR_NOCLEANUP(); }
37.791304
201
0.628394
valoni
a3932c968b99d72b94324deb598927f322d51ef3
10,574
cpp
C++
plugin/normalizePlugin/normalizePlugin.cpp
kvzhao/TensorRT-5.1.5
e47c3ca3247c8e63f0a236d547fc7b1327494e57
[ "Apache-2.0" ]
1
2019-09-09T01:59:51.000Z
2019-09-09T01:59:51.000Z
plugin/normalizePlugin/normalizePlugin.cpp
kvzhao/TensorRT-5.1.5
e47c3ca3247c8e63f0a236d547fc7b1327494e57
[ "Apache-2.0" ]
1
2019-08-12T06:46:14.000Z
2019-08-12T06:46:14.000Z
plugin/normalizePlugin/normalizePlugin.cpp
kvzhao/TensorRT-5.1.5
e47c3ca3247c8e63f0a236d547fc7b1327494e57
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2019, NVIDIA CORPORATION. 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. */ #include "normalizePlugin.h" #include <cstring> #include <cublas_v2.h> #include <cudnn.h> #include <iostream> #include <sstream> using namespace nvinfer1; using nvinfer1::plugin::Normalize; using nvinfer1::plugin::NormalizePluginCreator; namespace { const char* NORMALIZE_PLUGIN_VERSION{"1"}; const char* NORMALIZE_PLUGIN_NAME{"Normalize_TRT"}; } // namespace PluginFieldCollection NormalizePluginCreator::mFC{}; std::vector<PluginField> NormalizePluginCreator::mPluginAttributes; Normalize::Normalize(const Weights* weights, int nbWeights, bool acrossSpatial, bool channelShared, float eps) : acrossSpatial(acrossSpatial) , channelShared(channelShared) , eps(eps) { mNbWeights = nbWeights; ASSERT(nbWeights == 1); ASSERT(weights[0].count >= 1); mWeights = copyToDevice(weights[0].values, weights[0].count); cublasCreate(&mCublas); } Normalize::Normalize( const Weights* weights, int nbWeights, bool acrossSpatial, bool channelShared, float eps, int C, int H, int W) : acrossSpatial(acrossSpatial) , channelShared(channelShared) , eps(eps) , C(C) , H(H) , W(W) { mNbWeights = nbWeights; ASSERT(nbWeights == 1); ASSERT(weights[0].count >= 1); mWeights = copyToDevice(weights[0].values, weights[0].count); cublasCreate(&mCublas); } Normalize::Normalize(const void* buffer, size_t length) { const char *d = reinterpret_cast<const char*>(buffer), *a = d; C = read<int>(d); H = read<int>(d); W = read<int>(d); acrossSpatial = read<bool>(d); channelShared = read<bool>(d); eps = read<float>(d); int nbWeights = read<int>(d); mWeights = deserializeToDevice(d, nbWeights); ASSERT(d == a + length); } int Normalize::getNbOutputs() const { // Plugin layer has 1 output return 1; } Dims Normalize::getOutputDimensions(int index, const Dims* inputs, int nbInputDims) { ASSERT(nbInputDims == 1); ASSERT(index == 0); ASSERT(inputs[0].nbDims == 3); return DimsCHW(inputs[0].d[0], inputs[0].d[1], inputs[0].d[2]); } int Normalize::initialize() { return 0; } void Normalize::terminate() { CUBLASASSERT(cublasDestroy(mCublas)); } size_t Normalize::getWorkspaceSize(int maxBatchSize) const { return normalizePluginWorkspaceSize(acrossSpatial, C, H, W); } int Normalize::enqueue(int batchSize, const void* const* inputs, void** outputs, void* workspace, cudaStream_t stream) { const void* inputData = inputs[0]; void* outputData = outputs[0]; pluginStatus_t status = normalizeInference(stream, mCublas, acrossSpatial, channelShared, batchSize, C, H, W, eps, reinterpret_cast<const float*>(mWeights.values), inputData, outputData, workspace); ASSERT(status == STATUS_SUCCESS); return 0; } size_t Normalize::getSerializationSize() const { // C,H,W, acrossSpatial,channelShared, eps, mWeights.count,mWeights.values return sizeof(int) * 3 + sizeof(bool) * 2 + sizeof(float) + sizeof(int) + mWeights.count * sizeof(float); } void Normalize::serialize(void* buffer) const { char *d = reinterpret_cast<char*>(buffer), *a = d; write(d, C); write(d, H); write(d, W); write(d, acrossSpatial); write(d, channelShared); write(d, eps); write(d, (int) mWeights.count); serializeFromDevice(d, mWeights); ASSERT(d == a + getSerializationSize()); } bool Normalize::supportsFormat(DataType type, PluginFormat format) const { return (type == DataType::kFLOAT && format == PluginFormat::kNCHW); } Weights Normalize::copyToDevice(const void* hostData, size_t count) { void* deviceData; CUASSERT(cudaMalloc(&deviceData, count * sizeof(float))); CUASSERT(cudaMemcpy(deviceData, hostData, count * sizeof(float), cudaMemcpyHostToDevice)); return Weights{DataType::kFLOAT, deviceData, int64_t(count)}; } void Normalize::serializeFromDevice(char*& hostBuffer, Weights deviceWeights) const { CUASSERT(cudaMemcpy(hostBuffer, deviceWeights.values, deviceWeights.count * sizeof(float), cudaMemcpyDeviceToHost)); hostBuffer += deviceWeights.count * sizeof(float); } Weights Normalize::deserializeToDevice(const char*& hostBuffer, size_t count) { Weights w = copyToDevice(hostBuffer, count); hostBuffer += count * sizeof(float); return w; } // Set plugin namespace void Normalize::setPluginNamespace(const char* pluginNamespace) { mPluginNamespace = pluginNamespace; } const char* Normalize::getPluginNamespace() const { return mPluginNamespace; } // Return the DataType of the plugin output at the requested index DataType Normalize::getOutputDataType(int index, const nvinfer1::DataType* inputTypes, int nbInputs) const { ASSERT(index == 0); return DataType::kFLOAT; } // Return true if output tensor is broadcast across a batch. bool Normalize::isOutputBroadcastAcrossBatch(int outputIndex, const bool* inputIsBroadcasted, int nbInputs) const { return false; } // Return true if plugin can use input that is broadcast across batch without replication. bool Normalize::canBroadcastInputAcrossBatch(int inputIndex) const { return false; } // Configure the layer with input and output data types. void Normalize::configurePlugin(const Dims* inputDims, int nbInputs, const Dims* outputDims, int nbOutputs, const DataType* inputTypes, const DataType* outputTypes, const bool* inputIsBroadcast, const bool* outputIsBroadcast, PluginFormat floatFormat, int maxBatchSize) { ASSERT(*inputTypes == DataType::kFLOAT && floatFormat == PluginFormat::kNCHW); C = inputDims[0].d[0]; H = inputDims[0].d[1]; W = inputDims[0].d[2]; if (channelShared) { ASSERT(mWeights.count == 1); } else { ASSERT(mWeights.count == C); } ASSERT(nbInputs == 1); ASSERT(nbOutputs == 1); ASSERT(inputDims[0].nbDims >= 1); // number of dimensions of the input tensor must be >=2 ASSERT(inputDims[0].d[0] == outputDims[0].d[0] && inputDims[0].d[1] == outputDims[0].d[1] && inputDims[0].d[2] == outputDims[0].d[2]); } // Attach the plugin object to an execution context and grant the plugin the access to some context resource. void Normalize::attachToContext(cudnnContext* cudnnContext, cublasContext* cublasContext, IGpuAllocator* gpuAllocator) { } // Detach the plugin object from its execution context. void Normalize::detachFromContext() {} const char* Normalize::getPluginType() const { return NORMALIZE_PLUGIN_NAME; } const char* Normalize::getPluginVersion() const { return NORMALIZE_PLUGIN_VERSION; } void Normalize::destroy() { delete this; } // Clone the plugin IPluginV2Ext* Normalize::clone() const { // Create a new instance IPluginV2Ext* plugin = new Normalize(&mWeights, mNbWeights, acrossSpatial, channelShared, eps); // Set the namespace plugin->setPluginNamespace(mPluginNamespace); return plugin; } NormalizePluginCreator::NormalizePluginCreator() { mPluginAttributes.emplace_back(PluginField("weights", nullptr, PluginFieldType::kFLOAT32, 1)); mPluginAttributes.emplace_back(PluginField("acrossSpatial", nullptr, PluginFieldType::kINT32, 1)); mPluginAttributes.emplace_back(PluginField("channelShared", nullptr, PluginFieldType::kINT32, 1)); mPluginAttributes.emplace_back(PluginField("nbWeights", nullptr, PluginFieldType::kINT32, 1)); mPluginAttributes.emplace_back(PluginField("eps", nullptr, PluginFieldType::kFLOAT32, 1)); mFC.nbFields = mPluginAttributes.size(); mFC.fields = mPluginAttributes.data(); } const char* NormalizePluginCreator::getPluginName() const { return NORMALIZE_PLUGIN_NAME; } const char* NormalizePluginCreator::getPluginVersion() const { return NORMALIZE_PLUGIN_VERSION; } const PluginFieldCollection* NormalizePluginCreator::getFieldNames() { return &mFC; } IPluginV2Ext* NormalizePluginCreator::createPlugin(const char* name, const PluginFieldCollection* fc) { std::vector<float> weightValues; const PluginField* fields = fc->fields; for (int i = 0; i < fc->nbFields; ++i) { const char* attrName = fields[i].name; if (!strcmp(attrName, "nbWeights")) { ASSERT(fields[i].type == PluginFieldType::kINT32); mNbWeights = *(static_cast<const int*>(fields[i].data)); } else if (!strcmp(attrName, "acrossSpatial")) { ASSERT(fields[i].type == PluginFieldType::kINT32); mAcrossSpatial = *(static_cast<const bool*>(fields[i].data)); } else if (!strcmp(attrName, "channelShared")) { ASSERT(fields[i].type == PluginFieldType::kINT32); mChannelShared = *(static_cast<const bool*>(fields[i].data)); } else if (!strcmp(attrName, "eps")) { ASSERT(fields[i].type == PluginFieldType::kFLOAT32); mEps = *(static_cast<const float*>(fields[i].data)); } else if (!strcmp(attrName, "weights")) { ASSERT(fields[i].type == PluginFieldType::kFLOAT32); int size = fields[i].length; weightValues.reserve(size); const auto* w = static_cast<const float*>(fields[i].data); for (int j = 0; j < size; j++) { weightValues.push_back(*w); w++; } } } Weights weights{DataType::kFLOAT, weightValues.data(), (int64_t) weightValues.size()}; Normalize* obj = new Normalize(&weights, mNbWeights, mAcrossSpatial, mChannelShared, mEps); obj->setPluginNamespace(mNamespace.c_str()); return obj; } IPluginV2Ext* NormalizePluginCreator::deserializePlugin(const char* name, const void* serialData, size_t serialLength) { // This object will be deleted when the network is destroyed, which will // call Normalize::destroy() Normalize* obj = new Normalize(serialData, serialLength); obj->setPluginNamespace(mNamespace.c_str()); return obj; }
31.470238
120
0.693021
kvzhao
a3994edea939d2ced79f5ffa2190ea7cbc6e0933
6,105
cpp
C++
rocsolver/library/src/auxiliary/rocauxiliary_larft.cpp
eidenyoshida/rocSOLVER
1240759207b63f8aeba51db259873141c72f9735
[ "BSD-2-Clause" ]
null
null
null
rocsolver/library/src/auxiliary/rocauxiliary_larft.cpp
eidenyoshida/rocSOLVER
1240759207b63f8aeba51db259873141c72f9735
[ "BSD-2-Clause" ]
null
null
null
rocsolver/library/src/auxiliary/rocauxiliary_larft.cpp
eidenyoshida/rocSOLVER
1240759207b63f8aeba51db259873141c72f9735
[ "BSD-2-Clause" ]
null
null
null
/* ************************************************************************ * Copyright 2019-2020 Advanced Micro Devices, Inc. * ************************************************************************ */ #include "rocauxiliary_larft.hpp" template <typename T> rocblas_status rocsolver_larft_impl(rocblas_handle handle, const rocblas_direct direct, const rocblas_storev storev, const rocblas_int n, const rocblas_int k, T* V, const rocblas_int ldv, T* tau, T* F, const rocblas_int ldf) { if(!handle) return rocblas_status_invalid_handle; //logging is missing ??? // argument checking rocblas_status st = rocsolver_larft_argCheck(direct,storev,n,k,ldv,ldf,V,tau,F); if (st != rocblas_status_continue) return st; rocblas_stride stridev = 0; rocblas_stride stridet = 0; rocblas_stride stridef = 0; rocblas_int batch_count=1; // memory managment size_t size_1; //size of constants size_t size_2; //size of workspace size_t size_3; //size of array of pointers to workspace rocsolver_larft_getMemorySize<T,false>(k,batch_count,&size_1,&size_2,&size_3); // (TODO) MEMORY SIZE QUERIES AND ALLOCATIONS TO BE DONE WITH ROCBLAS HANDLE void *scalars, *work, *workArr; hipMalloc(&scalars,size_1); hipMalloc(&work,size_2); hipMalloc(&workArr,size_3); if (!scalars || (size_2 && !work) || (size_3 && !workArr)) return rocblas_status_memory_error; // scalar constants for rocblas functions calls // (to standarize and enable re-use, size_1 always equals 3*sizeof(T)) T sca[] = { -1, 0, 1 }; RETURN_IF_HIP_ERROR(hipMemcpy(scalars, sca, size_1, hipMemcpyHostToDevice)); // execution rocblas_status status = rocsolver_larft_template<T>(handle,direct,storev, n,k, V,0, //shifted 0 entries ldv, stridev, tau, stridet, F, ldf, stridef, batch_count, (T*)scalars, (T*)work, (T**)workArr); hipFree(scalars); hipFree(work); hipFree(workArr); return status; } /* * =========================================================================== * C wrapper * =========================================================================== */ extern "C" { ROCSOLVER_EXPORT rocblas_status rocsolver_slarft(rocblas_handle handle, const rocblas_direct direct, const rocblas_storev storev, const rocblas_int n, const rocblas_int k, float *V, const rocblas_int ldv, float *tau, float *T, const rocblas_int ldt) { return rocsolver_larft_impl<float>(handle, direct, storev, n, k, V, ldv, tau, T, ldt); } ROCSOLVER_EXPORT rocblas_status rocsolver_dlarft(rocblas_handle handle, const rocblas_direct direct, const rocblas_storev storev, const rocblas_int n, const rocblas_int k, double *V, const rocblas_int ldv, double *tau, double *T, const rocblas_int ldt) { return rocsolver_larft_impl<double>(handle, direct, storev, n, k, V, ldv, tau, T, ldt); } ROCSOLVER_EXPORT rocblas_status rocsolver_clarft(rocblas_handle handle, const rocblas_direct direct, const rocblas_storev storev, const rocblas_int n, const rocblas_int k, rocblas_float_complex *V, const rocblas_int ldv, rocblas_float_complex *tau, rocblas_float_complex *T, const rocblas_int ldt) { return rocsolver_larft_impl<rocblas_float_complex>(handle, direct, storev, n, k, V, ldv, tau, T, ldt); } ROCSOLVER_EXPORT rocblas_status rocsolver_zlarft(rocblas_handle handle, const rocblas_direct direct, const rocblas_storev storev, const rocblas_int n, const rocblas_int k, rocblas_double_complex *V, const rocblas_int ldv, rocblas_double_complex *tau, rocblas_double_complex *T, const rocblas_int ldt) { return rocsolver_larft_impl<rocblas_double_complex>(handle, direct, storev, n, k, V, ldv, tau, T, ldt); } } //extern C
44.562044
107
0.413923
eidenyoshida
a39971d571f4881019f41309634ee65cd09a7a1f
4,050
cpp
C++
src/DEX/EnumToString.cpp
ahawad/LIEF
88931ea405d9824faa5749731427533e0c27173e
[ "Apache-2.0" ]
null
null
null
src/DEX/EnumToString.cpp
ahawad/LIEF
88931ea405d9824faa5749731427533e0c27173e
[ "Apache-2.0" ]
null
null
null
src/DEX/EnumToString.cpp
ahawad/LIEF
88931ea405d9824faa5749731427533e0c27173e
[ "Apache-2.0" ]
null
null
null
/* Copyright 2017 - 2022 R. Thomas * Copyright 2017 - 2022 Quarkslab * * 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. */ #include "LIEF/DEX/EnumToString.hpp" #include <map> #include "frozen.hpp" namespace LIEF { namespace DEX { const char* to_string(MapItem::TYPES e) { CONST_MAP(MapItem::TYPES, const char*, 20) enumStrings{ {MapItem::TYPES::HEADER, "HEADER"}, {MapItem::TYPES::STRING_ID, "STRING_ID"}, {MapItem::TYPES::TYPE_ID, "TYPE_ID"}, {MapItem::TYPES::PROTO_ID, "PROTO_ID"}, {MapItem::TYPES::FIELD_ID, "FIELD_ID"}, {MapItem::TYPES::METHOD_ID, "METHOD_ID"}, {MapItem::TYPES::CLASS_DEF, "CLASS_DEF"}, {MapItem::TYPES::CALL_SITE_ID, "CALL_SITE_ID"}, {MapItem::TYPES::METHOD_HANDLE, "METHOD_HANDLE"}, {MapItem::TYPES::MAP_LIST, "MAP_LIST"}, {MapItem::TYPES::TYPE_LIST, "TYPE_LIST"}, {MapItem::TYPES::ANNOTATION_SET_REF_LIST, "ANNOTATION_SET_REF_LIST"}, {MapItem::TYPES::ANNOTATION_SET, "ANNOTATION_SET"}, {MapItem::TYPES::CLASS_DATA, "CLASS_DATA"}, {MapItem::TYPES::CODE, "CODE"}, {MapItem::TYPES::STRING_DATA, "STRING_DATA"}, {MapItem::TYPES::DEBUG_INFO, "DEBUG_INFO"}, {MapItem::TYPES::ANNOTATION, "ANNOTATION"}, {MapItem::TYPES::ENCODED_ARRAY, "ENCODED_ARRAY"}, {MapItem::TYPES::ANNOTATIONS_DIRECTORY, "ANNOTATIONS_DIRECTORY"}, }; const auto it = enumStrings.find(e); return it == enumStrings.end() ? "UNKNOWN" : it->second; } const char* to_string(ACCESS_FLAGS e) { CONST_MAP(ACCESS_FLAGS, const char*, 18) enumStrings{ {ACCESS_FLAGS::ACC_UNKNOWN, "UNKNOWN"}, {ACCESS_FLAGS::ACC_PUBLIC, "PUBLIC"}, {ACCESS_FLAGS::ACC_PRIVATE, "PRIVATE"}, {ACCESS_FLAGS::ACC_PROTECTED, "PROTECTED"}, {ACCESS_FLAGS::ACC_STATIC, "STATIC"}, {ACCESS_FLAGS::ACC_FINAL, "FINAL"}, {ACCESS_FLAGS::ACC_SYNCHRONIZED, "SYNCHRONIZED"}, {ACCESS_FLAGS::ACC_VOLATILE, "VOLATILE"}, {ACCESS_FLAGS::ACC_VARARGS, "VARARGS"}, {ACCESS_FLAGS::ACC_NATIVE, "NATIVE"}, {ACCESS_FLAGS::ACC_INTERFACE, "INTERFACE"}, {ACCESS_FLAGS::ACC_ABSTRACT, "ABSTRACT"}, {ACCESS_FLAGS::ACC_STRICT, "STRICT"}, {ACCESS_FLAGS::ACC_SYNTHETIC, "SYNTHETIC"}, {ACCESS_FLAGS::ACC_ANNOTATION, "ANNOTATION"}, {ACCESS_FLAGS::ACC_ENUM, "ENUM"}, {ACCESS_FLAGS::ACC_CONSTRUCTOR, "CONSTRUCTOR"}, {ACCESS_FLAGS::ACC_DECLARED_SYNCHRONIZED, "DECLARED_SYNCHRONIZED"}, }; const auto it = enumStrings.find(e); return it == enumStrings.end() ? "UNKNOWN" : it->second; } const char* to_string(Type::TYPES e) { CONST_MAP(Type::TYPES, const char*, 4) enumStrings{ {Type::TYPES::UNKNOWN, "UNKNOWN"}, {Type::TYPES::ARRAY, "ARRAY"}, {Type::TYPES::CLASS, "CLASS"}, {Type::TYPES::PRIMITIVE, "PRIMITIVE"}, }; const auto it = enumStrings.find(e); return it == enumStrings.end() ? "UNKNOWN" : it->second; } const char* to_string(Type::PRIMITIVES e) { CONST_MAP(Type::PRIMITIVES, const char*, 9) enumStrings{ {Type::PRIMITIVES::VOID_T, "VOID_T"}, {Type::PRIMITIVES::BOOLEAN, "BOOLEAN"}, {Type::PRIMITIVES::INT, "INT"}, {Type::PRIMITIVES::SHORT, "SHORT"}, {Type::PRIMITIVES::LONG, "LONG"}, {Type::PRIMITIVES::CHAR, "CHAR"}, {Type::PRIMITIVES::DOUBLE, "DOUBLE"}, {Type::PRIMITIVES::FLOAT, "FLOAT"}, {Type::PRIMITIVES::BYTE, "BYTE"}, }; const auto it = enumStrings.find(e); return it == enumStrings.end() ? "UNKNOWN" : it->second; } } // namespace DEX } // namespace LIEF
36.818182
75
0.661481
ahawad
a399fbdc7932b13a516b2268e4a76fe52b997c49
177,609
cpp
C++
src/alglib/alglibmisc.cpp
dc1394/Gauss_Legendre
70c179a27e20ae8cf109035031a5c84ba12a7fc9
[ "BSD-2-Clause" ]
null
null
null
src/alglib/alglibmisc.cpp
dc1394/Gauss_Legendre
70c179a27e20ae8cf109035031a5c84ba12a7fc9
[ "BSD-2-Clause" ]
null
null
null
src/alglib/alglibmisc.cpp
dc1394/Gauss_Legendre
70c179a27e20ae8cf109035031a5c84ba12a7fc9
[ "BSD-2-Clause" ]
null
null
null
/************************************************************************* ALGLIB 3.9.0 (source code generated 2014-12-11) Copyright (c) Sergey Bochkanov (ALGLIB project). >>> SOURCE LICENSE >>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation (www.fsf.org); either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses >>> END OF LICENSE >>> *************************************************************************/ #include "stdafx.h" #include "alglibmisc.h" // disable some irrelevant warnings #if (AE_COMPILER==AE_MSVC) #pragma warning(disable:4100) #pragma warning(disable:4127) #pragma warning(disable:4702) #pragma warning(disable:4996) #endif using namespace std; ///////////////////////////////////////////////////////////////////////// // // THIS SECTION CONTAINS IMPLEMENTATION OF C++ INTERFACE // ///////////////////////////////////////////////////////////////////////// namespace alglib { /************************************************************************* Portable high quality random number generator state. Initialized with HQRNDRandomize() or HQRNDSeed(). Fields: S1, S2 - seed values V - precomputed value MagicV - 'magic' value used to determine whether State structure was correctly initialized. *************************************************************************/ _hqrndstate_owner::_hqrndstate_owner() { p_struct = (alglib_impl::hqrndstate*)alglib_impl::ae_malloc(sizeof(alglib_impl::hqrndstate), NULL); if( p_struct==NULL ) throw ap_error("ALGLIB: malloc error"); alglib_impl::_hqrndstate_init(p_struct, NULL); } _hqrndstate_owner::_hqrndstate_owner(const _hqrndstate_owner &rhs) { p_struct = (alglib_impl::hqrndstate*)alglib_impl::ae_malloc(sizeof(alglib_impl::hqrndstate), NULL); if( p_struct==NULL ) throw ap_error("ALGLIB: malloc error"); alglib_impl::_hqrndstate_init_copy(p_struct, const_cast<alglib_impl::hqrndstate*>(rhs.p_struct), NULL); } _hqrndstate_owner& _hqrndstate_owner::operator=(const _hqrndstate_owner &rhs) { if( this==&rhs ) return *this; alglib_impl::_hqrndstate_clear(p_struct); alglib_impl::_hqrndstate_init_copy(p_struct, const_cast<alglib_impl::hqrndstate*>(rhs.p_struct), NULL); return *this; } _hqrndstate_owner::~_hqrndstate_owner() { alglib_impl::_hqrndstate_clear(p_struct); ae_free(p_struct); } alglib_impl::hqrndstate* _hqrndstate_owner::c_ptr() { return p_struct; } alglib_impl::hqrndstate* _hqrndstate_owner::c_ptr() const { return const_cast<alglib_impl::hqrndstate*>(p_struct); } hqrndstate::hqrndstate() : _hqrndstate_owner() { } hqrndstate::hqrndstate(const hqrndstate &rhs):_hqrndstate_owner(rhs) { } hqrndstate& hqrndstate::operator=(const hqrndstate &rhs) { if( this==&rhs ) return *this; _hqrndstate_owner::operator=(rhs); return *this; } hqrndstate::~hqrndstate() { } /************************************************************************* HQRNDState initialization with random values which come from standard RNG. -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndrandomize(hqrndstate &state) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::hqrndrandomize(const_cast<alglib_impl::hqrndstate*>(state.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* HQRNDState initialization with seed values -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndseed(const ae_int_t s1, const ae_int_t s2, hqrndstate &state) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::hqrndseed(s1, s2, const_cast<alglib_impl::hqrndstate*>(state.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This function generates random real number in (0,1), not including interval boundaries State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ double hqrnduniformr(const hqrndstate &state) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { double result = alglib_impl::hqrnduniformr(const_cast<alglib_impl::hqrndstate*>(state.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<double*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This function generates random integer number in [0, N) 1. State structure must be initialized with HQRNDRandomize() or HQRNDSeed() 2. N can be any positive number except for very large numbers: * close to 2^31 on 32-bit systems * close to 2^62 on 64-bit systems An exception will be generated if N is too large. -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ ae_int_t hqrnduniformi(const hqrndstate &state, const ae_int_t n) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::hqrnduniformi(const_cast<alglib_impl::hqrndstate*>(state.c_ptr()), n, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* Random number generator: normal numbers This function generates one random number from normal distribution. Its performance is equal to that of HQRNDNormal2() State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ double hqrndnormal(const hqrndstate &state) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { double result = alglib_impl::hqrndnormal(const_cast<alglib_impl::hqrndstate*>(state.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<double*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* Random number generator: random X and Y such that X^2+Y^2=1 State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndunit2(const hqrndstate &state, double &x, double &y) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::hqrndunit2(const_cast<alglib_impl::hqrndstate*>(state.c_ptr()), &x, &y, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* Random number generator: normal numbers This function generates two independent random numbers from normal distribution. Its performance is equal to that of HQRNDNormal() State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndnormal2(const hqrndstate &state, double &x1, double &x2) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::hqrndnormal2(const_cast<alglib_impl::hqrndstate*>(state.c_ptr()), &x1, &x2, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* Random number generator: exponential distribution State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 11.08.2007 by Bochkanov Sergey *************************************************************************/ double hqrndexponential(const hqrndstate &state, const double lambdav) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { double result = alglib_impl::hqrndexponential(const_cast<alglib_impl::hqrndstate*>(state.c_ptr()), lambdav, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<double*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This function generates random number from discrete distribution given by finite sample X. INPUT PARAMETERS State - high quality random number generator, must be initialized with HQRNDRandomize() or HQRNDSeed(). X - finite sample N - number of elements to use, N>=1 RESULT this function returns one of the X[i] for random i=0..N-1 -- ALGLIB -- Copyright 08.11.2011 by Bochkanov Sergey *************************************************************************/ double hqrnddiscrete(const hqrndstate &state, const real_1d_array &x, const ae_int_t n) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { double result = alglib_impl::hqrnddiscrete(const_cast<alglib_impl::hqrndstate*>(state.c_ptr()), const_cast<alglib_impl::ae_vector*>(x.c_ptr()), n, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<double*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This function generates random number from continuous distribution given by finite sample X. INPUT PARAMETERS State - high quality random number generator, must be initialized with HQRNDRandomize() or HQRNDSeed(). X - finite sample, array[N] (can be larger, in this case only leading N elements are used). THIS ARRAY MUST BE SORTED BY ASCENDING. N - number of elements to use, N>=1 RESULT this function returns random number from continuous distribution which tries to approximate X as mush as possible. min(X)<=Result<=max(X). -- ALGLIB -- Copyright 08.11.2011 by Bochkanov Sergey *************************************************************************/ double hqrndcontinuous(const hqrndstate &state, const real_1d_array &x, const ae_int_t n) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { double result = alglib_impl::hqrndcontinuous(const_cast<alglib_impl::hqrndstate*>(state.c_ptr()), const_cast<alglib_impl::ae_vector*>(x.c_ptr()), n, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<double*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* *************************************************************************/ _kdtree_owner::_kdtree_owner() { p_struct = (alglib_impl::kdtree*)alglib_impl::ae_malloc(sizeof(alglib_impl::kdtree), NULL); if( p_struct==NULL ) throw ap_error("ALGLIB: malloc error"); alglib_impl::_kdtree_init(p_struct, NULL); } _kdtree_owner::_kdtree_owner(const _kdtree_owner &rhs) { p_struct = (alglib_impl::kdtree*)alglib_impl::ae_malloc(sizeof(alglib_impl::kdtree), NULL); if( p_struct==NULL ) throw ap_error("ALGLIB: malloc error"); alglib_impl::_kdtree_init_copy(p_struct, const_cast<alglib_impl::kdtree*>(rhs.p_struct), NULL); } _kdtree_owner& _kdtree_owner::operator=(const _kdtree_owner &rhs) { if( this==&rhs ) return *this; alglib_impl::_kdtree_clear(p_struct); alglib_impl::_kdtree_init_copy(p_struct, const_cast<alglib_impl::kdtree*>(rhs.p_struct), NULL); return *this; } _kdtree_owner::~_kdtree_owner() { alglib_impl::_kdtree_clear(p_struct); ae_free(p_struct); } alglib_impl::kdtree* _kdtree_owner::c_ptr() { return p_struct; } alglib_impl::kdtree* _kdtree_owner::c_ptr() const { return const_cast<alglib_impl::kdtree*>(p_struct); } kdtree::kdtree() : _kdtree_owner() { } kdtree::kdtree(const kdtree &rhs):_kdtree_owner(rhs) { } kdtree& kdtree::operator=(const kdtree &rhs) { if( this==&rhs ) return *this; _kdtree_owner::operator=(rhs); return *this; } kdtree::~kdtree() { } /************************************************************************* This function serializes data structure to string. Important properties of s_out: * it contains alphanumeric characters, dots, underscores, minus signs * these symbols are grouped into words, which are separated by spaces and Windows-style (CR+LF) newlines * although serializer uses spaces and CR+LF as separators, you can replace any separator character by arbitrary combination of spaces, tabs, Windows or Unix newlines. It allows flexible reformatting of the string in case you want to include it into text or XML file. But you should not insert separators into the middle of the "words" nor you should change case of letters. * s_out can be freely moved between 32-bit and 64-bit systems, little and big endian machines, and so on. You can serialize structure on 32-bit machine and unserialize it on 64-bit one (or vice versa), or serialize it on SPARC and unserialize on x86. You can also serialize it in C++ version of ALGLIB and unserialize in C# one, and vice versa. *************************************************************************/ void kdtreeserialize(kdtree &obj, std::string &s_out) { alglib_impl::ae_state state; alglib_impl::ae_serializer serializer; alglib_impl::ae_int_t ssize; alglib_impl::ae_state_init(&state); try { alglib_impl::ae_serializer_init(&serializer); alglib_impl::ae_serializer_alloc_start(&serializer); alglib_impl::kdtreealloc(&serializer, obj.c_ptr(), &state); ssize = alglib_impl::ae_serializer_get_alloc_size(&serializer); s_out.clear(); s_out.reserve((size_t)(ssize+1)); alglib_impl::ae_serializer_sstart_str(&serializer, &s_out); alglib_impl::kdtreeserialize(&serializer, obj.c_ptr(), &state); alglib_impl::ae_serializer_stop(&serializer); if( s_out.length()>(size_t)ssize ) throw ap_error("ALGLIB: serialization integrity error"); alglib_impl::ae_serializer_clear(&serializer); alglib_impl::ae_state_clear(&state); } catch(alglib_impl::ae_error_type) { throw ap_error(state.error_msg); } } /************************************************************************* This function unserializes data structure from string. *************************************************************************/ void kdtreeunserialize(std::string &s_in, kdtree &obj) { alglib_impl::ae_state state; alglib_impl::ae_serializer serializer; alglib_impl::ae_state_init(&state); try { alglib_impl::ae_serializer_init(&serializer); alglib_impl::ae_serializer_ustart_str(&serializer, &s_in); alglib_impl::kdtreeunserialize(&serializer, obj.c_ptr(), &state); alglib_impl::ae_serializer_stop(&serializer); alglib_impl::ae_serializer_clear(&serializer); alglib_impl::ae_state_clear(&state); } catch(alglib_impl::ae_error_type) { throw ap_error(state.error_msg); } } /************************************************************************* KD-tree creation This subroutine creates KD-tree from set of X-values and optional Y-values INPUT PARAMETERS XY - dataset, array[0..N-1,0..NX+NY-1]. one row corresponds to one point. first NX columns contain X-values, next NY (NY may be zero) columns may contain associated Y-values N - number of points, N>=0. NX - space dimension, NX>=1. NY - number of optional Y-values, NY>=0. NormType- norm type: * 0 denotes infinity-norm * 1 denotes 1-norm * 2 denotes 2-norm (Euclidean norm) OUTPUT PARAMETERS KDT - KD-tree NOTES 1. KD-tree creation have O(N*logN) complexity and O(N*(2*NX+NY)) memory requirements. 2. Although KD-trees may be used with any combination of N and NX, they are more efficient than brute-force search only when N >> 4^NX. So they are most useful in low-dimensional tasks (NX=2, NX=3). NX=1 is another inefficient case, because simple binary search (without additional structures) is much more efficient in such tasks than KD-trees. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreebuild(const real_2d_array &xy, const ae_int_t n, const ae_int_t nx, const ae_int_t ny, const ae_int_t normtype, kdtree &kdt) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreebuild(const_cast<alglib_impl::ae_matrix*>(xy.c_ptr()), n, nx, ny, normtype, const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* KD-tree creation This subroutine creates KD-tree from set of X-values and optional Y-values INPUT PARAMETERS XY - dataset, array[0..N-1,0..NX+NY-1]. one row corresponds to one point. first NX columns contain X-values, next NY (NY may be zero) columns may contain associated Y-values N - number of points, N>=0. NX - space dimension, NX>=1. NY - number of optional Y-values, NY>=0. NormType- norm type: * 0 denotes infinity-norm * 1 denotes 1-norm * 2 denotes 2-norm (Euclidean norm) OUTPUT PARAMETERS KDT - KD-tree NOTES 1. KD-tree creation have O(N*logN) complexity and O(N*(2*NX+NY)) memory requirements. 2. Although KD-trees may be used with any combination of N and NX, they are more efficient than brute-force search only when N >> 4^NX. So they are most useful in low-dimensional tasks (NX=2, NX=3). NX=1 is another inefficient case, because simple binary search (without additional structures) is much more efficient in such tasks than KD-trees. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreebuild(const real_2d_array &xy, const ae_int_t nx, const ae_int_t ny, const ae_int_t normtype, kdtree &kdt) { alglib_impl::ae_state _alglib_env_state; ae_int_t n; n = xy.rows(); alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreebuild(const_cast<alglib_impl::ae_matrix*>(xy.c_ptr()), n, nx, ny, normtype, const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* KD-tree creation This subroutine creates KD-tree from set of X-values, integer tags and optional Y-values INPUT PARAMETERS XY - dataset, array[0..N-1,0..NX+NY-1]. one row corresponds to one point. first NX columns contain X-values, next NY (NY may be zero) columns may contain associated Y-values Tags - tags, array[0..N-1], contains integer tags associated with points. N - number of points, N>=0 NX - space dimension, NX>=1. NY - number of optional Y-values, NY>=0. NormType- norm type: * 0 denotes infinity-norm * 1 denotes 1-norm * 2 denotes 2-norm (Euclidean norm) OUTPUT PARAMETERS KDT - KD-tree NOTES 1. KD-tree creation have O(N*logN) complexity and O(N*(2*NX+NY)) memory requirements. 2. Although KD-trees may be used with any combination of N and NX, they are more efficient than brute-force search only when N >> 4^NX. So they are most useful in low-dimensional tasks (NX=2, NX=3). NX=1 is another inefficient case, because simple binary search (without additional structures) is much more efficient in such tasks than KD-trees. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreebuildtagged(const real_2d_array &xy, const integer_1d_array &tags, const ae_int_t n, const ae_int_t nx, const ae_int_t ny, const ae_int_t normtype, kdtree &kdt) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreebuildtagged(const_cast<alglib_impl::ae_matrix*>(xy.c_ptr()), const_cast<alglib_impl::ae_vector*>(tags.c_ptr()), n, nx, ny, normtype, const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* KD-tree creation This subroutine creates KD-tree from set of X-values, integer tags and optional Y-values INPUT PARAMETERS XY - dataset, array[0..N-1,0..NX+NY-1]. one row corresponds to one point. first NX columns contain X-values, next NY (NY may be zero) columns may contain associated Y-values Tags - tags, array[0..N-1], contains integer tags associated with points. N - number of points, N>=0 NX - space dimension, NX>=1. NY - number of optional Y-values, NY>=0. NormType- norm type: * 0 denotes infinity-norm * 1 denotes 1-norm * 2 denotes 2-norm (Euclidean norm) OUTPUT PARAMETERS KDT - KD-tree NOTES 1. KD-tree creation have O(N*logN) complexity and O(N*(2*NX+NY)) memory requirements. 2. Although KD-trees may be used with any combination of N and NX, they are more efficient than brute-force search only when N >> 4^NX. So they are most useful in low-dimensional tasks (NX=2, NX=3). NX=1 is another inefficient case, because simple binary search (without additional structures) is much more efficient in such tasks than KD-trees. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreebuildtagged(const real_2d_array &xy, const integer_1d_array &tags, const ae_int_t nx, const ae_int_t ny, const ae_int_t normtype, kdtree &kdt) { alglib_impl::ae_state _alglib_env_state; ae_int_t n; if( (xy.rows()!=tags.length())) throw ap_error("Error while calling 'kdtreebuildtagged': looks like one of arguments has wrong size"); n = xy.rows(); alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreebuildtagged(const_cast<alglib_impl::ae_matrix*>(xy.c_ptr()), const_cast<alglib_impl::ae_vector*>(tags.c_ptr()), n, nx, ny, normtype, const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* K-NN query: K nearest neighbors INPUT PARAMETERS KDT - KD-tree X - point, array[0..NX-1]. K - number of neighbors to return, K>=1 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True RESULT number of actual neighbors found (either K or N, if K>N). This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain these results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() to get distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequeryknn(const kdtree &kdt, const real_1d_array &x, const ae_int_t k, const bool selfmatch) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::kdtreequeryknn(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_vector*>(x.c_ptr()), k, selfmatch, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* K-NN query: K nearest neighbors INPUT PARAMETERS KDT - KD-tree X - point, array[0..NX-1]. K - number of neighbors to return, K>=1 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True RESULT number of actual neighbors found (either K or N, if K>N). This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain these results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() to get distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequeryknn(const kdtree &kdt, const real_1d_array &x, const ae_int_t k) { alglib_impl::ae_state _alglib_env_state; bool selfmatch; selfmatch = true; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::kdtreequeryknn(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_vector*>(x.c_ptr()), k, selfmatch, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* R-NN query: all points within R-sphere centered at X INPUT PARAMETERS KDT - KD-tree X - point, array[0..NX-1]. R - radius of sphere (in corresponding norm), R>0 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True RESULT number of neighbors found, >=0 This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain actual results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() to get distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequeryrnn(const kdtree &kdt, const real_1d_array &x, const double r, const bool selfmatch) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::kdtreequeryrnn(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_vector*>(x.c_ptr()), r, selfmatch, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* R-NN query: all points within R-sphere centered at X INPUT PARAMETERS KDT - KD-tree X - point, array[0..NX-1]. R - radius of sphere (in corresponding norm), R>0 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True RESULT number of neighbors found, >=0 This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain actual results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() to get distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequeryrnn(const kdtree &kdt, const real_1d_array &x, const double r) { alglib_impl::ae_state _alglib_env_state; bool selfmatch; selfmatch = true; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::kdtreequeryrnn(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_vector*>(x.c_ptr()), r, selfmatch, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* K-NN query: approximate K nearest neighbors INPUT PARAMETERS KDT - KD-tree X - point, array[0..NX-1]. K - number of neighbors to return, K>=1 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True Eps - approximation factor, Eps>=0. eps-approximate nearest neighbor is a neighbor whose distance from X is at most (1+eps) times distance of true nearest neighbor. RESULT number of actual neighbors found (either K or N, if K>N). NOTES significant performance gain may be achieved only when Eps is is on the order of magnitude of 1 or larger. This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain these results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() to get distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequeryaknn(const kdtree &kdt, const real_1d_array &x, const ae_int_t k, const bool selfmatch, const double eps) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::kdtreequeryaknn(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_vector*>(x.c_ptr()), k, selfmatch, eps, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* K-NN query: approximate K nearest neighbors INPUT PARAMETERS KDT - KD-tree X - point, array[0..NX-1]. K - number of neighbors to return, K>=1 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True Eps - approximation factor, Eps>=0. eps-approximate nearest neighbor is a neighbor whose distance from X is at most (1+eps) times distance of true nearest neighbor. RESULT number of actual neighbors found (either K or N, if K>N). NOTES significant performance gain may be achieved only when Eps is is on the order of magnitude of 1 or larger. This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain these results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() to get distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequeryaknn(const kdtree &kdt, const real_1d_array &x, const ae_int_t k, const double eps) { alglib_impl::ae_state _alglib_env_state; bool selfmatch; selfmatch = true; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::kdtreequeryaknn(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_vector*>(x.c_ptr()), k, selfmatch, eps, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* X-values from last query INPUT PARAMETERS KDT - KD-tree X - possibly pre-allocated buffer. If X is too small to store result, it is resized. If size(X) is enough to store result, it is left unchanged. OUTPUT PARAMETERS X - rows are filled with X-values NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsXY() X- and Y-values * KDTreeQueryResultsTags() tag values * KDTreeQueryResultsDistances() distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsx(const kdtree &kdt, real_2d_array &x) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreequeryresultsx(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_matrix*>(x.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* X- and Y-values from last query INPUT PARAMETERS KDT - KD-tree XY - possibly pre-allocated buffer. If XY is too small to store result, it is resized. If size(XY) is enough to store result, it is left unchanged. OUTPUT PARAMETERS XY - rows are filled with points: first NX columns with X-values, next NY columns - with Y-values. NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsX() X-values * KDTreeQueryResultsTags() tag values * KDTreeQueryResultsDistances() distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsxy(const kdtree &kdt, real_2d_array &xy) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreequeryresultsxy(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_matrix*>(xy.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* Tags from last query INPUT PARAMETERS KDT - KD-tree Tags - possibly pre-allocated buffer. If X is too small to store result, it is resized. If size(X) is enough to store result, it is left unchanged. OUTPUT PARAMETERS Tags - filled with tags associated with points, or, when no tags were supplied, with zeros NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsX() X-values * KDTreeQueryResultsXY() X- and Y-values * KDTreeQueryResultsDistances() distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultstags(const kdtree &kdt, integer_1d_array &tags) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreequeryresultstags(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_vector*>(tags.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* Distances from last query INPUT PARAMETERS KDT - KD-tree R - possibly pre-allocated buffer. If X is too small to store result, it is resized. If size(X) is enough to store result, it is left unchanged. OUTPUT PARAMETERS R - filled with distances (in corresponding norm) NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsX() X-values * KDTreeQueryResultsXY() X- and Y-values * KDTreeQueryResultsTags() tag values -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsdistances(const kdtree &kdt, real_1d_array &r) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreequeryresultsdistances(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_vector*>(r.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* X-values from last query; 'interactive' variant for languages like Python which support constructs like "X = KDTreeQueryResultsXI(KDT)" and interactive mode of interpreter. This function allocates new array on each call, so it is significantly slower than its 'non-interactive' counterpart, but it is more convenient when you call it from command line. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsxi(const kdtree &kdt, real_2d_array &x) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreequeryresultsxi(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_matrix*>(x.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* XY-values from last query; 'interactive' variant for languages like Python which support constructs like "XY = KDTreeQueryResultsXYI(KDT)" and interactive mode of interpreter. This function allocates new array on each call, so it is significantly slower than its 'non-interactive' counterpart, but it is more convenient when you call it from command line. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsxyi(const kdtree &kdt, real_2d_array &xy) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreequeryresultsxyi(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_matrix*>(xy.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* Tags from last query; 'interactive' variant for languages like Python which support constructs like "Tags = KDTreeQueryResultsTagsI(KDT)" and interactive mode of interpreter. This function allocates new array on each call, so it is significantly slower than its 'non-interactive' counterpart, but it is more convenient when you call it from command line. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultstagsi(const kdtree &kdt, integer_1d_array &tags) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreequeryresultstagsi(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_vector*>(tags.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* Distances from last query; 'interactive' variant for languages like Python which support constructs like "R = KDTreeQueryResultsDistancesI(KDT)" and interactive mode of interpreter. This function allocates new array on each call, so it is significantly slower than its 'non-interactive' counterpart, but it is more convenient when you call it from command line. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsdistancesi(const kdtree &kdt, real_1d_array &r) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreequeryresultsdistancesi(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_vector*>(r.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* *************************************************************************/ _xdebugrecord1_owner::_xdebugrecord1_owner() { p_struct = (alglib_impl::xdebugrecord1*)alglib_impl::ae_malloc(sizeof(alglib_impl::xdebugrecord1), NULL); if( p_struct==NULL ) throw ap_error("ALGLIB: malloc error"); alglib_impl::_xdebugrecord1_init(p_struct, NULL); } _xdebugrecord1_owner::_xdebugrecord1_owner(const _xdebugrecord1_owner &rhs) { p_struct = (alglib_impl::xdebugrecord1*)alglib_impl::ae_malloc(sizeof(alglib_impl::xdebugrecord1), NULL); if( p_struct==NULL ) throw ap_error("ALGLIB: malloc error"); alglib_impl::_xdebugrecord1_init_copy(p_struct, const_cast<alglib_impl::xdebugrecord1*>(rhs.p_struct), NULL); } _xdebugrecord1_owner& _xdebugrecord1_owner::operator=(const _xdebugrecord1_owner &rhs) { if( this==&rhs ) return *this; alglib_impl::_xdebugrecord1_clear(p_struct); alglib_impl::_xdebugrecord1_init_copy(p_struct, const_cast<alglib_impl::xdebugrecord1*>(rhs.p_struct), NULL); return *this; } _xdebugrecord1_owner::~_xdebugrecord1_owner() { alglib_impl::_xdebugrecord1_clear(p_struct); ae_free(p_struct); } alglib_impl::xdebugrecord1* _xdebugrecord1_owner::c_ptr() { return p_struct; } alglib_impl::xdebugrecord1* _xdebugrecord1_owner::c_ptr() const { return const_cast<alglib_impl::xdebugrecord1*>(p_struct); } xdebugrecord1::xdebugrecord1() : _xdebugrecord1_owner() ,i(p_struct->i),c(*((alglib::complex*)(&p_struct->c))),a(&p_struct->a) { } xdebugrecord1::xdebugrecord1(const xdebugrecord1 &rhs):_xdebugrecord1_owner(rhs) ,i(p_struct->i),c(*((alglib::complex*)(&p_struct->c))),a(&p_struct->a) { } xdebugrecord1& xdebugrecord1::operator=(const xdebugrecord1 &rhs) { if( this==&rhs ) return *this; _xdebugrecord1_owner::operator=(rhs); return *this; } xdebugrecord1::~xdebugrecord1() { } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Creates and returns XDebugRecord1 structure: * integer and complex fields of Rec1 are set to 1 and 1+i correspondingly * array field of Rec1 is set to [2,3] -- ALGLIB -- Copyright 27.05.2014 by Bochkanov Sergey *************************************************************************/ void xdebuginitrecord1(xdebugrecord1 &rec1) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebuginitrecord1(const_cast<alglib_impl::xdebugrecord1*>(rec1.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Counts number of True values in the boolean 1D array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_int_t xdebugb1count(const boolean_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::xdebugb1count(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by NOT(a[i]). Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb1not(const boolean_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugb1not(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Appends copy of array to itself. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb1appendcopy(boolean_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugb1appendcopy(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate N-element array with even-numbered elements set to True. Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb1outeven(const ae_int_t n, boolean_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugb1outeven(n, const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_int_t xdebugi1sum(const integer_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::xdebugi1sum(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -A[I] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi1neg(const integer_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugi1neg(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Appends copy of array to itself. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi1appendcopy(integer_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugi1appendcopy(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate N-element array with even-numbered A[I] set to I, and odd-numbered ones set to 0. Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi1outeven(const ae_int_t n, integer_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugi1outeven(n, const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ double xdebugr1sum(const real_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { double result = alglib_impl::xdebugr1sum(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<double*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -A[I] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr1neg(const real_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugr1neg(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Appends copy of array to itself. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr1appendcopy(real_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugr1appendcopy(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate N-element array with even-numbered A[I] set to I*0.25, and odd-numbered ones are set to 0. Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr1outeven(const ae_int_t n, real_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugr1outeven(n, const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ alglib::complex xdebugc1sum(const complex_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_complex result = alglib_impl::xdebugc1sum(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<alglib::complex*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -A[I] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc1neg(const complex_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugc1neg(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Appends copy of array to itself. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc1appendcopy(complex_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugc1appendcopy(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate N-element array with even-numbered A[K] set to (x,y) = (K*0.25, K*0.125) and odd-numbered ones are set to 0. Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc1outeven(const ae_int_t n, complex_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugc1outeven(n, const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Counts number of True values in the boolean 2D array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_int_t xdebugb2count(const boolean_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::xdebugb2count(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by NOT(a[i]). Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb2not(const boolean_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugb2not(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Transposes array. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb2transpose(boolean_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugb2transpose(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate MxN matrix with elements set to "Sin(3*I+5*J)>0" Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb2outsin(const ae_int_t m, const ae_int_t n, boolean_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugb2outsin(m, n, const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_int_t xdebugi2sum(const integer_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::xdebugi2sum(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -a[i,j] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi2neg(const integer_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugi2neg(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Transposes array. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi2transpose(integer_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugi2transpose(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate MxN matrix with elements set to "Sign(Sin(3*I+5*J))" Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi2outsin(const ae_int_t m, const ae_int_t n, integer_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugi2outsin(m, n, const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ double xdebugr2sum(const real_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { double result = alglib_impl::xdebugr2sum(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<double*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -a[i,j] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr2neg(const real_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugr2neg(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Transposes array. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr2transpose(real_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugr2transpose(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate MxN matrix with elements set to "Sin(3*I+5*J)" Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr2outsin(const ae_int_t m, const ae_int_t n, real_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugr2outsin(m, n, const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ alglib::complex xdebugc2sum(const complex_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_complex result = alglib_impl::xdebugc2sum(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<alglib::complex*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -a[i,j] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc2neg(const complex_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugc2neg(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Transposes array. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc2transpose(complex_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugc2transpose(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate MxN matrix with elements set to "Sin(3*I+5*J),Cos(3*I+5*J)" Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc2outsincos(const ae_int_t m, const ae_int_t n, complex_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugc2outsincos(m, n, const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of a[i,j]*(1+b[i,j]) such that c[i,j] is True -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ double xdebugmaskedbiasedproductsum(const ae_int_t m, const ae_int_t n, const real_2d_array &a, const real_2d_array &b, const boolean_2d_array &c) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { double result = alglib_impl::xdebugmaskedbiasedproductsum(m, n, const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), const_cast<alglib_impl::ae_matrix*>(b.c_ptr()), const_cast<alglib_impl::ae_matrix*>(c.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<double*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } } ///////////////////////////////////////////////////////////////////////// // // THIS SECTION CONTAINS IMPLEMENTATION OF COMPUTATIONAL CORE // ///////////////////////////////////////////////////////////////////////// namespace alglib_impl { static ae_int_t hqrnd_hqrndmax = 2147483561; static ae_int_t hqrnd_hqrndm1 = 2147483563; static ae_int_t hqrnd_hqrndm2 = 2147483399; static ae_int_t hqrnd_hqrndmagic = 1634357784; static ae_int_t hqrnd_hqrndintegerbase(hqrndstate* state, ae_state *_state); static ae_int_t nearestneighbor_splitnodesize = 6; static ae_int_t nearestneighbor_kdtreefirstversion = 0; static void nearestneighbor_kdtreesplit(kdtree* kdt, ae_int_t i1, ae_int_t i2, ae_int_t d, double s, ae_int_t* i3, ae_state *_state); static void nearestneighbor_kdtreegeneratetreerec(kdtree* kdt, ae_int_t* nodesoffs, ae_int_t* splitsoffs, ae_int_t i1, ae_int_t i2, ae_int_t maxleafsize, ae_state *_state); static void nearestneighbor_kdtreequerynnrec(kdtree* kdt, ae_int_t offs, ae_state *_state); static void nearestneighbor_kdtreeinitbox(kdtree* kdt, /* Real */ ae_vector* x, ae_state *_state); static void nearestneighbor_kdtreeallocdatasetindependent(kdtree* kdt, ae_int_t nx, ae_int_t ny, ae_state *_state); static void nearestneighbor_kdtreeallocdatasetdependent(kdtree* kdt, ae_int_t n, ae_int_t nx, ae_int_t ny, ae_state *_state); static void nearestneighbor_kdtreealloctemporaries(kdtree* kdt, ae_int_t n, ae_int_t nx, ae_int_t ny, ae_state *_state); /************************************************************************* HQRNDState initialization with random values which come from standard RNG. -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndrandomize(hqrndstate* state, ae_state *_state) { ae_int_t s0; ae_int_t s1; _hqrndstate_clear(state); s0 = ae_randominteger(hqrnd_hqrndm1, _state); s1 = ae_randominteger(hqrnd_hqrndm2, _state); hqrndseed(s0, s1, state, _state); } /************************************************************************* HQRNDState initialization with seed values -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndseed(ae_int_t s1, ae_int_t s2, hqrndstate* state, ae_state *_state) { _hqrndstate_clear(state); /* * Protection against negative seeds: * * SEED := -(SEED+1) * * We can use just "-SEED" because there exists such integer number N * that N<0, -N=N<0 too. (This number is equal to 0x800...000). Need * to handle such seed correctly forces us to use a bit complicated * formula. */ if( s1<0 ) { s1 = -(s1+1); } if( s2<0 ) { s2 = -(s2+1); } state->s1 = s1%(hqrnd_hqrndm1-1)+1; state->s2 = s2%(hqrnd_hqrndm2-1)+1; state->magicv = hqrnd_hqrndmagic; } /************************************************************************* This function generates random real number in (0,1), not including interval boundaries State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ double hqrnduniformr(hqrndstate* state, ae_state *_state) { double result; result = (double)(hqrnd_hqrndintegerbase(state, _state)+1)/(double)(hqrnd_hqrndmax+2); return result; } /************************************************************************* This function generates random integer number in [0, N) 1. State structure must be initialized with HQRNDRandomize() or HQRNDSeed() 2. N can be any positive number except for very large numbers: * close to 2^31 on 32-bit systems * close to 2^62 on 64-bit systems An exception will be generated if N is too large. -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ ae_int_t hqrnduniformi(hqrndstate* state, ae_int_t n, ae_state *_state) { ae_int_t maxcnt; ae_int_t mx; ae_int_t a; ae_int_t b; ae_int_t result; ae_assert(n>0, "HQRNDUniformI: N<=0!", _state); maxcnt = hqrnd_hqrndmax+1; /* * Two branches: one for N<=MaxCnt, another for N>MaxCnt. */ if( n>maxcnt ) { /* * N>=MaxCnt. * * We have two options here: * a) N is exactly divisible by MaxCnt * b) N is not divisible by MaxCnt * * In both cases we reduce problem on interval spanning [0,N) * to several subproblems on intervals spanning [0,MaxCnt). */ if( n%maxcnt==0 ) { /* * N is exactly divisible by MaxCnt. * * [0,N) range is dividided into N/MaxCnt bins, * each of them having length equal to MaxCnt. * * We generate: * * random bin number B * * random offset within bin A * Both random numbers are generated by recursively * calling HQRNDUniformI(). * * Result is equal to A+MaxCnt*B. */ ae_assert(n/maxcnt<=maxcnt, "HQRNDUniformI: N is too large", _state); a = hqrnduniformi(state, maxcnt, _state); b = hqrnduniformi(state, n/maxcnt, _state); result = a+maxcnt*b; } else { /* * N is NOT exactly divisible by MaxCnt. * * [0,N) range is dividided into Ceil(N/MaxCnt) bins, * each of them having length equal to MaxCnt. * * We generate: * * random bin number B in [0, Ceil(N/MaxCnt)-1] * * random offset within bin A * * if both of what is below is true * 1) bin number B is that of the last bin * 2) A >= N mod MaxCnt * then we repeat generation of A/B. * This stage is essential in order to avoid bias in the result. * * otherwise, we return A*MaxCnt+N */ ae_assert(n/maxcnt+1<=maxcnt, "HQRNDUniformI: N is too large", _state); result = -1; do { a = hqrnduniformi(state, maxcnt, _state); b = hqrnduniformi(state, n/maxcnt+1, _state); if( b==n/maxcnt&&a>=n%maxcnt ) { continue; } result = a+maxcnt*b; } while(result<0); } } else { /* * N<=MaxCnt * * Code below is a bit complicated because we can not simply * return "HQRNDIntegerBase() mod N" - it will be skewed for * large N's in [0.1*HQRNDMax...HQRNDMax]. */ mx = maxcnt-maxcnt%n; do { result = hqrnd_hqrndintegerbase(state, _state); } while(result>=mx); result = result%n; } return result; } /************************************************************************* Random number generator: normal numbers This function generates one random number from normal distribution. Its performance is equal to that of HQRNDNormal2() State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ double hqrndnormal(hqrndstate* state, ae_state *_state) { double v1; double v2; double result; hqrndnormal2(state, &v1, &v2, _state); result = v1; return result; } /************************************************************************* Random number generator: random X and Y such that X^2+Y^2=1 State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndunit2(hqrndstate* state, double* x, double* y, ae_state *_state) { double v; double mx; double mn; *x = 0; *y = 0; do { hqrndnormal2(state, x, y, _state); } while(!(ae_fp_neq(*x,(double)(0))||ae_fp_neq(*y,(double)(0)))); mx = ae_maxreal(ae_fabs(*x, _state), ae_fabs(*y, _state), _state); mn = ae_minreal(ae_fabs(*x, _state), ae_fabs(*y, _state), _state); v = mx*ae_sqrt(1+ae_sqr(mn/mx, _state), _state); *x = *x/v; *y = *y/v; } /************************************************************************* Random number generator: normal numbers This function generates two independent random numbers from normal distribution. Its performance is equal to that of HQRNDNormal() State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndnormal2(hqrndstate* state, double* x1, double* x2, ae_state *_state) { double u; double v; double s; *x1 = 0; *x2 = 0; for(;;) { u = 2*hqrnduniformr(state, _state)-1; v = 2*hqrnduniformr(state, _state)-1; s = ae_sqr(u, _state)+ae_sqr(v, _state); if( ae_fp_greater(s,(double)(0))&&ae_fp_less(s,(double)(1)) ) { /* * two Sqrt's instead of one to * avoid overflow when S is too small */ s = ae_sqrt(-2*ae_log(s, _state), _state)/ae_sqrt(s, _state); *x1 = u*s; *x2 = v*s; return; } } } /************************************************************************* Random number generator: exponential distribution State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 11.08.2007 by Bochkanov Sergey *************************************************************************/ double hqrndexponential(hqrndstate* state, double lambdav, ae_state *_state) { double result; ae_assert(ae_fp_greater(lambdav,(double)(0)), "HQRNDExponential: LambdaV<=0!", _state); result = -ae_log(hqrnduniformr(state, _state), _state)/lambdav; return result; } /************************************************************************* This function generates random number from discrete distribution given by finite sample X. INPUT PARAMETERS State - high quality random number generator, must be initialized with HQRNDRandomize() or HQRNDSeed(). X - finite sample N - number of elements to use, N>=1 RESULT this function returns one of the X[i] for random i=0..N-1 -- ALGLIB -- Copyright 08.11.2011 by Bochkanov Sergey *************************************************************************/ double hqrnddiscrete(hqrndstate* state, /* Real */ ae_vector* x, ae_int_t n, ae_state *_state) { double result; ae_assert(n>0, "HQRNDDiscrete: N<=0", _state); ae_assert(n<=x->cnt, "HQRNDDiscrete: Length(X)<N", _state); result = x->ptr.p_double[hqrnduniformi(state, n, _state)]; return result; } /************************************************************************* This function generates random number from continuous distribution given by finite sample X. INPUT PARAMETERS State - high quality random number generator, must be initialized with HQRNDRandomize() or HQRNDSeed(). X - finite sample, array[N] (can be larger, in this case only leading N elements are used). THIS ARRAY MUST BE SORTED BY ASCENDING. N - number of elements to use, N>=1 RESULT this function returns random number from continuous distribution which tries to approximate X as mush as possible. min(X)<=Result<=max(X). -- ALGLIB -- Copyright 08.11.2011 by Bochkanov Sergey *************************************************************************/ double hqrndcontinuous(hqrndstate* state, /* Real */ ae_vector* x, ae_int_t n, ae_state *_state) { double mx; double mn; ae_int_t i; double result; ae_assert(n>0, "HQRNDContinuous: N<=0", _state); ae_assert(n<=x->cnt, "HQRNDContinuous: Length(X)<N", _state); if( n==1 ) { result = x->ptr.p_double[0]; return result; } i = hqrnduniformi(state, n-1, _state); mn = x->ptr.p_double[i]; mx = x->ptr.p_double[i+1]; ae_assert(ae_fp_greater_eq(mx,mn), "HQRNDDiscrete: X is not sorted by ascending", _state); if( ae_fp_neq(mx,mn) ) { result = (mx-mn)*hqrnduniformr(state, _state)+mn; } else { result = mn; } return result; } /************************************************************************* This function returns random integer in [0,HQRNDMax] L'Ecuyer, Efficient and portable combined random number generators *************************************************************************/ static ae_int_t hqrnd_hqrndintegerbase(hqrndstate* state, ae_state *_state) { ae_int_t k; ae_int_t result; ae_assert(state->magicv==hqrnd_hqrndmagic, "HQRNDIntegerBase: State is not correctly initialized!", _state); k = state->s1/53668; state->s1 = 40014*(state->s1-k*53668)-k*12211; if( state->s1<0 ) { state->s1 = state->s1+2147483563; } k = state->s2/52774; state->s2 = 40692*(state->s2-k*52774)-k*3791; if( state->s2<0 ) { state->s2 = state->s2+2147483399; } /* * Result */ result = state->s1-state->s2; if( result<1 ) { result = result+2147483562; } result = result-1; return result; } void _hqrndstate_init(void* _p, ae_state *_state) { hqrndstate *p = (hqrndstate*)_p; ae_touch_ptr((void*)p); } void _hqrndstate_init_copy(void* _dst, void* _src, ae_state *_state) { hqrndstate *dst = (hqrndstate*)_dst; hqrndstate *src = (hqrndstate*)_src; dst->s1 = src->s1; dst->s2 = src->s2; dst->magicv = src->magicv; } void _hqrndstate_clear(void* _p) { hqrndstate *p = (hqrndstate*)_p; ae_touch_ptr((void*)p); } void _hqrndstate_destroy(void* _p) { hqrndstate *p = (hqrndstate*)_p; ae_touch_ptr((void*)p); } /************************************************************************* KD-tree creation This subroutine creates KD-tree from set of X-values and optional Y-values INPUT PARAMETERS XY - dataset, array[0..N-1,0..NX+NY-1]. one row corresponds to one point. first NX columns contain X-values, next NY (NY may be zero) columns may contain associated Y-values N - number of points, N>=0. NX - space dimension, NX>=1. NY - number of optional Y-values, NY>=0. NormType- norm type: * 0 denotes infinity-norm * 1 denotes 1-norm * 2 denotes 2-norm (Euclidean norm) OUTPUT PARAMETERS KDT - KD-tree NOTES 1. KD-tree creation have O(N*logN) complexity and O(N*(2*NX+NY)) memory requirements. 2. Although KD-trees may be used with any combination of N and NX, they are more efficient than brute-force search only when N >> 4^NX. So they are most useful in low-dimensional tasks (NX=2, NX=3). NX=1 is another inefficient case, because simple binary search (without additional structures) is much more efficient in such tasks than KD-trees. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreebuild(/* Real */ ae_matrix* xy, ae_int_t n, ae_int_t nx, ae_int_t ny, ae_int_t normtype, kdtree* kdt, ae_state *_state) { ae_frame _frame_block; ae_vector tags; ae_int_t i; ae_frame_make(_state, &_frame_block); _kdtree_clear(kdt); ae_vector_init(&tags, 0, DT_INT, _state); ae_assert(n>=0, "KDTreeBuild: N<0", _state); ae_assert(nx>=1, "KDTreeBuild: NX<1", _state); ae_assert(ny>=0, "KDTreeBuild: NY<0", _state); ae_assert(normtype>=0&&normtype<=2, "KDTreeBuild: incorrect NormType", _state); ae_assert(xy->rows>=n, "KDTreeBuild: rows(X)<N", _state); ae_assert(xy->cols>=nx+ny||n==0, "KDTreeBuild: cols(X)<NX+NY", _state); ae_assert(apservisfinitematrix(xy, n, nx+ny, _state), "KDTreeBuild: XY contains infinite or NaN values", _state); if( n>0 ) { ae_vector_set_length(&tags, n, _state); for(i=0; i<=n-1; i++) { tags.ptr.p_int[i] = 0; } } kdtreebuildtagged(xy, &tags, n, nx, ny, normtype, kdt, _state); ae_frame_leave(_state); } /************************************************************************* KD-tree creation This subroutine creates KD-tree from set of X-values, integer tags and optional Y-values INPUT PARAMETERS XY - dataset, array[0..N-1,0..NX+NY-1]. one row corresponds to one point. first NX columns contain X-values, next NY (NY may be zero) columns may contain associated Y-values Tags - tags, array[0..N-1], contains integer tags associated with points. N - number of points, N>=0 NX - space dimension, NX>=1. NY - number of optional Y-values, NY>=0. NormType- norm type: * 0 denotes infinity-norm * 1 denotes 1-norm * 2 denotes 2-norm (Euclidean norm) OUTPUT PARAMETERS KDT - KD-tree NOTES 1. KD-tree creation have O(N*logN) complexity and O(N*(2*NX+NY)) memory requirements. 2. Although KD-trees may be used with any combination of N and NX, they are more efficient than brute-force search only when N >> 4^NX. So they are most useful in low-dimensional tasks (NX=2, NX=3). NX=1 is another inefficient case, because simple binary search (without additional structures) is much more efficient in such tasks than KD-trees. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreebuildtagged(/* Real */ ae_matrix* xy, /* Integer */ ae_vector* tags, ae_int_t n, ae_int_t nx, ae_int_t ny, ae_int_t normtype, kdtree* kdt, ae_state *_state) { ae_int_t i; ae_int_t j; ae_int_t maxnodes; ae_int_t nodesoffs; ae_int_t splitsoffs; _kdtree_clear(kdt); ae_assert(n>=0, "KDTreeBuildTagged: N<0", _state); ae_assert(nx>=1, "KDTreeBuildTagged: NX<1", _state); ae_assert(ny>=0, "KDTreeBuildTagged: NY<0", _state); ae_assert(normtype>=0&&normtype<=2, "KDTreeBuildTagged: incorrect NormType", _state); ae_assert(xy->rows>=n, "KDTreeBuildTagged: rows(X)<N", _state); ae_assert(xy->cols>=nx+ny||n==0, "KDTreeBuildTagged: cols(X)<NX+NY", _state); ae_assert(apservisfinitematrix(xy, n, nx+ny, _state), "KDTreeBuildTagged: XY contains infinite or NaN values", _state); /* * initialize */ kdt->n = n; kdt->nx = nx; kdt->ny = ny; kdt->normtype = normtype; kdt->kcur = 0; /* * N=0 => quick exit */ if( n==0 ) { return; } /* * Allocate */ nearestneighbor_kdtreeallocdatasetindependent(kdt, nx, ny, _state); nearestneighbor_kdtreeallocdatasetdependent(kdt, n, nx, ny, _state); /* * Initial fill */ for(i=0; i<=n-1; i++) { ae_v_move(&kdt->xy.ptr.pp_double[i][0], 1, &xy->ptr.pp_double[i][0], 1, ae_v_len(0,nx-1)); ae_v_move(&kdt->xy.ptr.pp_double[i][nx], 1, &xy->ptr.pp_double[i][0], 1, ae_v_len(nx,2*nx+ny-1)); kdt->tags.ptr.p_int[i] = tags->ptr.p_int[i]; } /* * Determine bounding box */ ae_v_move(&kdt->boxmin.ptr.p_double[0], 1, &kdt->xy.ptr.pp_double[0][0], 1, ae_v_len(0,nx-1)); ae_v_move(&kdt->boxmax.ptr.p_double[0], 1, &kdt->xy.ptr.pp_double[0][0], 1, ae_v_len(0,nx-1)); for(i=1; i<=n-1; i++) { for(j=0; j<=nx-1; j++) { kdt->boxmin.ptr.p_double[j] = ae_minreal(kdt->boxmin.ptr.p_double[j], kdt->xy.ptr.pp_double[i][j], _state); kdt->boxmax.ptr.p_double[j] = ae_maxreal(kdt->boxmax.ptr.p_double[j], kdt->xy.ptr.pp_double[i][j], _state); } } /* * prepare tree structure * * MaxNodes=N because we guarantee no trivial splits, i.e. * every split will generate two non-empty boxes */ maxnodes = n; ae_vector_set_length(&kdt->nodes, nearestneighbor_splitnodesize*2*maxnodes, _state); ae_vector_set_length(&kdt->splits, 2*maxnodes, _state); nodesoffs = 0; splitsoffs = 0; ae_v_move(&kdt->curboxmin.ptr.p_double[0], 1, &kdt->boxmin.ptr.p_double[0], 1, ae_v_len(0,nx-1)); ae_v_move(&kdt->curboxmax.ptr.p_double[0], 1, &kdt->boxmax.ptr.p_double[0], 1, ae_v_len(0,nx-1)); nearestneighbor_kdtreegeneratetreerec(kdt, &nodesoffs, &splitsoffs, 0, n, 8, _state); } /************************************************************************* K-NN query: K nearest neighbors INPUT PARAMETERS KDT - KD-tree X - point, array[0..NX-1]. K - number of neighbors to return, K>=1 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True RESULT number of actual neighbors found (either K or N, if K>N). This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain these results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() to get distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequeryknn(kdtree* kdt, /* Real */ ae_vector* x, ae_int_t k, ae_bool selfmatch, ae_state *_state) { ae_int_t result; ae_assert(k>=1, "KDTreeQueryKNN: K<1!", _state); ae_assert(x->cnt>=kdt->nx, "KDTreeQueryKNN: Length(X)<NX!", _state); ae_assert(isfinitevector(x, kdt->nx, _state), "KDTreeQueryKNN: X contains infinite or NaN values!", _state); result = kdtreequeryaknn(kdt, x, k, selfmatch, 0.0, _state); return result; } /************************************************************************* R-NN query: all points within R-sphere centered at X INPUT PARAMETERS KDT - KD-tree X - point, array[0..NX-1]. R - radius of sphere (in corresponding norm), R>0 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True RESULT number of neighbors found, >=0 This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain actual results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() to get distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequeryrnn(kdtree* kdt, /* Real */ ae_vector* x, double r, ae_bool selfmatch, ae_state *_state) { ae_int_t i; ae_int_t j; ae_int_t result; ae_assert(ae_fp_greater(r,(double)(0)), "KDTreeQueryRNN: incorrect R!", _state); ae_assert(x->cnt>=kdt->nx, "KDTreeQueryRNN: Length(X)<NX!", _state); ae_assert(isfinitevector(x, kdt->nx, _state), "KDTreeQueryRNN: X contains infinite or NaN values!", _state); /* * Handle special case: KDT.N=0 */ if( kdt->n==0 ) { kdt->kcur = 0; result = 0; return result; } /* * Prepare parameters */ kdt->kneeded = 0; if( kdt->normtype!=2 ) { kdt->rneeded = r; } else { kdt->rneeded = ae_sqr(r, _state); } kdt->selfmatch = selfmatch; kdt->approxf = (double)(1); kdt->kcur = 0; /* * calculate distance from point to current bounding box */ nearestneighbor_kdtreeinitbox(kdt, x, _state); /* * call recursive search * results are returned as heap */ nearestneighbor_kdtreequerynnrec(kdt, 0, _state); /* * pop from heap to generate ordered representation * * last element is not pop'ed because it is already in * its place */ result = kdt->kcur; j = kdt->kcur; for(i=kdt->kcur; i>=2; i--) { tagheappopi(&kdt->r, &kdt->idx, &j, _state); } return result; } /************************************************************************* K-NN query: approximate K nearest neighbors INPUT PARAMETERS KDT - KD-tree X - point, array[0..NX-1]. K - number of neighbors to return, K>=1 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True Eps - approximation factor, Eps>=0. eps-approximate nearest neighbor is a neighbor whose distance from X is at most (1+eps) times distance of true nearest neighbor. RESULT number of actual neighbors found (either K or N, if K>N). NOTES significant performance gain may be achieved only when Eps is is on the order of magnitude of 1 or larger. This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain these results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() to get distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequeryaknn(kdtree* kdt, /* Real */ ae_vector* x, ae_int_t k, ae_bool selfmatch, double eps, ae_state *_state) { ae_int_t i; ae_int_t j; ae_int_t result; ae_assert(k>0, "KDTreeQueryAKNN: incorrect K!", _state); ae_assert(ae_fp_greater_eq(eps,(double)(0)), "KDTreeQueryAKNN: incorrect Eps!", _state); ae_assert(x->cnt>=kdt->nx, "KDTreeQueryAKNN: Length(X)<NX!", _state); ae_assert(isfinitevector(x, kdt->nx, _state), "KDTreeQueryAKNN: X contains infinite or NaN values!", _state); /* * Handle special case: KDT.N=0 */ if( kdt->n==0 ) { kdt->kcur = 0; result = 0; return result; } /* * Prepare parameters */ k = ae_minint(k, kdt->n, _state); kdt->kneeded = k; kdt->rneeded = (double)(0); kdt->selfmatch = selfmatch; if( kdt->normtype==2 ) { kdt->approxf = 1/ae_sqr(1+eps, _state); } else { kdt->approxf = 1/(1+eps); } kdt->kcur = 0; /* * calculate distance from point to current bounding box */ nearestneighbor_kdtreeinitbox(kdt, x, _state); /* * call recursive search * results are returned as heap */ nearestneighbor_kdtreequerynnrec(kdt, 0, _state); /* * pop from heap to generate ordered representation * * last element is non pop'ed because it is already in * its place */ result = kdt->kcur; j = kdt->kcur; for(i=kdt->kcur; i>=2; i--) { tagheappopi(&kdt->r, &kdt->idx, &j, _state); } return result; } /************************************************************************* X-values from last query INPUT PARAMETERS KDT - KD-tree X - possibly pre-allocated buffer. If X is too small to store result, it is resized. If size(X) is enough to store result, it is left unchanged. OUTPUT PARAMETERS X - rows are filled with X-values NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsXY() X- and Y-values * KDTreeQueryResultsTags() tag values * KDTreeQueryResultsDistances() distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsx(kdtree* kdt, /* Real */ ae_matrix* x, ae_state *_state) { ae_int_t i; ae_int_t k; if( kdt->kcur==0 ) { return; } if( x->rows<kdt->kcur||x->cols<kdt->nx ) { ae_matrix_set_length(x, kdt->kcur, kdt->nx, _state); } k = kdt->kcur; for(i=0; i<=k-1; i++) { ae_v_move(&x->ptr.pp_double[i][0], 1, &kdt->xy.ptr.pp_double[kdt->idx.ptr.p_int[i]][kdt->nx], 1, ae_v_len(0,kdt->nx-1)); } } /************************************************************************* X- and Y-values from last query INPUT PARAMETERS KDT - KD-tree XY - possibly pre-allocated buffer. If XY is too small to store result, it is resized. If size(XY) is enough to store result, it is left unchanged. OUTPUT PARAMETERS XY - rows are filled with points: first NX columns with X-values, next NY columns - with Y-values. NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsX() X-values * KDTreeQueryResultsTags() tag values * KDTreeQueryResultsDistances() distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsxy(kdtree* kdt, /* Real */ ae_matrix* xy, ae_state *_state) { ae_int_t i; ae_int_t k; if( kdt->kcur==0 ) { return; } if( xy->rows<kdt->kcur||xy->cols<kdt->nx+kdt->ny ) { ae_matrix_set_length(xy, kdt->kcur, kdt->nx+kdt->ny, _state); } k = kdt->kcur; for(i=0; i<=k-1; i++) { ae_v_move(&xy->ptr.pp_double[i][0], 1, &kdt->xy.ptr.pp_double[kdt->idx.ptr.p_int[i]][kdt->nx], 1, ae_v_len(0,kdt->nx+kdt->ny-1)); } } /************************************************************************* Tags from last query INPUT PARAMETERS KDT - KD-tree Tags - possibly pre-allocated buffer. If X is too small to store result, it is resized. If size(X) is enough to store result, it is left unchanged. OUTPUT PARAMETERS Tags - filled with tags associated with points, or, when no tags were supplied, with zeros NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsX() X-values * KDTreeQueryResultsXY() X- and Y-values * KDTreeQueryResultsDistances() distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultstags(kdtree* kdt, /* Integer */ ae_vector* tags, ae_state *_state) { ae_int_t i; ae_int_t k; if( kdt->kcur==0 ) { return; } if( tags->cnt<kdt->kcur ) { ae_vector_set_length(tags, kdt->kcur, _state); } k = kdt->kcur; for(i=0; i<=k-1; i++) { tags->ptr.p_int[i] = kdt->tags.ptr.p_int[kdt->idx.ptr.p_int[i]]; } } /************************************************************************* Distances from last query INPUT PARAMETERS KDT - KD-tree R - possibly pre-allocated buffer. If X is too small to store result, it is resized. If size(X) is enough to store result, it is left unchanged. OUTPUT PARAMETERS R - filled with distances (in corresponding norm) NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsX() X-values * KDTreeQueryResultsXY() X- and Y-values * KDTreeQueryResultsTags() tag values -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsdistances(kdtree* kdt, /* Real */ ae_vector* r, ae_state *_state) { ae_int_t i; ae_int_t k; if( kdt->kcur==0 ) { return; } if( r->cnt<kdt->kcur ) { ae_vector_set_length(r, kdt->kcur, _state); } k = kdt->kcur; /* * unload norms * * Abs() call is used to handle cases with negative norms * (generated during KFN requests) */ if( kdt->normtype==0 ) { for(i=0; i<=k-1; i++) { r->ptr.p_double[i] = ae_fabs(kdt->r.ptr.p_double[i], _state); } } if( kdt->normtype==1 ) { for(i=0; i<=k-1; i++) { r->ptr.p_double[i] = ae_fabs(kdt->r.ptr.p_double[i], _state); } } if( kdt->normtype==2 ) { for(i=0; i<=k-1; i++) { r->ptr.p_double[i] = ae_sqrt(ae_fabs(kdt->r.ptr.p_double[i], _state), _state); } } } /************************************************************************* X-values from last query; 'interactive' variant for languages like Python which support constructs like "X = KDTreeQueryResultsXI(KDT)" and interactive mode of interpreter. This function allocates new array on each call, so it is significantly slower than its 'non-interactive' counterpart, but it is more convenient when you call it from command line. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsxi(kdtree* kdt, /* Real */ ae_matrix* x, ae_state *_state) { ae_matrix_clear(x); kdtreequeryresultsx(kdt, x, _state); } /************************************************************************* XY-values from last query; 'interactive' variant for languages like Python which support constructs like "XY = KDTreeQueryResultsXYI(KDT)" and interactive mode of interpreter. This function allocates new array on each call, so it is significantly slower than its 'non-interactive' counterpart, but it is more convenient when you call it from command line. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsxyi(kdtree* kdt, /* Real */ ae_matrix* xy, ae_state *_state) { ae_matrix_clear(xy); kdtreequeryresultsxy(kdt, xy, _state); } /************************************************************************* Tags from last query; 'interactive' variant for languages like Python which support constructs like "Tags = KDTreeQueryResultsTagsI(KDT)" and interactive mode of interpreter. This function allocates new array on each call, so it is significantly slower than its 'non-interactive' counterpart, but it is more convenient when you call it from command line. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultstagsi(kdtree* kdt, /* Integer */ ae_vector* tags, ae_state *_state) { ae_vector_clear(tags); kdtreequeryresultstags(kdt, tags, _state); } /************************************************************************* Distances from last query; 'interactive' variant for languages like Python which support constructs like "R = KDTreeQueryResultsDistancesI(KDT)" and interactive mode of interpreter. This function allocates new array on each call, so it is significantly slower than its 'non-interactive' counterpart, but it is more convenient when you call it from command line. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsdistancesi(kdtree* kdt, /* Real */ ae_vector* r, ae_state *_state) { ae_vector_clear(r); kdtreequeryresultsdistances(kdt, r, _state); } /************************************************************************* Serializer: allocation -- ALGLIB -- Copyright 14.03.2011 by Bochkanov Sergey *************************************************************************/ void kdtreealloc(ae_serializer* s, kdtree* tree, ae_state *_state) { /* * Header */ ae_serializer_alloc_entry(s); ae_serializer_alloc_entry(s); /* * Data */ ae_serializer_alloc_entry(s); ae_serializer_alloc_entry(s); ae_serializer_alloc_entry(s); ae_serializer_alloc_entry(s); allocrealmatrix(s, &tree->xy, -1, -1, _state); allocintegerarray(s, &tree->tags, -1, _state); allocrealarray(s, &tree->boxmin, -1, _state); allocrealarray(s, &tree->boxmax, -1, _state); allocintegerarray(s, &tree->nodes, -1, _state); allocrealarray(s, &tree->splits, -1, _state); } /************************************************************************* Serializer: serialization -- ALGLIB -- Copyright 14.03.2011 by Bochkanov Sergey *************************************************************************/ void kdtreeserialize(ae_serializer* s, kdtree* tree, ae_state *_state) { /* * Header */ ae_serializer_serialize_int(s, getkdtreeserializationcode(_state), _state); ae_serializer_serialize_int(s, nearestneighbor_kdtreefirstversion, _state); /* * Data */ ae_serializer_serialize_int(s, tree->n, _state); ae_serializer_serialize_int(s, tree->nx, _state); ae_serializer_serialize_int(s, tree->ny, _state); ae_serializer_serialize_int(s, tree->normtype, _state); serializerealmatrix(s, &tree->xy, -1, -1, _state); serializeintegerarray(s, &tree->tags, -1, _state); serializerealarray(s, &tree->boxmin, -1, _state); serializerealarray(s, &tree->boxmax, -1, _state); serializeintegerarray(s, &tree->nodes, -1, _state); serializerealarray(s, &tree->splits, -1, _state); } /************************************************************************* Serializer: unserialization -- ALGLIB -- Copyright 14.03.2011 by Bochkanov Sergey *************************************************************************/ void kdtreeunserialize(ae_serializer* s, kdtree* tree, ae_state *_state) { ae_int_t i0; ae_int_t i1; _kdtree_clear(tree); /* * check correctness of header */ ae_serializer_unserialize_int(s, &i0, _state); ae_assert(i0==getkdtreeserializationcode(_state), "KDTreeUnserialize: stream header corrupted", _state); ae_serializer_unserialize_int(s, &i1, _state); ae_assert(i1==nearestneighbor_kdtreefirstversion, "KDTreeUnserialize: stream header corrupted", _state); /* * Unserialize data */ ae_serializer_unserialize_int(s, &tree->n, _state); ae_serializer_unserialize_int(s, &tree->nx, _state); ae_serializer_unserialize_int(s, &tree->ny, _state); ae_serializer_unserialize_int(s, &tree->normtype, _state); unserializerealmatrix(s, &tree->xy, _state); unserializeintegerarray(s, &tree->tags, _state); unserializerealarray(s, &tree->boxmin, _state); unserializerealarray(s, &tree->boxmax, _state); unserializeintegerarray(s, &tree->nodes, _state); unserializerealarray(s, &tree->splits, _state); nearestneighbor_kdtreealloctemporaries(tree, tree->n, tree->nx, tree->ny, _state); } /************************************************************************* Rearranges nodes [I1,I2) using partition in D-th dimension with S as threshold. Returns split position I3: [I1,I3) and [I3,I2) are created as result. This subroutine doesn't create tree structures, just rearranges nodes. *************************************************************************/ static void nearestneighbor_kdtreesplit(kdtree* kdt, ae_int_t i1, ae_int_t i2, ae_int_t d, double s, ae_int_t* i3, ae_state *_state) { ae_int_t i; ae_int_t j; ae_int_t ileft; ae_int_t iright; double v; *i3 = 0; ae_assert(kdt->n>0, "KDTreeSplit: internal error", _state); /* * split XY/Tags in two parts: * * [ILeft,IRight] is non-processed part of XY/Tags * * After cycle is done, we have Ileft=IRight. We deal with * this element separately. * * After this, [I1,ILeft) contains left part, and [ILeft,I2) * contains right part. */ ileft = i1; iright = i2-1; while(ileft<iright) { if( ae_fp_less_eq(kdt->xy.ptr.pp_double[ileft][d],s) ) { /* * XY[ILeft] is on its place. * Advance ILeft. */ ileft = ileft+1; } else { /* * XY[ILeft,..] must be at IRight. * Swap and advance IRight. */ for(i=0; i<=2*kdt->nx+kdt->ny-1; i++) { v = kdt->xy.ptr.pp_double[ileft][i]; kdt->xy.ptr.pp_double[ileft][i] = kdt->xy.ptr.pp_double[iright][i]; kdt->xy.ptr.pp_double[iright][i] = v; } j = kdt->tags.ptr.p_int[ileft]; kdt->tags.ptr.p_int[ileft] = kdt->tags.ptr.p_int[iright]; kdt->tags.ptr.p_int[iright] = j; iright = iright-1; } } if( ae_fp_less_eq(kdt->xy.ptr.pp_double[ileft][d],s) ) { ileft = ileft+1; } else { iright = iright-1; } *i3 = ileft; } /************************************************************************* Recursive kd-tree generation subroutine. PARAMETERS KDT tree NodesOffs unused part of Nodes[] which must be filled by tree SplitsOffs unused part of Splits[] I1, I2 points from [I1,I2) are processed NodesOffs[] and SplitsOffs[] must be large enough. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ static void nearestneighbor_kdtreegeneratetreerec(kdtree* kdt, ae_int_t* nodesoffs, ae_int_t* splitsoffs, ae_int_t i1, ae_int_t i2, ae_int_t maxleafsize, ae_state *_state) { ae_int_t n; ae_int_t nx; ae_int_t ny; ae_int_t i; ae_int_t j; ae_int_t oldoffs; ae_int_t i3; ae_int_t cntless; ae_int_t cntgreater; double minv; double maxv; ae_int_t minidx; ae_int_t maxidx; ae_int_t d; double ds; double s; double v; double v0; double v1; ae_assert(kdt->n>0, "KDTreeGenerateTreeRec: internal error", _state); ae_assert(i2>i1, "KDTreeGenerateTreeRec: internal error", _state); /* * Generate leaf if needed */ if( i2-i1<=maxleafsize ) { kdt->nodes.ptr.p_int[*nodesoffs+0] = i2-i1; kdt->nodes.ptr.p_int[*nodesoffs+1] = i1; *nodesoffs = *nodesoffs+2; return; } /* * Load values for easier access */ nx = kdt->nx; ny = kdt->ny; /* * Select dimension to split: * * D is a dimension number * In case bounding box has zero size, we enforce creation of the leaf node. */ d = 0; ds = kdt->curboxmax.ptr.p_double[0]-kdt->curboxmin.ptr.p_double[0]; for(i=1; i<=nx-1; i++) { v = kdt->curboxmax.ptr.p_double[i]-kdt->curboxmin.ptr.p_double[i]; if( ae_fp_greater(v,ds) ) { ds = v; d = i; } } if( ae_fp_eq(ds,(double)(0)) ) { kdt->nodes.ptr.p_int[*nodesoffs+0] = i2-i1; kdt->nodes.ptr.p_int[*nodesoffs+1] = i1; *nodesoffs = *nodesoffs+2; return; } /* * Select split position S using sliding midpoint rule, * rearrange points into [I1,I3) and [I3,I2). * * In case all points has same value of D-th component * (MinV=MaxV) we enforce D-th dimension of bounding * box to become exactly zero and repeat tree construction. */ s = kdt->curboxmin.ptr.p_double[d]+0.5*ds; ae_v_move(&kdt->buf.ptr.p_double[0], 1, &kdt->xy.ptr.pp_double[i1][d], kdt->xy.stride, ae_v_len(0,i2-i1-1)); n = i2-i1; cntless = 0; cntgreater = 0; minv = kdt->buf.ptr.p_double[0]; maxv = kdt->buf.ptr.p_double[0]; minidx = i1; maxidx = i1; for(i=0; i<=n-1; i++) { v = kdt->buf.ptr.p_double[i]; if( ae_fp_less(v,minv) ) { minv = v; minidx = i1+i; } if( ae_fp_greater(v,maxv) ) { maxv = v; maxidx = i1+i; } if( ae_fp_less(v,s) ) { cntless = cntless+1; } if( ae_fp_greater(v,s) ) { cntgreater = cntgreater+1; } } if( ae_fp_eq(minv,maxv) ) { /* * In case all points has same value of D-th component * (MinV=MaxV) we enforce D-th dimension of bounding * box to become exactly zero and repeat tree construction. */ v0 = kdt->curboxmin.ptr.p_double[d]; v1 = kdt->curboxmax.ptr.p_double[d]; kdt->curboxmin.ptr.p_double[d] = minv; kdt->curboxmax.ptr.p_double[d] = maxv; nearestneighbor_kdtreegeneratetreerec(kdt, nodesoffs, splitsoffs, i1, i2, maxleafsize, _state); kdt->curboxmin.ptr.p_double[d] = v0; kdt->curboxmax.ptr.p_double[d] = v1; return; } if( cntless>0&&cntgreater>0 ) { /* * normal midpoint split */ nearestneighbor_kdtreesplit(kdt, i1, i2, d, s, &i3, _state); } else { /* * sliding midpoint */ if( cntless==0 ) { /* * 1. move split to MinV, * 2. place one point to the left bin (move to I1), * others - to the right bin */ s = minv; if( minidx!=i1 ) { for(i=0; i<=2*nx+ny-1; i++) { v = kdt->xy.ptr.pp_double[minidx][i]; kdt->xy.ptr.pp_double[minidx][i] = kdt->xy.ptr.pp_double[i1][i]; kdt->xy.ptr.pp_double[i1][i] = v; } j = kdt->tags.ptr.p_int[minidx]; kdt->tags.ptr.p_int[minidx] = kdt->tags.ptr.p_int[i1]; kdt->tags.ptr.p_int[i1] = j; } i3 = i1+1; } else { /* * 1. move split to MaxV, * 2. place one point to the right bin (move to I2-1), * others - to the left bin */ s = maxv; if( maxidx!=i2-1 ) { for(i=0; i<=2*nx+ny-1; i++) { v = kdt->xy.ptr.pp_double[maxidx][i]; kdt->xy.ptr.pp_double[maxidx][i] = kdt->xy.ptr.pp_double[i2-1][i]; kdt->xy.ptr.pp_double[i2-1][i] = v; } j = kdt->tags.ptr.p_int[maxidx]; kdt->tags.ptr.p_int[maxidx] = kdt->tags.ptr.p_int[i2-1]; kdt->tags.ptr.p_int[i2-1] = j; } i3 = i2-1; } } /* * Generate 'split' node */ kdt->nodes.ptr.p_int[*nodesoffs+0] = 0; kdt->nodes.ptr.p_int[*nodesoffs+1] = d; kdt->nodes.ptr.p_int[*nodesoffs+2] = *splitsoffs; kdt->splits.ptr.p_double[*splitsoffs+0] = s; oldoffs = *nodesoffs; *nodesoffs = *nodesoffs+nearestneighbor_splitnodesize; *splitsoffs = *splitsoffs+1; /* * Recirsive generation: * * update CurBox * * call subroutine * * restore CurBox */ kdt->nodes.ptr.p_int[oldoffs+3] = *nodesoffs; v = kdt->curboxmax.ptr.p_double[d]; kdt->curboxmax.ptr.p_double[d] = s; nearestneighbor_kdtreegeneratetreerec(kdt, nodesoffs, splitsoffs, i1, i3, maxleafsize, _state); kdt->curboxmax.ptr.p_double[d] = v; kdt->nodes.ptr.p_int[oldoffs+4] = *nodesoffs; v = kdt->curboxmin.ptr.p_double[d]; kdt->curboxmin.ptr.p_double[d] = s; nearestneighbor_kdtreegeneratetreerec(kdt, nodesoffs, splitsoffs, i3, i2, maxleafsize, _state); kdt->curboxmin.ptr.p_double[d] = v; } /************************************************************************* Recursive subroutine for NN queries. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ static void nearestneighbor_kdtreequerynnrec(kdtree* kdt, ae_int_t offs, ae_state *_state) { double ptdist; ae_int_t i; ae_int_t j; ae_int_t nx; ae_int_t i1; ae_int_t i2; ae_int_t d; double s; double v; double t1; ae_int_t childbestoffs; ae_int_t childworstoffs; ae_int_t childoffs; double prevdist; ae_bool todive; ae_bool bestisleft; ae_bool updatemin; ae_assert(kdt->n>0, "KDTreeQueryNNRec: internal error", _state); /* * Leaf node. * Process points. */ if( kdt->nodes.ptr.p_int[offs]>0 ) { i1 = kdt->nodes.ptr.p_int[offs+1]; i2 = i1+kdt->nodes.ptr.p_int[offs]; for(i=i1; i<=i2-1; i++) { /* * Calculate distance */ ptdist = (double)(0); nx = kdt->nx; if( kdt->normtype==0 ) { for(j=0; j<=nx-1; j++) { ptdist = ae_maxreal(ptdist, ae_fabs(kdt->xy.ptr.pp_double[i][j]-kdt->x.ptr.p_double[j], _state), _state); } } if( kdt->normtype==1 ) { for(j=0; j<=nx-1; j++) { ptdist = ptdist+ae_fabs(kdt->xy.ptr.pp_double[i][j]-kdt->x.ptr.p_double[j], _state); } } if( kdt->normtype==2 ) { for(j=0; j<=nx-1; j++) { ptdist = ptdist+ae_sqr(kdt->xy.ptr.pp_double[i][j]-kdt->x.ptr.p_double[j], _state); } } /* * Skip points with zero distance if self-matches are turned off */ if( ae_fp_eq(ptdist,(double)(0))&&!kdt->selfmatch ) { continue; } /* * We CAN'T process point if R-criterion isn't satisfied, * i.e. (RNeeded<>0) AND (PtDist>R). */ if( ae_fp_eq(kdt->rneeded,(double)(0))||ae_fp_less_eq(ptdist,kdt->rneeded) ) { /* * R-criterion is satisfied, we must either: * * replace worst point, if (KNeeded<>0) AND (KCur=KNeeded) * (or skip, if worst point is better) * * add point without replacement otherwise */ if( kdt->kcur<kdt->kneeded||kdt->kneeded==0 ) { /* * add current point to heap without replacement */ tagheappushi(&kdt->r, &kdt->idx, &kdt->kcur, ptdist, i, _state); } else { /* * New points are added or not, depending on their distance. * If added, they replace element at the top of the heap */ if( ae_fp_less(ptdist,kdt->r.ptr.p_double[0]) ) { if( kdt->kneeded==1 ) { kdt->idx.ptr.p_int[0] = i; kdt->r.ptr.p_double[0] = ptdist; } else { tagheapreplacetopi(&kdt->r, &kdt->idx, kdt->kneeded, ptdist, i, _state); } } } } } return; } /* * Simple split */ if( kdt->nodes.ptr.p_int[offs]==0 ) { /* * Load: * * D dimension to split * * S split position */ d = kdt->nodes.ptr.p_int[offs+1]; s = kdt->splits.ptr.p_double[kdt->nodes.ptr.p_int[offs+2]]; /* * Calculate: * * ChildBestOffs child box with best chances * * ChildWorstOffs child box with worst chances */ if( ae_fp_less_eq(kdt->x.ptr.p_double[d],s) ) { childbestoffs = kdt->nodes.ptr.p_int[offs+3]; childworstoffs = kdt->nodes.ptr.p_int[offs+4]; bestisleft = ae_true; } else { childbestoffs = kdt->nodes.ptr.p_int[offs+4]; childworstoffs = kdt->nodes.ptr.p_int[offs+3]; bestisleft = ae_false; } /* * Navigate through childs */ for(i=0; i<=1; i++) { /* * Select child to process: * * ChildOffs current child offset in Nodes[] * * UpdateMin whether minimum or maximum value * of bounding box is changed on update */ if( i==0 ) { childoffs = childbestoffs; updatemin = !bestisleft; } else { updatemin = bestisleft; childoffs = childworstoffs; } /* * Update bounding box and current distance */ if( updatemin ) { prevdist = kdt->curdist; t1 = kdt->x.ptr.p_double[d]; v = kdt->curboxmin.ptr.p_double[d]; if( ae_fp_less_eq(t1,s) ) { if( kdt->normtype==0 ) { kdt->curdist = ae_maxreal(kdt->curdist, s-t1, _state); } if( kdt->normtype==1 ) { kdt->curdist = kdt->curdist-ae_maxreal(v-t1, (double)(0), _state)+s-t1; } if( kdt->normtype==2 ) { kdt->curdist = kdt->curdist-ae_sqr(ae_maxreal(v-t1, (double)(0), _state), _state)+ae_sqr(s-t1, _state); } } kdt->curboxmin.ptr.p_double[d] = s; } else { prevdist = kdt->curdist; t1 = kdt->x.ptr.p_double[d]; v = kdt->curboxmax.ptr.p_double[d]; if( ae_fp_greater_eq(t1,s) ) { if( kdt->normtype==0 ) { kdt->curdist = ae_maxreal(kdt->curdist, t1-s, _state); } if( kdt->normtype==1 ) { kdt->curdist = kdt->curdist-ae_maxreal(t1-v, (double)(0), _state)+t1-s; } if( kdt->normtype==2 ) { kdt->curdist = kdt->curdist-ae_sqr(ae_maxreal(t1-v, (double)(0), _state), _state)+ae_sqr(t1-s, _state); } } kdt->curboxmax.ptr.p_double[d] = s; } /* * Decide: to dive into cell or not to dive */ if( ae_fp_neq(kdt->rneeded,(double)(0))&&ae_fp_greater(kdt->curdist,kdt->rneeded) ) { todive = ae_false; } else { if( kdt->kcur<kdt->kneeded||kdt->kneeded==0 ) { /* * KCur<KNeeded (i.e. not all points are found) */ todive = ae_true; } else { /* * KCur=KNeeded, decide to dive or not to dive * using point position relative to bounding box. */ todive = ae_fp_less_eq(kdt->curdist,kdt->r.ptr.p_double[0]*kdt->approxf); } } if( todive ) { nearestneighbor_kdtreequerynnrec(kdt, childoffs, _state); } /* * Restore bounding box and distance */ if( updatemin ) { kdt->curboxmin.ptr.p_double[d] = v; } else { kdt->curboxmax.ptr.p_double[d] = v; } kdt->curdist = prevdist; } return; } } /************************************************************************* Copies X[] to KDT.X[] Loads distance from X[] to bounding box. Initializes CurBox[]. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ static void nearestneighbor_kdtreeinitbox(kdtree* kdt, /* Real */ ae_vector* x, ae_state *_state) { ae_int_t i; double vx; double vmin; double vmax; ae_assert(kdt->n>0, "KDTreeInitBox: internal error", _state); /* * calculate distance from point to current bounding box */ kdt->curdist = (double)(0); if( kdt->normtype==0 ) { for(i=0; i<=kdt->nx-1; i++) { vx = x->ptr.p_double[i]; vmin = kdt->boxmin.ptr.p_double[i]; vmax = kdt->boxmax.ptr.p_double[i]; kdt->x.ptr.p_double[i] = vx; kdt->curboxmin.ptr.p_double[i] = vmin; kdt->curboxmax.ptr.p_double[i] = vmax; if( ae_fp_less(vx,vmin) ) { kdt->curdist = ae_maxreal(kdt->curdist, vmin-vx, _state); } else { if( ae_fp_greater(vx,vmax) ) { kdt->curdist = ae_maxreal(kdt->curdist, vx-vmax, _state); } } } } if( kdt->normtype==1 ) { for(i=0; i<=kdt->nx-1; i++) { vx = x->ptr.p_double[i]; vmin = kdt->boxmin.ptr.p_double[i]; vmax = kdt->boxmax.ptr.p_double[i]; kdt->x.ptr.p_double[i] = vx; kdt->curboxmin.ptr.p_double[i] = vmin; kdt->curboxmax.ptr.p_double[i] = vmax; if( ae_fp_less(vx,vmin) ) { kdt->curdist = kdt->curdist+vmin-vx; } else { if( ae_fp_greater(vx,vmax) ) { kdt->curdist = kdt->curdist+vx-vmax; } } } } if( kdt->normtype==2 ) { for(i=0; i<=kdt->nx-1; i++) { vx = x->ptr.p_double[i]; vmin = kdt->boxmin.ptr.p_double[i]; vmax = kdt->boxmax.ptr.p_double[i]; kdt->x.ptr.p_double[i] = vx; kdt->curboxmin.ptr.p_double[i] = vmin; kdt->curboxmax.ptr.p_double[i] = vmax; if( ae_fp_less(vx,vmin) ) { kdt->curdist = kdt->curdist+ae_sqr(vmin-vx, _state); } else { if( ae_fp_greater(vx,vmax) ) { kdt->curdist = kdt->curdist+ae_sqr(vx-vmax, _state); } } } } } /************************************************************************* This function allocates all dataset-independent array fields of KDTree, i.e. such array fields that their dimensions do not depend on dataset size. This function do not sets KDT.NX or KDT.NY - it just allocates arrays -- ALGLIB -- Copyright 14.03.2011 by Bochkanov Sergey *************************************************************************/ static void nearestneighbor_kdtreeallocdatasetindependent(kdtree* kdt, ae_int_t nx, ae_int_t ny, ae_state *_state) { ae_assert(kdt->n>0, "KDTreeAllocDatasetIndependent: internal error", _state); ae_vector_set_length(&kdt->x, nx, _state); ae_vector_set_length(&kdt->boxmin, nx, _state); ae_vector_set_length(&kdt->boxmax, nx, _state); ae_vector_set_length(&kdt->curboxmin, nx, _state); ae_vector_set_length(&kdt->curboxmax, nx, _state); } /************************************************************************* This function allocates all dataset-dependent array fields of KDTree, i.e. such array fields that their dimensions depend on dataset size. This function do not sets KDT.N, KDT.NX or KDT.NY - it just allocates arrays. -- ALGLIB -- Copyright 14.03.2011 by Bochkanov Sergey *************************************************************************/ static void nearestneighbor_kdtreeallocdatasetdependent(kdtree* kdt, ae_int_t n, ae_int_t nx, ae_int_t ny, ae_state *_state) { ae_assert(n>0, "KDTreeAllocDatasetDependent: internal error", _state); ae_matrix_set_length(&kdt->xy, n, 2*nx+ny, _state); ae_vector_set_length(&kdt->tags, n, _state); ae_vector_set_length(&kdt->idx, n, _state); ae_vector_set_length(&kdt->r, n, _state); ae_vector_set_length(&kdt->x, nx, _state); ae_vector_set_length(&kdt->buf, ae_maxint(n, nx, _state), _state); ae_vector_set_length(&kdt->nodes, nearestneighbor_splitnodesize*2*n, _state); ae_vector_set_length(&kdt->splits, 2*n, _state); } /************************************************************************* This function allocates temporaries. This function do not sets KDT.N, KDT.NX or KDT.NY - it just allocates arrays. -- ALGLIB -- Copyright 14.03.2011 by Bochkanov Sergey *************************************************************************/ static void nearestneighbor_kdtreealloctemporaries(kdtree* kdt, ae_int_t n, ae_int_t nx, ae_int_t ny, ae_state *_state) { ae_assert(n>0, "KDTreeAllocTemporaries: internal error", _state); ae_vector_set_length(&kdt->x, nx, _state); ae_vector_set_length(&kdt->idx, n, _state); ae_vector_set_length(&kdt->r, n, _state); ae_vector_set_length(&kdt->buf, ae_maxint(n, nx, _state), _state); ae_vector_set_length(&kdt->curboxmin, nx, _state); ae_vector_set_length(&kdt->curboxmax, nx, _state); } void _kdtree_init(void* _p, ae_state *_state) { kdtree *p = (kdtree*)_p; ae_touch_ptr((void*)p); ae_matrix_init(&p->xy, 0, 0, DT_REAL, _state); ae_vector_init(&p->tags, 0, DT_INT, _state); ae_vector_init(&p->boxmin, 0, DT_REAL, _state); ae_vector_init(&p->boxmax, 0, DT_REAL, _state); ae_vector_init(&p->nodes, 0, DT_INT, _state); ae_vector_init(&p->splits, 0, DT_REAL, _state); ae_vector_init(&p->x, 0, DT_REAL, _state); ae_vector_init(&p->idx, 0, DT_INT, _state); ae_vector_init(&p->r, 0, DT_REAL, _state); ae_vector_init(&p->buf, 0, DT_REAL, _state); ae_vector_init(&p->curboxmin, 0, DT_REAL, _state); ae_vector_init(&p->curboxmax, 0, DT_REAL, _state); } void _kdtree_init_copy(void* _dst, void* _src, ae_state *_state) { kdtree *dst = (kdtree*)_dst; kdtree *src = (kdtree*)_src; dst->n = src->n; dst->nx = src->nx; dst->ny = src->ny; dst->normtype = src->normtype; ae_matrix_init_copy(&dst->xy, &src->xy, _state); ae_vector_init_copy(&dst->tags, &src->tags, _state); ae_vector_init_copy(&dst->boxmin, &src->boxmin, _state); ae_vector_init_copy(&dst->boxmax, &src->boxmax, _state); ae_vector_init_copy(&dst->nodes, &src->nodes, _state); ae_vector_init_copy(&dst->splits, &src->splits, _state); ae_vector_init_copy(&dst->x, &src->x, _state); dst->kneeded = src->kneeded; dst->rneeded = src->rneeded; dst->selfmatch = src->selfmatch; dst->approxf = src->approxf; dst->kcur = src->kcur; ae_vector_init_copy(&dst->idx, &src->idx, _state); ae_vector_init_copy(&dst->r, &src->r, _state); ae_vector_init_copy(&dst->buf, &src->buf, _state); ae_vector_init_copy(&dst->curboxmin, &src->curboxmin, _state); ae_vector_init_copy(&dst->curboxmax, &src->curboxmax, _state); dst->curdist = src->curdist; dst->debugcounter = src->debugcounter; } void _kdtree_clear(void* _p) { kdtree *p = (kdtree*)_p; ae_touch_ptr((void*)p); ae_matrix_clear(&p->xy); ae_vector_clear(&p->tags); ae_vector_clear(&p->boxmin); ae_vector_clear(&p->boxmax); ae_vector_clear(&p->nodes); ae_vector_clear(&p->splits); ae_vector_clear(&p->x); ae_vector_clear(&p->idx); ae_vector_clear(&p->r); ae_vector_clear(&p->buf); ae_vector_clear(&p->curboxmin); ae_vector_clear(&p->curboxmax); } void _kdtree_destroy(void* _p) { kdtree *p = (kdtree*)_p; ae_touch_ptr((void*)p); ae_matrix_destroy(&p->xy); ae_vector_destroy(&p->tags); ae_vector_destroy(&p->boxmin); ae_vector_destroy(&p->boxmax); ae_vector_destroy(&p->nodes); ae_vector_destroy(&p->splits); ae_vector_destroy(&p->x); ae_vector_destroy(&p->idx); ae_vector_destroy(&p->r); ae_vector_destroy(&p->buf); ae_vector_destroy(&p->curboxmin); ae_vector_destroy(&p->curboxmax); } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Creates and returns XDebugRecord1 structure: * integer and complex fields of Rec1 are set to 1 and 1+i correspondingly * array field of Rec1 is set to [2,3] -- ALGLIB -- Copyright 27.05.2014 by Bochkanov Sergey *************************************************************************/ void xdebuginitrecord1(xdebugrecord1* rec1, ae_state *_state) { _xdebugrecord1_clear(rec1); rec1->i = 1; rec1->c.x = (double)(1); rec1->c.y = (double)(1); ae_vector_set_length(&rec1->a, 2, _state); rec1->a.ptr.p_double[0] = (double)(2); rec1->a.ptr.p_double[1] = (double)(3); } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Counts number of True values in the boolean 1D array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_int_t xdebugb1count(/* Boolean */ ae_vector* a, ae_state *_state) { ae_int_t i; ae_int_t result; result = 0; for(i=0; i<=a->cnt-1; i++) { if( a->ptr.p_bool[i] ) { result = result+1; } } return result; } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by NOT(a[i]). Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb1not(/* Boolean */ ae_vector* a, ae_state *_state) { ae_int_t i; for(i=0; i<=a->cnt-1; i++) { a->ptr.p_bool[i] = !a->ptr.p_bool[i]; } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Appends copy of array to itself. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb1appendcopy(/* Boolean */ ae_vector* a, ae_state *_state) { ae_frame _frame_block; ae_int_t i; ae_vector b; ae_frame_make(_state, &_frame_block); ae_vector_init(&b, 0, DT_BOOL, _state); ae_vector_set_length(&b, a->cnt, _state); for(i=0; i<=b.cnt-1; i++) { b.ptr.p_bool[i] = a->ptr.p_bool[i]; } ae_vector_set_length(a, 2*b.cnt, _state); for(i=0; i<=a->cnt-1; i++) { a->ptr.p_bool[i] = b.ptr.p_bool[i%b.cnt]; } ae_frame_leave(_state); } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate N-element array with even-numbered elements set to True. Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb1outeven(ae_int_t n, /* Boolean */ ae_vector* a, ae_state *_state) { ae_int_t i; ae_vector_clear(a); ae_vector_set_length(a, n, _state); for(i=0; i<=a->cnt-1; i++) { a->ptr.p_bool[i] = i%2==0; } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_int_t xdebugi1sum(/* Integer */ ae_vector* a, ae_state *_state) { ae_int_t i; ae_int_t result; result = 0; for(i=0; i<=a->cnt-1; i++) { result = result+a->ptr.p_int[i]; } return result; } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -A[I] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi1neg(/* Integer */ ae_vector* a, ae_state *_state) { ae_int_t i; for(i=0; i<=a->cnt-1; i++) { a->ptr.p_int[i] = -a->ptr.p_int[i]; } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Appends copy of array to itself. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi1appendcopy(/* Integer */ ae_vector* a, ae_state *_state) { ae_frame _frame_block; ae_int_t i; ae_vector b; ae_frame_make(_state, &_frame_block); ae_vector_init(&b, 0, DT_INT, _state); ae_vector_set_length(&b, a->cnt, _state); for(i=0; i<=b.cnt-1; i++) { b.ptr.p_int[i] = a->ptr.p_int[i]; } ae_vector_set_length(a, 2*b.cnt, _state); for(i=0; i<=a->cnt-1; i++) { a->ptr.p_int[i] = b.ptr.p_int[i%b.cnt]; } ae_frame_leave(_state); } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate N-element array with even-numbered A[I] set to I, and odd-numbered ones set to 0. Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi1outeven(ae_int_t n, /* Integer */ ae_vector* a, ae_state *_state) { ae_int_t i; ae_vector_clear(a); ae_vector_set_length(a, n, _state); for(i=0; i<=a->cnt-1; i++) { if( i%2==0 ) { a->ptr.p_int[i] = i; } else { a->ptr.p_int[i] = 0; } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ double xdebugr1sum(/* Real */ ae_vector* a, ae_state *_state) { ae_int_t i; double result; result = (double)(0); for(i=0; i<=a->cnt-1; i++) { result = result+a->ptr.p_double[i]; } return result; } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -A[I] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr1neg(/* Real */ ae_vector* a, ae_state *_state) { ae_int_t i; for(i=0; i<=a->cnt-1; i++) { a->ptr.p_double[i] = -a->ptr.p_double[i]; } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Appends copy of array to itself. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr1appendcopy(/* Real */ ae_vector* a, ae_state *_state) { ae_frame _frame_block; ae_int_t i; ae_vector b; ae_frame_make(_state, &_frame_block); ae_vector_init(&b, 0, DT_REAL, _state); ae_vector_set_length(&b, a->cnt, _state); for(i=0; i<=b.cnt-1; i++) { b.ptr.p_double[i] = a->ptr.p_double[i]; } ae_vector_set_length(a, 2*b.cnt, _state); for(i=0; i<=a->cnt-1; i++) { a->ptr.p_double[i] = b.ptr.p_double[i%b.cnt]; } ae_frame_leave(_state); } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate N-element array with even-numbered A[I] set to I*0.25, and odd-numbered ones are set to 0. Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr1outeven(ae_int_t n, /* Real */ ae_vector* a, ae_state *_state) { ae_int_t i; ae_vector_clear(a); ae_vector_set_length(a, n, _state); for(i=0; i<=a->cnt-1; i++) { if( i%2==0 ) { a->ptr.p_double[i] = i*0.25; } else { a->ptr.p_double[i] = (double)(0); } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_complex xdebugc1sum(/* Complex */ ae_vector* a, ae_state *_state) { ae_int_t i; ae_complex result; result = ae_complex_from_i(0); for(i=0; i<=a->cnt-1; i++) { result = ae_c_add(result,a->ptr.p_complex[i]); } return result; } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -A[I] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc1neg(/* Complex */ ae_vector* a, ae_state *_state) { ae_int_t i; for(i=0; i<=a->cnt-1; i++) { a->ptr.p_complex[i] = ae_c_neg(a->ptr.p_complex[i]); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Appends copy of array to itself. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc1appendcopy(/* Complex */ ae_vector* a, ae_state *_state) { ae_frame _frame_block; ae_int_t i; ae_vector b; ae_frame_make(_state, &_frame_block); ae_vector_init(&b, 0, DT_COMPLEX, _state); ae_vector_set_length(&b, a->cnt, _state); for(i=0; i<=b.cnt-1; i++) { b.ptr.p_complex[i] = a->ptr.p_complex[i]; } ae_vector_set_length(a, 2*b.cnt, _state); for(i=0; i<=a->cnt-1; i++) { a->ptr.p_complex[i] = b.ptr.p_complex[i%b.cnt]; } ae_frame_leave(_state); } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate N-element array with even-numbered A[K] set to (x,y) = (K*0.25, K*0.125) and odd-numbered ones are set to 0. Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc1outeven(ae_int_t n, /* Complex */ ae_vector* a, ae_state *_state) { ae_int_t i; ae_vector_clear(a); ae_vector_set_length(a, n, _state); for(i=0; i<=a->cnt-1; i++) { if( i%2==0 ) { a->ptr.p_complex[i].x = i*0.250; a->ptr.p_complex[i].y = i*0.125; } else { a->ptr.p_complex[i] = ae_complex_from_i(0); } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Counts number of True values in the boolean 2D array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_int_t xdebugb2count(/* Boolean */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; ae_int_t result; result = 0; for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { if( a->ptr.pp_bool[i][j] ) { result = result+1; } } } return result; } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by NOT(a[i]). Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb2not(/* Boolean */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { a->ptr.pp_bool[i][j] = !a->ptr.pp_bool[i][j]; } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Transposes array. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb2transpose(/* Boolean */ ae_matrix* a, ae_state *_state) { ae_frame _frame_block; ae_int_t i; ae_int_t j; ae_matrix b; ae_frame_make(_state, &_frame_block); ae_matrix_init(&b, 0, 0, DT_BOOL, _state); ae_matrix_set_length(&b, a->rows, a->cols, _state); for(i=0; i<=b.rows-1; i++) { for(j=0; j<=b.cols-1; j++) { b.ptr.pp_bool[i][j] = a->ptr.pp_bool[i][j]; } } ae_matrix_set_length(a, b.cols, b.rows, _state); for(i=0; i<=b.rows-1; i++) { for(j=0; j<=b.cols-1; j++) { a->ptr.pp_bool[j][i] = b.ptr.pp_bool[i][j]; } } ae_frame_leave(_state); } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate MxN matrix with elements set to "Sin(3*I+5*J)>0" Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb2outsin(ae_int_t m, ae_int_t n, /* Boolean */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; ae_matrix_clear(a); ae_matrix_set_length(a, m, n, _state); for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { a->ptr.pp_bool[i][j] = ae_fp_greater(ae_sin((double)(3*i+5*j), _state),(double)(0)); } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_int_t xdebugi2sum(/* Integer */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; ae_int_t result; result = 0; for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { result = result+a->ptr.pp_int[i][j]; } } return result; } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -a[i,j] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi2neg(/* Integer */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { a->ptr.pp_int[i][j] = -a->ptr.pp_int[i][j]; } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Transposes array. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi2transpose(/* Integer */ ae_matrix* a, ae_state *_state) { ae_frame _frame_block; ae_int_t i; ae_int_t j; ae_matrix b; ae_frame_make(_state, &_frame_block); ae_matrix_init(&b, 0, 0, DT_INT, _state); ae_matrix_set_length(&b, a->rows, a->cols, _state); for(i=0; i<=b.rows-1; i++) { for(j=0; j<=b.cols-1; j++) { b.ptr.pp_int[i][j] = a->ptr.pp_int[i][j]; } } ae_matrix_set_length(a, b.cols, b.rows, _state); for(i=0; i<=b.rows-1; i++) { for(j=0; j<=b.cols-1; j++) { a->ptr.pp_int[j][i] = b.ptr.pp_int[i][j]; } } ae_frame_leave(_state); } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate MxN matrix with elements set to "Sign(Sin(3*I+5*J))" Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi2outsin(ae_int_t m, ae_int_t n, /* Integer */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; ae_matrix_clear(a); ae_matrix_set_length(a, m, n, _state); for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { a->ptr.pp_int[i][j] = ae_sign(ae_sin((double)(3*i+5*j), _state), _state); } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ double xdebugr2sum(/* Real */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; double result; result = (double)(0); for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { result = result+a->ptr.pp_double[i][j]; } } return result; } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -a[i,j] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr2neg(/* Real */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { a->ptr.pp_double[i][j] = -a->ptr.pp_double[i][j]; } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Transposes array. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr2transpose(/* Real */ ae_matrix* a, ae_state *_state) { ae_frame _frame_block; ae_int_t i; ae_int_t j; ae_matrix b; ae_frame_make(_state, &_frame_block); ae_matrix_init(&b, 0, 0, DT_REAL, _state); ae_matrix_set_length(&b, a->rows, a->cols, _state); for(i=0; i<=b.rows-1; i++) { for(j=0; j<=b.cols-1; j++) { b.ptr.pp_double[i][j] = a->ptr.pp_double[i][j]; } } ae_matrix_set_length(a, b.cols, b.rows, _state); for(i=0; i<=b.rows-1; i++) { for(j=0; j<=b.cols-1; j++) { a->ptr.pp_double[j][i] = b.ptr.pp_double[i][j]; } } ae_frame_leave(_state); } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate MxN matrix with elements set to "Sin(3*I+5*J)" Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr2outsin(ae_int_t m, ae_int_t n, /* Real */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; ae_matrix_clear(a); ae_matrix_set_length(a, m, n, _state); for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { a->ptr.pp_double[i][j] = ae_sin((double)(3*i+5*j), _state); } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_complex xdebugc2sum(/* Complex */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; ae_complex result; result = ae_complex_from_i(0); for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { result = ae_c_add(result,a->ptr.pp_complex[i][j]); } } return result; } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -a[i,j] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc2neg(/* Complex */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { a->ptr.pp_complex[i][j] = ae_c_neg(a->ptr.pp_complex[i][j]); } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Transposes array. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc2transpose(/* Complex */ ae_matrix* a, ae_state *_state) { ae_frame _frame_block; ae_int_t i; ae_int_t j; ae_matrix b; ae_frame_make(_state, &_frame_block); ae_matrix_init(&b, 0, 0, DT_COMPLEX, _state); ae_matrix_set_length(&b, a->rows, a->cols, _state); for(i=0; i<=b.rows-1; i++) { for(j=0; j<=b.cols-1; j++) { b.ptr.pp_complex[i][j] = a->ptr.pp_complex[i][j]; } } ae_matrix_set_length(a, b.cols, b.rows, _state); for(i=0; i<=b.rows-1; i++) { for(j=0; j<=b.cols-1; j++) { a->ptr.pp_complex[j][i] = b.ptr.pp_complex[i][j]; } } ae_frame_leave(_state); } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate MxN matrix with elements set to "Sin(3*I+5*J),Cos(3*I+5*J)" Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc2outsincos(ae_int_t m, ae_int_t n, /* Complex */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; ae_matrix_clear(a); ae_matrix_set_length(a, m, n, _state); for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { a->ptr.pp_complex[i][j].x = ae_sin((double)(3*i+5*j), _state); a->ptr.pp_complex[i][j].y = ae_cos((double)(3*i+5*j), _state); } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of a[i,j]*(1+b[i,j]) such that c[i,j] is True -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ double xdebugmaskedbiasedproductsum(ae_int_t m, ae_int_t n, /* Real */ ae_matrix* a, /* Real */ ae_matrix* b, /* Boolean */ ae_matrix* c, ae_state *_state) { ae_int_t i; ae_int_t j; double result; ae_assert(m>=a->rows, "Assertion failed", _state); ae_assert(m>=b->rows, "Assertion failed", _state); ae_assert(m>=c->rows, "Assertion failed", _state); ae_assert(n>=a->cols, "Assertion failed", _state); ae_assert(n>=b->cols, "Assertion failed", _state); ae_assert(n>=c->cols, "Assertion failed", _state); result = 0.0; for(i=0; i<=m-1; i++) { for(j=0; j<=n-1; j++) { if( c->ptr.pp_bool[i][j] ) { result = result+a->ptr.pp_double[i][j]*(1+b->ptr.pp_double[i][j]); } } } return result; } void _xdebugrecord1_init(void* _p, ae_state *_state) { xdebugrecord1 *p = (xdebugrecord1*)_p; ae_touch_ptr((void*)p); ae_vector_init(&p->a, 0, DT_REAL, _state); } void _xdebugrecord1_init_copy(void* _dst, void* _src, ae_state *_state) { xdebugrecord1 *dst = (xdebugrecord1*)_dst; xdebugrecord1 *src = (xdebugrecord1*)_src; dst->i = src->i; dst->c = src->c; ae_vector_init_copy(&dst->a, &src->a, _state); } void _xdebugrecord1_clear(void* _p) { xdebugrecord1 *p = (xdebugrecord1*)_p; ae_touch_ptr((void*)p); ae_vector_clear(&p->a); } void _xdebugrecord1_destroy(void* _p) { xdebugrecord1 *p = (xdebugrecord1*)_p; ae_touch_ptr((void*)p); ae_vector_destroy(&p->a); } }
31.806769
236
0.56192
dc1394
a39c287b0063e72596163718cbbbfed66a0e5331
5,399
cpp
C++
src/game/server/player_pickup.cpp
bluedogz162/tf_coop_extended_custom
0212744ebef4f74c4e0047320d9da7d8571a8ee0
[ "Unlicense" ]
4
2020-04-24T22:20:34.000Z
2022-01-10T23:16:53.000Z
src/game/server/player_pickup.cpp
bluedogz162/tf_coop_extended_custom
0212744ebef4f74c4e0047320d9da7d8571a8ee0
[ "Unlicense" ]
1
2020-05-01T19:13:25.000Z
2020-05-02T07:01:45.000Z
src/game/server/player_pickup.cpp
bluedogz162/tf_coop_extended_custom
0212744ebef4f74c4e0047320d9da7d8571a8ee0
[ "Unlicense" ]
3
2020-04-24T22:20:36.000Z
2022-02-21T21:48:05.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //=============================================================================// #include "cbase.h" #include "player_pickup.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" // player pickup utility routine void Pickup_ForcePlayerToDropThisObject( CBaseEntity *pTarget ) { if ( pTarget == NULL ) return; IPhysicsObject *pPhysics = pTarget->VPhysicsGetObject(); if ( pPhysics == NULL ) return; if ( pPhysics->GetGameFlags() & FVPHYSICS_PLAYER_HELD ) { CBasePlayer* pPlayer = NULL; if (gpGlobals->maxClients == 1) { pPlayer = UTIL_GetLocalPlayer(); } else { // See which MP player is holding the physics object and then use that player to get the real mass of the object. // This is ugly but better than having linkage between an object and its "holding" player. for (int i = 1; i <= gpGlobals->maxClients; i++) { CBasePlayer* tempPlayer = UTIL_PlayerByIndex(i); if (tempPlayer && (tempPlayer->GetHeldObject() == pTarget)) { pPlayer = tempPlayer; break; } } } if (pPlayer) pPlayer->ForceDropOfCarriedPhysObjects( pTarget ); } } void Pickup_OnPhysGunDrop( CBaseEntity *pDroppedObject, CBasePlayer *pPlayer, PhysGunDrop_t Reason ) { IPlayerPickupVPhysics *pPickup = dynamic_cast<IPlayerPickupVPhysics *>(pDroppedObject); if ( pPickup ) { pPickup->OnPhysGunDrop( pPlayer, Reason ); } } void Pickup_OnPhysGunPickup( CBaseEntity *pPickedUpObject, CBasePlayer *pPlayer, PhysGunPickup_t reason ) { IPlayerPickupVPhysics *pPickup = dynamic_cast<IPlayerPickupVPhysics *>(pPickedUpObject); if ( pPickup ) { pPickup->OnPhysGunPickup( pPlayer, reason ); } // send phys gun pickup item event, but only in single player if ( !g_pGameRules->IsMultiplayer() ) { IGameEvent *event = gameeventmanager->CreateEvent( "physgun_pickup" ); if ( event ) { event->SetInt( "entindex", pPickedUpObject->entindex() ); gameeventmanager->FireEvent( event ); } } } bool Pickup_OnAttemptPhysGunPickup( CBaseEntity *pPickedUpObject, CBasePlayer *pPlayer, PhysGunPickup_t reason ) { IPlayerPickupVPhysics *pPickup = dynamic_cast<IPlayerPickupVPhysics *>(pPickedUpObject); if ( pPickup ) { return pPickup->OnAttemptPhysGunPickup( pPlayer, reason ); } return true; } CBaseEntity *Pickup_OnFailedPhysGunPickup( CBaseEntity *pPickedUpObject, Vector vPhysgunPos ) { IPlayerPickupVPhysics *pPickup = dynamic_cast<IPlayerPickupVPhysics *>(pPickedUpObject); if ( pPickup ) { return pPickup->OnFailedPhysGunPickup( vPhysgunPos ); } return NULL; } bool Pickup_GetPreferredCarryAngles( CBaseEntity *pObject, CBasePlayer *pPlayer, matrix3x4_t &localToWorld, QAngle &outputAnglesWorldSpace ) { IPlayerPickupVPhysics *pPickup = dynamic_cast<IPlayerPickupVPhysics *>(pObject); if ( pPickup ) { if ( pPickup->HasPreferredCarryAnglesForPlayer( pPlayer ) ) { outputAnglesWorldSpace = TransformAnglesToWorldSpace( pPickup->PreferredCarryAngles(), localToWorld ); return true; } } return false; } bool Pickup_ForcePhysGunOpen( CBaseEntity *pObject, CBasePlayer *pPlayer ) { IPlayerPickupVPhysics *pPickup = dynamic_cast<IPlayerPickupVPhysics *>(pObject); if ( pPickup ) { return pPickup->ForcePhysgunOpen( pPlayer ); } return false; } AngularImpulse Pickup_PhysGunLaunchAngularImpulse( CBaseEntity *pObject, PhysGunForce_t reason ) { IPlayerPickupVPhysics *pPickup = dynamic_cast<IPlayerPickupVPhysics *>(pObject); if ( pPickup != NULL && pPickup->ShouldPuntUseLaunchForces( reason ) ) { return pPickup->PhysGunLaunchAngularImpulse(); } return RandomAngularImpulse( -600, 600 ); } Vector Pickup_DefaultPhysGunLaunchVelocity( const Vector &vecForward, float flMass ) { #if defined( HL2_DLL ) && defined( TF_CLASSIC ) // Calculate the velocity based on physcannon rules float flForceMax = physcannon_maxforce.GetFloat(); float flForce = flForceMax; float mass = flMass; if ( mass > 100 ) { mass = MIN( mass, 1000 ); float flForceMin = physcannon_minforce.GetFloat(); flForce = SimpleSplineRemapValClamped( mass, 100, 600, flForceMax, flForceMin ); } return ( vecForward * flForce ); #endif // Do the simple calculation return ( vecForward * flMass ); } Vector Pickup_PhysGunLaunchVelocity( CBaseEntity *pObject, const Vector &vecForward, PhysGunForce_t reason ) { // The object must be valid if ( pObject == NULL ) { Assert( 0 ); return vec3_origin; } // Shouldn't ever get here with a non-vphysics object. IPhysicsObject *pPhysicsObject = pObject->VPhysicsGetObject(); if ( pPhysicsObject == NULL ) { Assert( 0 ); return vec3_origin; } // Call the pickup entity's callback IPlayerPickupVPhysics *pPickup = dynamic_cast<IPlayerPickupVPhysics *>(pObject); if ( pPickup != NULL && pPickup->ShouldPuntUseLaunchForces( reason ) ) return pPickup->PhysGunLaunchVelocity( vecForward, pPhysicsObject->GetMass() ); // Do our default behavior return Pickup_DefaultPhysGunLaunchVelocity( vecForward, pPhysicsObject->GetMass() ); } bool Pickup_ShouldPuntUseLaunchForces( CBaseEntity *pObject, PhysGunForce_t reason ) { IPlayerPickupVPhysics *pPickup = dynamic_cast<IPlayerPickupVPhysics *>(pObject); if ( pPickup ) { return pPickup->ShouldPuntUseLaunchForces( reason ); } return false; }
27.687179
140
0.724949
bluedogz162
a39d62766849e91d7c9bf3c30f60acb1816208c7
11,133
cpp
C++
ProceduralTerrainGen/Plugins/RuntimeMeshComponent/Intermediate/Build/Win32/UE4/Inc/RuntimeMeshComponent/RuntimeMeshModifierNormals.gen.cpp
RFornalik/ProceduralTerrain
017b8df6606eef242a399192518dcd9ebd3bbcc9
[ "MIT" ]
null
null
null
ProceduralTerrainGen/Plugins/RuntimeMeshComponent/Intermediate/Build/Win32/UE4/Inc/RuntimeMeshComponent/RuntimeMeshModifierNormals.gen.cpp
RFornalik/ProceduralTerrain
017b8df6606eef242a399192518dcd9ebd3bbcc9
[ "MIT" ]
null
null
null
ProceduralTerrainGen/Plugins/RuntimeMeshComponent/Intermediate/Build/Win32/UE4/Inc/RuntimeMeshComponent/RuntimeMeshModifierNormals.gen.cpp
RFornalik/ProceduralTerrain
017b8df6606eef242a399192518dcd9ebd3bbcc9
[ "MIT" ]
null
null
null
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "RuntimeMeshComponent/Public/Modifiers/RuntimeMeshModifierNormals.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeRuntimeMeshModifierNormals() {} // Cross Module References RUNTIMEMESHCOMPONENT_API UClass* Z_Construct_UClass_URuntimeMeshModifierNormals_NoRegister(); RUNTIMEMESHCOMPONENT_API UClass* Z_Construct_UClass_URuntimeMeshModifierNormals(); RUNTIMEMESHCOMPONENT_API UClass* Z_Construct_UClass_URuntimeMeshModifier(); UPackage* Z_Construct_UPackage__Script_RuntimeMeshComponent(); RUNTIMEMESHCOMPONENT_API UScriptStruct* Z_Construct_UScriptStruct_FRuntimeMeshRenderableMeshData(); // End Cross Module References DEFINE_FUNCTION(URuntimeMeshModifierNormals::execCalculateNormalsTangents) { P_GET_STRUCT_REF(FRuntimeMeshRenderableMeshData,Z_Param_Out_MeshData); P_GET_UBOOL(Z_Param_bInComputeSmoothNormals); P_FINISH; P_NATIVE_BEGIN; URuntimeMeshModifierNormals::CalculateNormalsTangents(Z_Param_Out_MeshData,Z_Param_bInComputeSmoothNormals); P_NATIVE_END; } void URuntimeMeshModifierNormals::StaticRegisterNativesURuntimeMeshModifierNormals() { UClass* Class = URuntimeMeshModifierNormals::StaticClass(); static const FNameNativePtrPair Funcs[] = { { "CalculateNormalsTangents", &URuntimeMeshModifierNormals::execCalculateNormalsTangents }, }; FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, UE_ARRAY_COUNT(Funcs)); } struct Z_Construct_UFunction_URuntimeMeshModifierNormals_CalculateNormalsTangents_Statics { struct RuntimeMeshModifierNormals_eventCalculateNormalsTangents_Parms { FRuntimeMeshRenderableMeshData MeshData; bool bInComputeSmoothNormals; }; static void NewProp_bInComputeSmoothNormals_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bInComputeSmoothNormals; static const UE4CodeGen_Private::FStructPropertyParams NewProp_MeshData; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; void Z_Construct_UFunction_URuntimeMeshModifierNormals_CalculateNormalsTangents_Statics::NewProp_bInComputeSmoothNormals_SetBit(void* Obj) { ((RuntimeMeshModifierNormals_eventCalculateNormalsTangents_Parms*)Obj)->bInComputeSmoothNormals = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_URuntimeMeshModifierNormals_CalculateNormalsTangents_Statics::NewProp_bInComputeSmoothNormals = { "bInComputeSmoothNormals", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(RuntimeMeshModifierNormals_eventCalculateNormalsTangents_Parms), &Z_Construct_UFunction_URuntimeMeshModifierNormals_CalculateNormalsTangents_Statics::NewProp_bInComputeSmoothNormals_SetBit, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_URuntimeMeshModifierNormals_CalculateNormalsTangents_Statics::NewProp_MeshData = { "MeshData", nullptr, (EPropertyFlags)0x0010000000000180, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(RuntimeMeshModifierNormals_eventCalculateNormalsTangents_Parms, MeshData), Z_Construct_UScriptStruct_FRuntimeMeshRenderableMeshData, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_URuntimeMeshModifierNormals_CalculateNormalsTangents_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_URuntimeMeshModifierNormals_CalculateNormalsTangents_Statics::NewProp_bInComputeSmoothNormals, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_URuntimeMeshModifierNormals_CalculateNormalsTangents_Statics::NewProp_MeshData, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_URuntimeMeshModifierNormals_CalculateNormalsTangents_Statics::Function_MetaDataParams[] = { { "Category", "RuntimeMesh|Modifiers|Normals" }, { "CPP_Default_bInComputeSmoothNormals", "false" }, { "ModuleRelativePath", "Public/Modifiers/RuntimeMeshModifierNormals.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_URuntimeMeshModifierNormals_CalculateNormalsTangents_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_URuntimeMeshModifierNormals, nullptr, "CalculateNormalsTangents", nullptr, nullptr, sizeof(RuntimeMeshModifierNormals_eventCalculateNormalsTangents_Parms), Z_Construct_UFunction_URuntimeMeshModifierNormals_CalculateNormalsTangents_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_URuntimeMeshModifierNormals_CalculateNormalsTangents_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04422401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_URuntimeMeshModifierNormals_CalculateNormalsTangents_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_URuntimeMeshModifierNormals_CalculateNormalsTangents_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_URuntimeMeshModifierNormals_CalculateNormalsTangents() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_URuntimeMeshModifierNormals_CalculateNormalsTangents_Statics::FuncParams); } return ReturnFunction; } UClass* Z_Construct_UClass_URuntimeMeshModifierNormals_NoRegister() { return URuntimeMeshModifierNormals::StaticClass(); } struct Z_Construct_UClass_URuntimeMeshModifierNormals_Statics { static UObject* (*const DependentSingletons[])(); static const FClassFunctionLinkInfo FuncInfo[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bComputeSmoothNormals_MetaData[]; #endif static void NewProp_bComputeSmoothNormals_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bComputeSmoothNormals; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_URuntimeMeshModifierNormals_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_URuntimeMeshModifier, (UObject* (*)())Z_Construct_UPackage__Script_RuntimeMeshComponent, }; const FClassFunctionLinkInfo Z_Construct_UClass_URuntimeMeshModifierNormals_Statics::FuncInfo[] = { { &Z_Construct_UFunction_URuntimeMeshModifierNormals_CalculateNormalsTangents, "CalculateNormalsTangents" }, // 1798533073 }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_URuntimeMeshModifierNormals_Statics::Class_MetaDataParams[] = { { "BlueprintType", "true" }, { "HideCategories", "Object Object" }, { "IncludePath", "Modifiers/RuntimeMeshModifierNormals.h" }, { "IsBlueprintBase", "true" }, { "ModuleRelativePath", "Public/Modifiers/RuntimeMeshModifierNormals.h" }, { "ShortTooltip", "A RuntimeMeshModifierNormals is a class that implements logic to generate normals and tangents for a supplied mesh." }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_URuntimeMeshModifierNormals_Statics::NewProp_bComputeSmoothNormals_MetaData[] = { { "Category", "RuntimeMesh|Modifiers|Normals" }, { "ModuleRelativePath", "Public/Modifiers/RuntimeMeshModifierNormals.h" }, }; #endif void Z_Construct_UClass_URuntimeMeshModifierNormals_Statics::NewProp_bComputeSmoothNormals_SetBit(void* Obj) { ((URuntimeMeshModifierNormals*)Obj)->bComputeSmoothNormals = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_URuntimeMeshModifierNormals_Statics::NewProp_bComputeSmoothNormals = { "bComputeSmoothNormals", nullptr, (EPropertyFlags)0x0010000000020005, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(URuntimeMeshModifierNormals), &Z_Construct_UClass_URuntimeMeshModifierNormals_Statics::NewProp_bComputeSmoothNormals_SetBit, METADATA_PARAMS(Z_Construct_UClass_URuntimeMeshModifierNormals_Statics::NewProp_bComputeSmoothNormals_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_URuntimeMeshModifierNormals_Statics::NewProp_bComputeSmoothNormals_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_URuntimeMeshModifierNormals_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_URuntimeMeshModifierNormals_Statics::NewProp_bComputeSmoothNormals, }; const FCppClassTypeInfoStatic Z_Construct_UClass_URuntimeMeshModifierNormals_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<URuntimeMeshModifierNormals>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_URuntimeMeshModifierNormals_Statics::ClassParams = { &URuntimeMeshModifierNormals::StaticClass, nullptr, &StaticCppClassTypeInfo, DependentSingletons, FuncInfo, Z_Construct_UClass_URuntimeMeshModifierNormals_Statics::PropPointers, nullptr, UE_ARRAY_COUNT(DependentSingletons), UE_ARRAY_COUNT(FuncInfo), UE_ARRAY_COUNT(Z_Construct_UClass_URuntimeMeshModifierNormals_Statics::PropPointers), 0, 0x001000A0u, METADATA_PARAMS(Z_Construct_UClass_URuntimeMeshModifierNormals_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_URuntimeMeshModifierNormals_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_URuntimeMeshModifierNormals() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_URuntimeMeshModifierNormals_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(URuntimeMeshModifierNormals, 114252792); template<> RUNTIMEMESHCOMPONENT_API UClass* StaticClass<URuntimeMeshModifierNormals>() { return URuntimeMeshModifierNormals::StaticClass(); } static FCompiledInDefer Z_CompiledInDefer_UClass_URuntimeMeshModifierNormals(Z_Construct_UClass_URuntimeMeshModifierNormals, &URuntimeMeshModifierNormals::StaticClass, TEXT("/Script/RuntimeMeshComponent"), TEXT("URuntimeMeshModifierNormals"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(URuntimeMeshModifierNormals); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
65.105263
870
0.849367
RFornalik
a3a07102ec9623d69ab1c2e460f30f78d3156db4
2,919
cpp
C++
lonestar/experimental/meshsingularities/Productions/Point3D/main.cpp
lineagech/Galois
5c7c0abaf7253cb354e35a3836147a960a37ad5b
[ "BSD-3-Clause" ]
null
null
null
lonestar/experimental/meshsingularities/Productions/Point3D/main.cpp
lineagech/Galois
5c7c0abaf7253cb354e35a3836147a960a37ad5b
[ "BSD-3-Clause" ]
null
null
null
lonestar/experimental/meshsingularities/Productions/Point3D/main.cpp
lineagech/Galois
5c7c0abaf7253cb354e35a3836147a960a37ad5b
[ "BSD-3-Clause" ]
null
null
null
/* * This file belongs to the Galois project, a C++ library for exploiting * parallelism. The code is being released under the terms of the 3-Clause BSD * License (a copy is located in LICENSE.txt at the top-level directory). * * Copyright (C) 2018, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. */ #include <stdio.h> #include "MatrixGenerator.hxx" #include <map> #include <time.h> #include <map> #include "../EquationSystem.h" using namespace D3; double test_function(int dim, ...) { double* data = new double[dim]; double result = 0; va_list args; va_start(args, dim); for (int i = 0; i < dim; ++i) { data[i] = va_arg(args, double); } va_end(args); if (dim == 3) { double x = data[0]; double y = data[1]; double z = data[2]; result = 3 * x * x + 2 * y * y + z * z + x * y * z + x * x * z + y * y + 2 * x * x * y * y * z * z; } else { result = -1; } delete[] data; return result; } int main(int argc, char** argv) { int nrOfTiers = 4; int i = 0; GenericMatrixGenerator* matrixGenerator = new MatrixGenerator(); TaskDescription taskDescription; taskDescription.dimensions = 3; taskDescription.nrOfTiers = 4; taskDescription.size = 1; taskDescription.function = test_function; taskDescription.x = -1; taskDescription.y = -1; taskDescription.z = -1; std::vector<EquationSystem*>* tiers = matrixGenerator->CreateMatrixAndRhs(taskDescription); EquationSystem* globalSystem = new EquationSystem( matrixGenerator->GetMatrix(), matrixGenerator->GetRhs(), matrixGenerator->GetMatrixSize()); globalSystem->eliminate(matrixGenerator->GetMatrixSize()); globalSystem->backwardSubstitute(matrixGenerator->GetMatrixSize() - 1); std::map<int, double>* result_map = new std::map<int, double>(); for (int i = 0; i < matrixGenerator->GetMatrixSize(); i++) { (*result_map)[i] = globalSystem->rhs[i]; } matrixGenerator->checkSolution(result_map, test_function); delete matrixGenerator; delete result_map; return 0; }
33.170455
79
0.689277
lineagech
a3a208ca97557248d7a4b53eec435789d8d28700
537
cc
C++
base/init.cc
xiaoqiyu/CTPTrader
7423b8cb012e31f16c39b5055792886b39b11251
[ "Apache-2.0" ]
142
2017-06-14T11:39:55.000Z
2022-03-20T15:08:39.000Z
base/init.cc
xiaoqiyu/DERIQT
57c20c40a692a4f877296a39ed91aeab8e4c6d66
[ "Apache-2.0" ]
17
2015-07-13T02:37:55.000Z
2017-05-02T07:12:33.000Z
base/init.cc
xiaoqiyu/DERIQT
57c20c40a692a4f877296a39ed91aeab8e4c6d66
[ "Apache-2.0" ]
54
2015-04-20T07:27:43.000Z
2017-04-27T21:17:32.000Z
#include "base/init.h" #include "absl/debugging/failure_signal_handler.h" #include "absl/debugging/symbolize.h" #include "absl/flags/parse.h" #include "glog/logging.h" namespace base { void InitProgram(int argc, char *argv[]) { // Initialize the symbolizer to get a human-readable stack trace absl::InitializeSymbolizer(argv[0]); absl::FailureSignalHandlerOptions options; absl::InstallFailureSignalHandler(options); absl::ParseCommandLine(argc, argv); google::InitGoogleLogging(argv[0]); } } // namespace base
25.571429
66
0.743017
xiaoqiyu
a3a252e51737b84ad789f78ae4001110b4e2d5f6
7,781
hpp
C++
libraries/chain/include/eosio/chain/exceptions.hpp
camielvanramele/Graduation-Internship
ab0e9b8db65b775459ddb3cb813e8e51b55ad1d1
[ "MIT" ]
2
2021-08-19T03:03:45.000Z
2021-08-19T03:04:46.000Z
libraries/chain/include/eosio/chain/exceptions.hpp
ElementhFoundation/blockchain
5f63038c0e6fc90bc4bc0bc576410087785d8099
[ "MIT" ]
null
null
null
libraries/chain/include/eosio/chain/exceptions.hpp
ElementhFoundation/blockchain
5f63038c0e6fc90bc4bc0bc576410087785d8099
[ "MIT" ]
null
null
null
/** * @file * @copyright defined in eos/LICENSE.txt */ #pragma once #include <fc/exception/exception.hpp> #include <eosio/chain/protocol.hpp> #include <eosio/utilities/exception_macros.hpp> namespace eosio { namespace chain { FC_DECLARE_EXCEPTION( chain_exception, 3000000, "blockchain exception" ) FC_DECLARE_DERIVED_EXCEPTION( database_query_exception, eosio::chain::chain_exception, 3010000, "database query exception" ) FC_DECLARE_DERIVED_EXCEPTION( block_validate_exception, eosio::chain::chain_exception, 3020000, "block validation exception" ) FC_DECLARE_DERIVED_EXCEPTION( transaction_exception, eosio::chain::chain_exception, 3030000, "transaction validation exception" ) FC_DECLARE_DERIVED_EXCEPTION( action_validate_exception, eosio::chain::chain_exception, 3040000, "message validation exception" ) FC_DECLARE_DERIVED_EXCEPTION( utility_exception, eosio::chain::chain_exception, 3070000, "utility method exception" ) FC_DECLARE_DERIVED_EXCEPTION( undo_database_exception, eosio::chain::chain_exception, 3080000, "undo database exception" ) FC_DECLARE_DERIVED_EXCEPTION( unlinkable_block_exception, eosio::chain::chain_exception, 3090000, "unlinkable block" ) FC_DECLARE_DERIVED_EXCEPTION( black_swan_exception, eosio::chain::chain_exception, 3100000, "black swan" ) FC_DECLARE_DERIVED_EXCEPTION( unknown_block_exception, eosio::chain::chain_exception, 3110000, "unknown block" ) FC_DECLARE_DERIVED_EXCEPTION( chain_type_exception, eosio::chain::chain_exception, 3120000, "chain type exception" ) FC_DECLARE_DERIVED_EXCEPTION( missing_plugin_exception, eosio::chain::chain_exception, 3130000, "missing plugin exception" ) FC_DECLARE_DERIVED_EXCEPTION( permission_query_exception, eosio::chain::database_query_exception, 3010001, "permission query exception" ) FC_DECLARE_DERIVED_EXCEPTION( block_tx_output_exception, eosio::chain::block_validate_exception, 3020001, "transaction outputs in block do not match transaction outputs from applying block" ) FC_DECLARE_DERIVED_EXCEPTION( block_concurrency_exception, eosio::chain::block_validate_exception, 3020002, "block does not guarantee concurrent exection without conflicts" ) FC_DECLARE_DERIVED_EXCEPTION( block_lock_exception, eosio::chain::block_validate_exception, 3020003, "shard locks in block are incorrect or mal-formed" ) FC_DECLARE_DERIVED_EXCEPTION( tx_missing_auth, eosio::chain::transaction_exception, 3030001, "missing required authority" ) FC_DECLARE_DERIVED_EXCEPTION( tx_missing_sigs, eosio::chain::transaction_exception, 3030002, "signatures do not satisfy declared authorizations" ) FC_DECLARE_DERIVED_EXCEPTION( tx_irrelevant_auth, eosio::chain::transaction_exception, 3030003, "irrelevant authority included" ) FC_DECLARE_DERIVED_EXCEPTION( tx_irrelevant_sig, eosio::chain::transaction_exception, 3030004, "irrelevant signature included" ) FC_DECLARE_DERIVED_EXCEPTION( tx_duplicate_sig, eosio::chain::transaction_exception, 3030005, "duplicate signature included" ) FC_DECLARE_DERIVED_EXCEPTION( invalid_committee_approval, eosio::chain::transaction_exception, 3030006, "committee account cannot directly approve transaction" ) FC_DECLARE_DERIVED_EXCEPTION( insufficient_fee, eosio::chain::transaction_exception, 3030007, "insufficient fee" ) FC_DECLARE_DERIVED_EXCEPTION( tx_missing_recipient, eosio::chain::transaction_exception, 3030009, "missing required recipient" ) FC_DECLARE_DERIVED_EXCEPTION( checktime_exceeded, eosio::chain::transaction_exception, 3030010, "allotted processing time was exceeded" ) FC_DECLARE_DERIVED_EXCEPTION( tx_duplicate, eosio::chain::transaction_exception, 3030011, "duplicate transaction" ) FC_DECLARE_DERIVED_EXCEPTION( unknown_transaction_exception, eosio::chain::transaction_exception, 3030012, "unknown transaction" ) FC_DECLARE_DERIVED_EXCEPTION( tx_scheduling_exception, eosio::chain::transaction_exception, 3030013, "transaction failed during sheduling" ) FC_DECLARE_DERIVED_EXCEPTION( tx_unknown_argument, eosio::chain::transaction_exception, 3030014, "transaction provided an unknown value to a system call" ) FC_DECLARE_DERIVED_EXCEPTION( tx_resource_exhausted, eosio::chain::transaction_exception, 3030015, "transaction exhausted allowed resources" ) FC_DECLARE_DERIVED_EXCEPTION( page_memory_error, eosio::chain::transaction_exception, 3030016, "error in WASM page memory" ) FC_DECLARE_DERIVED_EXCEPTION( unsatisfied_permission, eosio::chain::transaction_exception, 3030017, "Unsatisfied permission" ) FC_DECLARE_DERIVED_EXCEPTION( tx_msgs_auth_exceeded, eosio::chain::transaction_exception, 3030018, "Number of transaction messages per authorized account has been exceeded" ) FC_DECLARE_DERIVED_EXCEPTION( tx_msgs_code_exceeded, eosio::chain::transaction_exception, 3030019, "Number of transaction messages per code account has been exceeded" ) FC_DECLARE_DERIVED_EXCEPTION( wasm_execution_error, eosio::chain::transaction_exception, 3030020, "Runtime Error Processing WASM" ) FC_DECLARE_DERIVED_EXCEPTION( tx_decompression_error, eosio::chain::transaction_exception, 3030020, "Error decompressing transaction" ) FC_DECLARE_DERIVED_EXCEPTION( account_name_exists_exception, eosio::chain::action_validate_exception, 3040001, "account name already exists" ) FC_DECLARE_DERIVED_EXCEPTION( invalid_pts_address, eosio::chain::utility_exception, 3060001, "invalid pts address" ) FC_DECLARE_DERIVED_EXCEPTION( insufficient_feeds, eosio::chain::chain_exception, 37006, "insufficient feeds" ) FC_DECLARE_DERIVED_EXCEPTION( pop_empty_chain, eosio::chain::undo_database_exception, 3070001, "there are no blocks to pop" ) FC_DECLARE_DERIVED_EXCEPTION( name_type_exception, eosio::chain::chain_type_exception, 3120001, "Invalid name" ) FC_DECLARE_DERIVED_EXCEPTION( public_key_type_exception, eosio::chain::chain_type_exception, 3120002, "Invalid public key" ) FC_DECLARE_DERIVED_EXCEPTION( authority_type_exception, eosio::chain::chain_type_exception, 3120003, "Invalid authority" ) FC_DECLARE_DERIVED_EXCEPTION( action_type_exception, eosio::chain::chain_type_exception, 3120004, "Invalid action" ) FC_DECLARE_DERIVED_EXCEPTION( transaction_type_exception, eosio::chain::chain_type_exception, 3120005, "Invalid transaction" ) FC_DECLARE_DERIVED_EXCEPTION( abi_type_exception, eosio::chain::chain_type_exception, 3120006, "Invalid ABI" ) FC_DECLARE_DERIVED_EXCEPTION( missing_chain_api_plugin_exception, eosio::chain::missing_plugin_exception, 3130001, "Missing Chain API Plugin" ) FC_DECLARE_DERIVED_EXCEPTION( missing_wallet_api_plugin_exception, eosio::chain::missing_plugin_exception, 3130002, "Missing Wallet API Plugin" ) FC_DECLARE_DERIVED_EXCEPTION( missing_account_history_api_plugin_exception, eosio::chain::missing_plugin_exception, 3130003, "Missing Account History API Plugin" ) FC_DECLARE_DERIVED_EXCEPTION( missing_net_api_plugin_exception, eosio::chain::missing_plugin_exception, 3130003, "Missing Net API Plugin" ) #define EOS_RECODE_EXC( cause_type, effect_type ) \ catch( const cause_type& e ) \ { throw( effect_type( e.what(), e.get_log() ) ); } } } // eosio::chain
101.051948
202
0.7589
camielvanramele
a3a8b302709dcb5b523a845731f2a60ffaafbc7e
3,769
cpp
C++
test/external_contribution/CopyPipelineHigh6/Pack8to1/Pack8to1_genx.cpp
dmitryryintel/cm-compiler
1ef7651dc1c33d3e4853f8779d6a720e45e20e19
[ "Intel", "MIT" ]
115
2018-02-01T18:56:44.000Z
2022-03-21T13:23:00.000Z
test/external_contribution/CopyPipelineHigh6/Pack8to1/Pack8to1_genx.cpp
dmitryryintel/cm-compiler
1ef7651dc1c33d3e4853f8779d6a720e45e20e19
[ "Intel", "MIT" ]
27
2018-09-17T17:49:49.000Z
2021-11-03T04:31:51.000Z
test/external_contribution/CopyPipelineHigh6/Pack8to1/Pack8to1_genx.cpp
dmitryryintel/cm-compiler
1ef7651dc1c33d3e4853f8779d6a720e45e20e19
[ "Intel", "MIT" ]
55
2018-02-01T07:11:49.000Z
2022-03-04T01:20:23.000Z
/* * Copyright (c) 2017, Intel Corporation * * 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 <cm/cm.h> #include <cm/cmtl.h> #define BLKW 16 #define BLKH 16 #define X 0 #define Y 1 inline _GENX_ void Pack8to1 ( matrix_ref<uchar, 16, 16> in, matrix_ref<uchar, 16, 2> out ) { matrix<uchar, 16, 16> transposed_in; cmtl::Transpose_16x16(in.select_all(), transposed_in.select_all()); #pragma unroll for (int j = 0; j < 2; j++) { out.select<16,1,1,1>(0,j) = (transposed_in.row(0+j*8) & 0x80) >> 0 | (transposed_in.row(1+j*8) & 0x80) >> 1 | (transposed_in.row(2+j*8) & 0x80) >> 2 | (transposed_in.row(3+j*8) & 0x80) >> 3 | (transposed_in.row(4+j*8) & 0x80) >> 4 | (transposed_in.row(5+j*8) & 0x80) >> 5 | (transposed_in.row(6+j*8) & 0x80) >> 6 | (transposed_in.row(7+j*8) & 0x80) >> 7; } } extern "C" _GENX_MAIN_ void Pack8to1_4C_GENX( SurfaceIndex SrcSI, SurfaceIndex DstCSI, SurfaceIndex DstMSI, SurfaceIndex DstYSI, SurfaceIndex DstKSI ) { matrix<uchar, BLKH, BLKW * 4> cmykIn; vector<short, 2> pos, pos4, posout; pos(X) = cm_local_id(X) + cm_group_id(X) * cm_local_size(X); pos(Y) = cm_local_id(Y) + cm_group_id(Y) * cm_local_size(Y); // Even through the block size is 16x16, but as two loops, the actual block // size is 32x16 pos4(X) = pos(X) * 32 * 4; pos4(Y) = pos(Y) * BLKH; posout(X) = pos(X) * 4; pos(X) = pos(X) * 32; pos(Y) = pos(Y) * BLKH; matrix<uchar, BLKH, 2> out1bit; matrix<uchar, BLKH, 4> outC1bit, outM1bit, outY1bit; #pragma unroll for (int loop = 0; loop < 2; loop++) { read(SrcSI, pos4(X), pos4(Y), cmykIn.select<8,1,32,1>(0,0)); read(SrcSI, pos4(X)+32, pos4(Y), cmykIn.select<8,1,32,1>(0,32)); read(SrcSI, pos4(X), pos4(Y)+8, cmykIn.select<8,1,32,1>(8,0)); read(SrcSI, pos4(X)+32, pos4(Y)+8, cmykIn.select<8,1,32,1>(8,32)); matrix<uchar,BLKH, BLKW> kinput(cmykIn.select<16,1,16,4>(0,3)); matrix<uchar,BLKH, BLKW> yinput(cmykIn.select<16,1,16,4>(0,2)); matrix<uchar,BLKH, BLKW> minput(cmykIn.select<16,1,16,4>(0,1)); matrix<uchar,BLKH, BLKW> cinput(cmykIn.select<16,1,16,4>(0,0)); Pack8to1(cinput, out1bit); outC1bit.select<16,1,2,1>(0,loop*2) = out1bit; Pack8to1(minput, out1bit); outM1bit.select<16,1,2,1>(0,loop*2) = out1bit; Pack8to1(yinput, out1bit); outY1bit.select<16,1,2,1>(0,loop*2) = out1bit; write(DstKSI, pos(X), pos(Y), kinput); pos4(X) += 64; pos(X) += 16; } write(DstCSI, posout(X), pos(Y), outC1bit); write(DstMSI, posout(X), pos(Y), outM1bit); write(DstYSI, posout(X), pos(Y), outY1bit); }
32.773913
78
0.639958
dmitryryintel
a3aa9c1f95ce6f2ab2cc35d15be7bda7ee413957
27,578
cpp
C++
doc/cppnow-2016/example/mpl_at.cpp
GuiCodron/sml
2dab1265f87f70a2941af9de8f3f157df9a6a53f
[ "BSL-1.0" ]
320
2020-07-03T18:58:34.000Z
2022-03-31T05:31:44.000Z
doc/cppnow-2016/example/mpl_at.cpp
GuiCodron/sml
2dab1265f87f70a2941af9de8f3f157df9a6a53f
[ "BSL-1.0" ]
106
2020-06-30T15:03:00.000Z
2022-03-31T10:42:38.000Z
doc/cppnow-2016/example/mpl_at.cpp
GuiCodron/sml
2dab1265f87f70a2941af9de8f3f157df9a6a53f
[ "BSL-1.0" ]
55
2020-07-10T12:32:49.000Z
2022-03-14T07:12:28.000Z
// // Copyright (c) 2016-2019 Kris Jusiak (kris at jusiak dot net) // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #define BOOST_MPL_LIMIT_MAP_SIZE 128 #include <boost/preprocessor/iterate.hpp> #include <boost/mpl/map/map50.hpp> namespace boost { namespace mpl { // clang-format off #define BOOST_PP_ITERATION_PARAMS_1 \ (3, (51, BOOST_MPL_LIMIT_MAP_SIZE, <boost/mpl/map/aux_/numbered.hpp>)) #include BOOST_PP_ITERATE() // clang-format on } // namespace mpl } // namespace boost #define BOOST_MPL_PREPROCESSING_MODE #include <boost/mpl/map.hpp> #undef BOOST_MPL_PREPROCESSING_MODE #include <boost/mpl/map.hpp> #include <boost/mpl/at.hpp> namespace mpl = boost::mpl; using m = mpl::map<mpl::pair<mpl::int_<1>, mpl::int_<1>>, mpl::pair<mpl::int_<2>, mpl::int_<2>>, mpl::pair<mpl::int_<3>, mpl::int_<3>>, mpl::pair<mpl::int_<4>, mpl::int_<4>>, mpl::pair<mpl::int_<5>, mpl::int_<5>>, mpl::pair<mpl::int_<6>, mpl::int_<6>>, mpl::pair<mpl::int_<7>, mpl::int_<7>>, mpl::pair<mpl::int_<8>, mpl::int_<8>>, mpl::pair<mpl::int_<9>, mpl::int_<9>>, mpl::pair<mpl::int_<10>, mpl::int_<10>>, mpl::pair<mpl::int_<11>, mpl::int_<11>>, mpl::pair<mpl::int_<12>, mpl::int_<12>>, mpl::pair<mpl::int_<13>, mpl::int_<13>>, mpl::pair<mpl::int_<14>, mpl::int_<14>>, mpl::pair<mpl::int_<15>, mpl::int_<15>>, mpl::pair<mpl::int_<16>, mpl::int_<16>>, mpl::pair<mpl::int_<17>, mpl::int_<17>>, mpl::pair<mpl::int_<18>, mpl::int_<18>>, mpl::pair<mpl::int_<19>, mpl::int_<19>>, mpl::pair<mpl::int_<20>, mpl::int_<20>>, mpl::pair<mpl::int_<21>, mpl::int_<21>>, mpl::pair<mpl::int_<22>, mpl::int_<22>>, mpl::pair<mpl::int_<23>, mpl::int_<23>>, mpl::pair<mpl::int_<24>, mpl::int_<24>>, mpl::pair<mpl::int_<25>, mpl::int_<25>>, mpl::pair<mpl::int_<26>, mpl::int_<26>>, mpl::pair<mpl::int_<27>, mpl::int_<27>>, mpl::pair<mpl::int_<28>, mpl::int_<28>>, mpl::pair<mpl::int_<29>, mpl::int_<29>>, mpl::pair<mpl::int_<30>, mpl::int_<30>>, mpl::pair<mpl::int_<31>, mpl::int_<31>>, mpl::pair<mpl::int_<32>, mpl::int_<32>>, mpl::pair<mpl::int_<33>, mpl::int_<33>>, mpl::pair<mpl::int_<34>, mpl::int_<34>>, mpl::pair<mpl::int_<35>, mpl::int_<35>>, mpl::pair<mpl::int_<36>, mpl::int_<36>>, mpl::pair<mpl::int_<37>, mpl::int_<37>>, mpl::pair<mpl::int_<38>, mpl::int_<38>>, mpl::pair<mpl::int_<39>, mpl::int_<39>>, mpl::pair<mpl::int_<40>, mpl::int_<40>>, mpl::pair<mpl::int_<41>, mpl::int_<41>>, mpl::pair<mpl::int_<42>, mpl::int_<42>>, mpl::pair<mpl::int_<43>, mpl::int_<43>>, mpl::pair<mpl::int_<44>, mpl::int_<44>>, mpl::pair<mpl::int_<45>, mpl::int_<45>>, mpl::pair<mpl::int_<46>, mpl::int_<46>>, mpl::pair<mpl::int_<47>, mpl::int_<47>>, mpl::pair<mpl::int_<48>, mpl::int_<48>>, mpl::pair<mpl::int_<49>, mpl::int_<49>>, mpl::pair<mpl::int_<50>, mpl::int_<50>>, mpl::pair<mpl::int_<51>, mpl::int_<51>>, mpl::pair<mpl::int_<52>, mpl::int_<52>>, mpl::pair<mpl::int_<53>, mpl::int_<53>>, mpl::pair<mpl::int_<54>, mpl::int_<54>>, mpl::pair<mpl::int_<55>, mpl::int_<55>>, mpl::pair<mpl::int_<56>, mpl::int_<56>>, mpl::pair<mpl::int_<57>, mpl::int_<57>>, mpl::pair<mpl::int_<58>, mpl::int_<58>>, mpl::pair<mpl::int_<59>, mpl::int_<59>>, mpl::pair<mpl::int_<60>, mpl::int_<60>>, mpl::pair<mpl::int_<61>, mpl::int_<61>>, mpl::pair<mpl::int_<62>, mpl::int_<62>>, mpl::pair<mpl::int_<63>, mpl::int_<63>>, mpl::pair<mpl::int_<64>, mpl::int_<64>>, mpl::pair<mpl::int_<65>, mpl::int_<65>>, mpl::pair<mpl::int_<66>, mpl::int_<66>>, mpl::pair<mpl::int_<67>, mpl::int_<67>>, mpl::pair<mpl::int_<68>, mpl::int_<68>>, mpl::pair<mpl::int_<69>, mpl::int_<69>>, mpl::pair<mpl::int_<70>, mpl::int_<70>>, mpl::pair<mpl::int_<71>, mpl::int_<71>>, mpl::pair<mpl::int_<72>, mpl::int_<72>>, mpl::pair<mpl::int_<73>, mpl::int_<73>>, mpl::pair<mpl::int_<74>, mpl::int_<74>>, mpl::pair<mpl::int_<75>, mpl::int_<75>>, mpl::pair<mpl::int_<76>, mpl::int_<76>>, mpl::pair<mpl::int_<77>, mpl::int_<77>>, mpl::pair<mpl::int_<78>, mpl::int_<78>>, mpl::pair<mpl::int_<79>, mpl::int_<79>>, mpl::pair<mpl::int_<80>, mpl::int_<80>>, mpl::pair<mpl::int_<81>, mpl::int_<81>>, mpl::pair<mpl::int_<82>, mpl::int_<82>>, mpl::pair<mpl::int_<83>, mpl::int_<83>>, mpl::pair<mpl::int_<84>, mpl::int_<84>>, mpl::pair<mpl::int_<85>, mpl::int_<85>>, mpl::pair<mpl::int_<86>, mpl::int_<86>>, mpl::pair<mpl::int_<87>, mpl::int_<87>>, mpl::pair<mpl::int_<88>, mpl::int_<88>>, mpl::pair<mpl::int_<89>, mpl::int_<89>>, mpl::pair<mpl::int_<90>, mpl::int_<90>>, mpl::pair<mpl::int_<91>, mpl::int_<91>>, mpl::pair<mpl::int_<92>, mpl::int_<92>>, mpl::pair<mpl::int_<93>, mpl::int_<93>>, mpl::pair<mpl::int_<94>, mpl::int_<94>>, mpl::pair<mpl::int_<95>, mpl::int_<95>>, mpl::pair<mpl::int_<96>, mpl::int_<96>>, mpl::pair<mpl::int_<97>, mpl::int_<97>>, mpl::pair<mpl::int_<98>, mpl::int_<98>>, mpl::pair<mpl::int_<99>, mpl::int_<99>>, mpl::pair<mpl::int_<100>, mpl::int_<100>>, mpl::pair<mpl::int_<101>, mpl::int_<101>>, mpl::pair<mpl::int_<102>, mpl::int_<102>>, mpl::pair<mpl::int_<103>, mpl::int_<103>>, mpl::pair<mpl::int_<104>, mpl::int_<104>>, mpl::pair<mpl::int_<105>, mpl::int_<105>>, mpl::pair<mpl::int_<106>, mpl::int_<106>>, mpl::pair<mpl::int_<107>, mpl::int_<107>>, mpl::pair<mpl::int_<108>, mpl::int_<108>>, mpl::pair<mpl::int_<109>, mpl::int_<109>>, mpl::pair<mpl::int_<110>, mpl::int_<110>>, mpl::pair<mpl::int_<111>, mpl::int_<111>>, mpl::pair<mpl::int_<112>, mpl::int_<112>>, mpl::pair<mpl::int_<113>, mpl::int_<113>>, mpl::pair<mpl::int_<114>, mpl::int_<114>>, mpl::pair<mpl::int_<115>, mpl::int_<115>>, mpl::pair<mpl::int_<116>, mpl::int_<116>>, mpl::pair<mpl::int_<117>, mpl::int_<117>>, mpl::pair<mpl::int_<118>, mpl::int_<118>>, mpl::pair<mpl::int_<119>, mpl::int_<119>>, mpl::pair<mpl::int_<120>, mpl::int_<120>>, mpl::pair<mpl::int_<121>, mpl::int_<121>>, mpl::pair<mpl::int_<122>, mpl::int_<122>>, mpl::pair<mpl::int_<123>, mpl::int_<123>>, mpl::pair<mpl::int_<124>, mpl::int_<124>>, mpl::pair<mpl::int_<125>, mpl::int_<125>>, mpl::pair<mpl::int_<126>, mpl::int_<126>>, mpl::pair<mpl::int_<127>, mpl::int_<127>>, mpl::pair<mpl::int_<128>, mpl::int_<128>>>; template <class> struct q; int main() { static_assert(boost::is_same<typename mpl::at<m, mpl::int_<1>>::type, mpl::int_<1>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<2>>::type, mpl::int_<2>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<3>>::type, mpl::int_<3>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<4>>::type, mpl::int_<4>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<5>>::type, mpl::int_<5>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<6>>::type, mpl::int_<6>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<7>>::type, mpl::int_<7>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<8>>::type, mpl::int_<8>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<9>>::type, mpl::int_<9>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<10>>::type, mpl::int_<10>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<11>>::type, mpl::int_<11>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<12>>::type, mpl::int_<12>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<13>>::type, mpl::int_<13>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<14>>::type, mpl::int_<14>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<15>>::type, mpl::int_<15>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<16>>::type, mpl::int_<16>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<17>>::type, mpl::int_<17>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<18>>::type, mpl::int_<18>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<19>>::type, mpl::int_<19>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<20>>::type, mpl::int_<20>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<21>>::type, mpl::int_<21>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<22>>::type, mpl::int_<22>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<23>>::type, mpl::int_<23>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<24>>::type, mpl::int_<24>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<25>>::type, mpl::int_<25>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<26>>::type, mpl::int_<26>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<27>>::type, mpl::int_<27>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<28>>::type, mpl::int_<28>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<29>>::type, mpl::int_<29>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<30>>::type, mpl::int_<30>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<31>>::type, mpl::int_<31>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<32>>::type, mpl::int_<32>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<33>>::type, mpl::int_<33>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<34>>::type, mpl::int_<34>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<35>>::type, mpl::int_<35>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<36>>::type, mpl::int_<36>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<37>>::type, mpl::int_<37>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<38>>::type, mpl::int_<38>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<39>>::type, mpl::int_<39>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<40>>::type, mpl::int_<40>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<41>>::type, mpl::int_<41>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<42>>::type, mpl::int_<42>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<43>>::type, mpl::int_<43>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<44>>::type, mpl::int_<44>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<45>>::type, mpl::int_<45>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<46>>::type, mpl::int_<46>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<47>>::type, mpl::int_<47>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<48>>::type, mpl::int_<48>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<49>>::type, mpl::int_<49>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<50>>::type, mpl::int_<50>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<51>>::type, mpl::int_<51>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<52>>::type, mpl::int_<52>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<53>>::type, mpl::int_<53>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<54>>::type, mpl::int_<54>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<55>>::type, mpl::int_<55>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<56>>::type, mpl::int_<56>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<57>>::type, mpl::int_<57>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<58>>::type, mpl::int_<58>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<59>>::type, mpl::int_<59>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<60>>::type, mpl::int_<60>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<61>>::type, mpl::int_<61>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<62>>::type, mpl::int_<62>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<63>>::type, mpl::int_<63>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<64>>::type, mpl::int_<64>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<65>>::type, mpl::int_<65>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<66>>::type, mpl::int_<66>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<67>>::type, mpl::int_<67>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<68>>::type, mpl::int_<68>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<69>>::type, mpl::int_<69>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<70>>::type, mpl::int_<70>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<71>>::type, mpl::int_<71>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<72>>::type, mpl::int_<72>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<73>>::type, mpl::int_<73>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<74>>::type, mpl::int_<74>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<75>>::type, mpl::int_<75>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<76>>::type, mpl::int_<76>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<77>>::type, mpl::int_<77>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<78>>::type, mpl::int_<78>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<79>>::type, mpl::int_<79>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<80>>::type, mpl::int_<80>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<81>>::type, mpl::int_<81>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<82>>::type, mpl::int_<82>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<83>>::type, mpl::int_<83>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<84>>::type, mpl::int_<84>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<85>>::type, mpl::int_<85>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<86>>::type, mpl::int_<86>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<87>>::type, mpl::int_<87>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<88>>::type, mpl::int_<88>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<89>>::type, mpl::int_<89>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<90>>::type, mpl::int_<90>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<91>>::type, mpl::int_<91>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<92>>::type, mpl::int_<92>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<93>>::type, mpl::int_<93>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<94>>::type, mpl::int_<94>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<95>>::type, mpl::int_<95>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<96>>::type, mpl::int_<96>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<97>>::type, mpl::int_<97>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<98>>::type, mpl::int_<98>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<99>>::type, mpl::int_<99>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<100>>::type, mpl::int_<100>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<101>>::type, mpl::int_<101>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<102>>::type, mpl::int_<102>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<103>>::type, mpl::int_<103>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<104>>::type, mpl::int_<104>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<105>>::type, mpl::int_<105>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<106>>::type, mpl::int_<106>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<107>>::type, mpl::int_<107>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<108>>::type, mpl::int_<108>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<109>>::type, mpl::int_<109>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<110>>::type, mpl::int_<110>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<111>>::type, mpl::int_<111>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<112>>::type, mpl::int_<112>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<113>>::type, mpl::int_<113>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<114>>::type, mpl::int_<114>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<115>>::type, mpl::int_<115>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<116>>::type, mpl::int_<116>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<117>>::type, mpl::int_<117>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<118>>::type, mpl::int_<118>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<119>>::type, mpl::int_<119>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<120>>::type, mpl::int_<120>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<121>>::type, mpl::int_<121>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<122>>::type, mpl::int_<122>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<123>>::type, mpl::int_<123>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<124>>::type, mpl::int_<124>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<125>>::type, mpl::int_<125>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<126>>::type, mpl::int_<126>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<127>>::type, mpl::int_<127>>::value, ""); static_assert(boost::is_same<typename mpl::at<m, mpl::int_<128>>::type, mpl::int_<128>>::value, ""); }
50.416819
80
0.44822
GuiCodron
a3aaba8be3a2eee78d1064444a1ec2498fec650b
4,632
cpp
C++
samples/snippets/cpp/VS_Snippets_Remoting/Httpwebrequest_proxy/CPP/httpwebrequest_proxy.cpp
broken240/dotnet-api-docs
af0894cae0c60a12d53ad7fde36bd5e1203d0897
[ "CC-BY-4.0", "MIT" ]
1
2020-07-05T20:15:35.000Z
2020-07-05T20:15:35.000Z
samples/snippets/cpp/VS_Snippets_Remoting/Httpwebrequest_proxy/CPP/httpwebrequest_proxy.cpp
broken240/dotnet-api-docs
af0894cae0c60a12d53ad7fde36bd5e1203d0897
[ "CC-BY-4.0", "MIT" ]
null
null
null
samples/snippets/cpp/VS_Snippets_Remoting/Httpwebrequest_proxy/CPP/httpwebrequest_proxy.cpp
broken240/dotnet-api-docs
af0894cae0c60a12d53ad7fde36bd5e1203d0897
[ "CC-BY-4.0", "MIT" ]
null
null
null
/*System::Net::HttpWebRequest::Proxy This program demonstrates the 'Proxy' property of the 'HttpWebRequest' class. A 'HttpWebRequest' Object* and a 'Proxy' Object* is created.The Proxy Object is then assigned to the 'Proxy' Property of the 'HttpWebRequest' Object* and printed onto the console(this is the default Proxy setting).New Proxy address and the credentials are requested from the User::A new Proxy Object* is then constructed from the supplied inputs.Then the 'Proxy' property of the request is associated with the new Proxy Object*. Note:No credentials are required if the Proxy does not require any authentication. */ #using <System.dll> using namespace System; using namespace System::IO; using namespace System::Net; using namespace System::Text; int main() { try { // <Snippet1> // Create a new request to the mentioned URL. HttpWebRequest ^ myWebRequest = (HttpWebRequest ^) (WebRequest::Create("http://www.microsoft.com")); // Obtain the 'Proxy' of the Default browser. IWebProxy ^ proxy = myWebRequest->Proxy; // Print the Proxy Url to the console. if (proxy) { Console::WriteLine("Proxy: {0}", proxy->GetProxy(myWebRequest->RequestUri)); } else { Console::WriteLine("Proxy is null; no proxy will be used"); } WebProxy ^ myProxy = gcnew WebProxy; Console::WriteLine("\nPlease enter the new Proxy Address that is to be set:"); Console::WriteLine("(Example:http://myproxy.example.com:port)"); String ^ proxyAddress; try { proxyAddress = Console::ReadLine(); if (proxyAddress->Length > 0) { Console::WriteLine("\nPlease enter the Credentials "); Console::WriteLine("Username:"); String ^ username; username = Console::ReadLine(); Console::WriteLine("\nPassword:"); String ^ password; password = Console::ReadLine(); // Create a new Uri object. Uri ^ newUri = gcnew Uri(proxyAddress); // Associate the newUri object to 'myProxy' object so that new myProxy settings can be set. myProxy->Address = newUri; // Create a NetworkCredential object and associate it with the Proxy property of request object. myProxy->Credentials = gcnew NetworkCredential(username, password); myWebRequest->Proxy = myProxy; } Console::WriteLine("\nThe Address of the new Proxy settings are {0}", myProxy->Address); HttpWebResponse ^ myWebResponse = (HttpWebResponse ^) (myWebRequest->GetResponse()); // </Snippet1> // Print the HTML contents of the page to the console. Stream ^ streamResponse = myWebResponse->GetResponseStream(); StreamReader ^ streamRead = gcnew StreamReader(streamResponse); array < Char > ^readBuff = gcnew array < Char > (256); int count = streamRead->Read(readBuff, 0, 256); Console::WriteLine("\nThe contents of the HTML pages are :"); while (count > 0) { String ^ outputData = gcnew String(readBuff, 0, count); Console::Write(outputData); count = streamRead->Read(readBuff, 0, 256); } streamResponse->Close(); streamRead->Close(); // Release the HttpWebResponse Resource. myWebResponse->Close(); Console::WriteLine("\nPress any key to continue........."); Console::Read(); } catch(UriFormatException ^ e) { Console::WriteLine("\nUriFormatException is thrown. Message: {0}", e->Message); Console::WriteLine("\nThe format of the Proxy address you entered is invalid"); Console::WriteLine("\nPress any key to continue........."); Console::Read(); } } catch(WebException ^ e) { Console::WriteLine("\nWebException raised!"); Console::WriteLine("\nMessage: {0} ", e->Message); Console::WriteLine("\nStatus: {0} ", e->Status); } catch(Exception ^ e) { Console::WriteLine("\nException is raised. "); Console::WriteLine("\nMessage: {0} ", e->Message); } }
41.72973
113
0.568005
broken240
a3b1e02b04f4a567d852ad370004c6b66ff29b77
12,335
hpp
C++
include/MasterServer/DedicatedServerPrepareForConnectionRequest.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/MasterServer/DedicatedServerPrepareForConnectionRequest.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/MasterServer/DedicatedServerPrepareForConnectionRequest.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: BGNet.Core.Messages.BaseReliableRequest #include "BGNet/Core/Messages/BaseReliableRequest.hpp" // Including type: MasterServer.IDedicatedServerMasterServerServerToClientMessage #include "MasterServer/IDedicatedServerMasterServerServerToClientMessage.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Net namespace System::Net { // Forward declaring type: IPEndPoint class IPEndPoint; } // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: ByteArrayNetSerializable class ByteArrayNetSerializable; // Forward declaring type: PacketPool`1<T> template<typename T> class PacketPool_1; } // Forward declaring namespace: LiteNetLib::Utils namespace LiteNetLib::Utils { // Forward declaring type: NetDataWriter class NetDataWriter; // Forward declaring type: NetDataReader class NetDataReader; } // Completed forward declares // Type namespace: MasterServer namespace MasterServer { // Forward declaring type: DedicatedServerPrepareForConnectionRequest class DedicatedServerPrepareForConnectionRequest; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::MasterServer::DedicatedServerPrepareForConnectionRequest); DEFINE_IL2CPP_ARG_TYPE(::MasterServer::DedicatedServerPrepareForConnectionRequest*, "MasterServer", "DedicatedServerPrepareForConnectionRequest"); // Type namespace: MasterServer namespace MasterServer { // Size: 0x48 #pragma pack(push, 1) // Autogenerated type: MasterServer.DedicatedServerPrepareForConnectionRequest // [TokenAttribute] Offset: FFFFFFFF class DedicatedServerPrepareForConnectionRequest : public ::BGNet::Core::Messages::BaseReliableRequest/*, public ::MasterServer::IDedicatedServerMasterServerServerToClientMessage*/ { public: // Writing base type padding for base size: 0x14 to desired offset: 0x18 char ___base_padding[0x4] = {}; #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // public System.String id // Size: 0x8 // Offset: 0x18 ::StringW id; // Field size check static_assert(sizeof(::StringW) == 0x8); // public System.String userId // Size: 0x8 // Offset: 0x20 ::StringW userId; // Field size check static_assert(sizeof(::StringW) == 0x8); // public System.String userName // Size: 0x8 // Offset: 0x28 ::StringW userName; // Field size check static_assert(sizeof(::StringW) == 0x8); // public System.Net.IPEndPoint remoteEndPoint // Size: 0x8 // Offset: 0x30 ::System::Net::IPEndPoint* remoteEndPoint; // Field size check static_assert(sizeof(::System::Net::IPEndPoint*) == 0x8); // public readonly ByteArrayNetSerializable random // Size: 0x8 // Offset: 0x38 ::GlobalNamespace::ByteArrayNetSerializable* random; // Field size check static_assert(sizeof(::GlobalNamespace::ByteArrayNetSerializable*) == 0x8); // public readonly ByteArrayNetSerializable publicKey // Size: 0x8 // Offset: 0x40 ::GlobalNamespace::ByteArrayNetSerializable* publicKey; // Field size check static_assert(sizeof(::GlobalNamespace::ByteArrayNetSerializable*) == 0x8); public: // Creating interface conversion operator: operator ::MasterServer::IDedicatedServerMasterServerServerToClientMessage operator ::MasterServer::IDedicatedServerMasterServerServerToClientMessage() noexcept { return *reinterpret_cast<::MasterServer::IDedicatedServerMasterServerServerToClientMessage*>(this); } // Deleting conversion operator: operator uint constexpr operator uint() const noexcept = delete; // Get instance field reference: public System.String id ::StringW& dyn_id(); // Get instance field reference: public System.String userId ::StringW& dyn_userId(); // Get instance field reference: public System.String userName ::StringW& dyn_userName(); // Get instance field reference: public System.Net.IPEndPoint remoteEndPoint ::System::Net::IPEndPoint*& dyn_remoteEndPoint(); // Get instance field reference: public readonly ByteArrayNetSerializable random ::GlobalNamespace::ByteArrayNetSerializable*& dyn_random(); // Get instance field reference: public readonly ByteArrayNetSerializable publicKey ::GlobalNamespace::ByteArrayNetSerializable*& dyn_publicKey(); // static public PacketPool`1<MasterServer.DedicatedServerPrepareForConnectionRequest> get_pool() // Offset: 0x164E258 static ::GlobalNamespace::PacketPool_1<::MasterServer::DedicatedServerPrepareForConnectionRequest*>* get_pool(); // public MasterServer.DedicatedServerPrepareForConnectionRequest Init(System.String id, System.String userId, System.String userName, System.Net.IPEndPoint remoteEndPoint, System.Byte[] random, System.Byte[] publicKey) // Offset: 0x164E2A0 ::MasterServer::DedicatedServerPrepareForConnectionRequest* Init(::StringW id, ::StringW userId, ::StringW userName, ::System::Net::IPEndPoint* remoteEndPoint, ::ArrayW<uint8_t> random, ::ArrayW<uint8_t> publicKey); // public System.Void .ctor() // Offset: 0x164E4D4 // Implemented from: BGNet.Core.Messages.BaseReliableRequest // Base method: System.Void BaseReliableRequest::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static DedicatedServerPrepareForConnectionRequest* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::MasterServer::DedicatedServerPrepareForConnectionRequest::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<DedicatedServerPrepareForConnectionRequest*, creationType>())); } // public override System.Void Serialize(LiteNetLib.Utils.NetDataWriter writer) // Offset: 0x164E2F8 // Implemented from: BGNet.Core.Messages.BaseReliableRequest // Base method: System.Void BaseReliableRequest::Serialize(LiteNetLib.Utils.NetDataWriter writer) void Serialize(::LiteNetLib::Utils::NetDataWriter* writer); // public override System.Void Deserialize(LiteNetLib.Utils.NetDataReader reader) // Offset: 0x164E3C0 // Implemented from: BGNet.Core.Messages.BaseReliableRequest // Base method: System.Void BaseReliableRequest::Deserialize(LiteNetLib.Utils.NetDataReader reader) void Deserialize(::LiteNetLib::Utils::NetDataReader* reader); // public override System.Void Release() // Offset: 0x164E458 // Implemented from: BGNet.Core.Messages.BaseReliableRequest // Base method: System.Void BaseReliableRequest::Release() void Release(); }; // MasterServer.DedicatedServerPrepareForConnectionRequest #pragma pack(pop) static check_size<sizeof(DedicatedServerPrepareForConnectionRequest), 64 + sizeof(::GlobalNamespace::ByteArrayNetSerializable*)> __MasterServer_DedicatedServerPrepareForConnectionRequestSizeCheck; static_assert(sizeof(DedicatedServerPrepareForConnectionRequest) == 0x48); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: MasterServer::DedicatedServerPrepareForConnectionRequest::get_pool // Il2CppName: get_pool template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::PacketPool_1<::MasterServer::DedicatedServerPrepareForConnectionRequest*>* (*)()>(&MasterServer::DedicatedServerPrepareForConnectionRequest::get_pool)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(MasterServer::DedicatedServerPrepareForConnectionRequest*), "get_pool", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: MasterServer::DedicatedServerPrepareForConnectionRequest::Init // Il2CppName: Init template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::MasterServer::DedicatedServerPrepareForConnectionRequest* (MasterServer::DedicatedServerPrepareForConnectionRequest::*)(::StringW, ::StringW, ::StringW, ::System::Net::IPEndPoint*, ::ArrayW<uint8_t>, ::ArrayW<uint8_t>)>(&MasterServer::DedicatedServerPrepareForConnectionRequest::Init)> { static const MethodInfo* get() { static auto* id = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* userId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* userName = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* remoteEndPoint = &::il2cpp_utils::GetClassFromName("System.Net", "IPEndPoint")->byval_arg; static auto* random = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg; static auto* publicKey = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg; return ::il2cpp_utils::FindMethod(classof(MasterServer::DedicatedServerPrepareForConnectionRequest*), "Init", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{id, userId, userName, remoteEndPoint, random, publicKey}); } }; // Writing MetadataGetter for method: MasterServer::DedicatedServerPrepareForConnectionRequest::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: MasterServer::DedicatedServerPrepareForConnectionRequest::Serialize // Il2CppName: Serialize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (MasterServer::DedicatedServerPrepareForConnectionRequest::*)(::LiteNetLib::Utils::NetDataWriter*)>(&MasterServer::DedicatedServerPrepareForConnectionRequest::Serialize)> { static const MethodInfo* get() { static auto* writer = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataWriter")->byval_arg; return ::il2cpp_utils::FindMethod(classof(MasterServer::DedicatedServerPrepareForConnectionRequest*), "Serialize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{writer}); } }; // Writing MetadataGetter for method: MasterServer::DedicatedServerPrepareForConnectionRequest::Deserialize // Il2CppName: Deserialize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (MasterServer::DedicatedServerPrepareForConnectionRequest::*)(::LiteNetLib::Utils::NetDataReader*)>(&MasterServer::DedicatedServerPrepareForConnectionRequest::Deserialize)> { static const MethodInfo* get() { static auto* reader = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataReader")->byval_arg; return ::il2cpp_utils::FindMethod(classof(MasterServer::DedicatedServerPrepareForConnectionRequest*), "Deserialize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{reader}); } }; // Writing MetadataGetter for method: MasterServer::DedicatedServerPrepareForConnectionRequest::Release // Il2CppName: Release template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (MasterServer::DedicatedServerPrepareForConnectionRequest::*)()>(&MasterServer::DedicatedServerPrepareForConnectionRequest::Release)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(MasterServer::DedicatedServerPrepareForConnectionRequest*), "Release", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
58.183962
359
0.754439
RedBrumbler
a3b6bb5e964e1c1366f705ced2a9cf61c92a3ad8
3,402
cpp
C++
deps/boost_1_63_0/libs/qvm/test/rot_quat_test.cpp
newtondev/drachtio-server
cd18c6c0e1aa05501b068fc373682333bab5640c
[ "MIT" ]
null
null
null
deps/boost_1_63_0/libs/qvm/test/rot_quat_test.cpp
newtondev/drachtio-server
cd18c6c0e1aa05501b068fc373682333bab5640c
[ "MIT" ]
null
null
null
deps/boost_1_63_0/libs/qvm/test/rot_quat_test.cpp
newtondev/drachtio-server
cd18c6c0e1aa05501b068fc373682333bab5640c
[ "MIT" ]
null
null
null
//Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc. //Distributed under the Boost Software License, Version 1.0. (See accompanying //file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/qvm/quat_operations.hpp> #include <boost/qvm/mat_operations.hpp> #include "test_qvm_matrix.hpp" #include "test_qvm_quaternion.hpp" #include "test_qvm_vector.hpp" #include "gold.hpp" namespace { void test_x() { using namespace boost::qvm; test_qvm::vector<V1,3> axis; axis.a[0]=1; for( float r=0; r<6.28f; r+=0.5f ) { test_qvm::quaternion<Q1> q1=rot_quat(axis,r); test_qvm::matrix<M1,3,3> x1=convert_to< test_qvm::matrix<M1,3,3> >(q1); test_qvm::rotation_x(x1.b,r); BOOST_QVM_TEST_CLOSE(x1.a,x1.b,0.000001f); test_qvm::quaternion<Q2> q2(42,1); set_rot(q2,axis,r); test_qvm::matrix<M2,3,3> x2=convert_to< test_qvm::matrix<M2,3,3> >(q2); test_qvm::rotation_x(x2.b,r); BOOST_QVM_TEST_CLOSE(x2.a,x2.b,0.000001f); test_qvm::quaternion<Q1> q3(42,1); test_qvm::quaternion<Q1> q4(42,1); rotate(q3,axis,r); q3 = q3*q1; BOOST_QVM_TEST_EQ(q3.a,q3.a); } } void test_y() { using namespace boost::qvm; test_qvm::vector<V1,3> axis; axis.a[1]=1; for( float r=0; r<6.28f; r+=0.5f ) { test_qvm::quaternion<Q1> q1=rot_quat(axis,r); test_qvm::matrix<M1,3,3> x1=convert_to< test_qvm::matrix<M1,3,3> >(q1); test_qvm::rotation_y(x1.b,r); BOOST_QVM_TEST_CLOSE(x1.a,x1.b,0.000001f); test_qvm::quaternion<Q2> q2(42,1); set_rot(q2,axis,r); test_qvm::matrix<M2,3,3> x2=convert_to< test_qvm::matrix<M2,3,3> >(q2); test_qvm::rotation_y(x2.b,r); BOOST_QVM_TEST_CLOSE(x2.a,x2.b,0.000001f); test_qvm::quaternion<Q1> q3(42,1); test_qvm::quaternion<Q1> q4(42,1); rotate(q3,axis,r); q3 = q3*q1; BOOST_QVM_TEST_EQ(q3.a,q3.a); } } void test_z() { using namespace boost::qvm; test_qvm::vector<V1,3> axis; axis.a[2]=1; for( float r=0; r<6.28f; r+=0.5f ) { test_qvm::quaternion<Q1> q1=rot_quat(axis,r); test_qvm::matrix<M1,3,3> x1=convert_to< test_qvm::matrix<M1,3,3> >(q1); test_qvm::rotation_z(x1.b,r); BOOST_QVM_TEST_CLOSE(x1.a,x1.b,0.000001f); test_qvm::quaternion<Q2> q2(42,1); set_rot(q2,axis,r); test_qvm::matrix<M2,3,3> x2=convert_to< test_qvm::matrix<M2,3,3> >(q2); test_qvm::rotation_z(x2.b,r); BOOST_QVM_TEST_CLOSE(x2.a,x2.b,0.000001f); test_qvm::quaternion<Q1> q3(42,1); test_qvm::quaternion<Q1> q4(42,1); rotate(q3,axis,r); q3 = q3*q1; BOOST_QVM_TEST_EQ(q3.a,q3.a); } } } int main() { test_x(); test_y(); test_z(); return boost::report_errors(); }
35.4375
85
0.516461
newtondev
a3b7899daa1dc5d90fb8b9ca2a869b93c8444be4
1,587
cpp
C++
Engine/Core/Utilities.cpp
Alex-Sindledecker/Mitochondrion_Engine
4185f8633648473c64126e47a60adf02b68aaae5
[ "MIT" ]
null
null
null
Engine/Core/Utilities.cpp
Alex-Sindledecker/Mitochondrion_Engine
4185f8633648473c64126e47a60adf02b68aaae5
[ "MIT" ]
null
null
null
Engine/Core/Utilities.cpp
Alex-Sindledecker/Mitochondrion_Engine
4185f8633648473c64126e47a60adf02b68aaae5
[ "MIT" ]
null
null
null
#include "mepch.h" #include "Utilities.h" namespace util { ThreadPool::ThreadPool(size_t size) { start(size); } ThreadPool::~ThreadPool() { if (!drain) finish(); } void ThreadPool::start(size_t size) { for (int i = 0; i < size; i++) { threads.emplace_back([=] { //Thread loop while (true) { //Get the next task and execute it Task task; { std::unique_lock<std::mutex> lk(mutex); cv.wait(lk, [=] { return drain || !tasks.empty(); }); if (drain && tasks.empty()) return; task = std::move(tasks.front()); tasks.pop(); } task(); } }); } } void ThreadPool::finish() { drain = true; cv.notify_all(); for (std::thread& t : threads) t.join(); } static auto startTime = std::chrono::high_resolution_clock::now(); double getCurrentTime() { auto current = std::chrono::high_resolution_clock::now() - startTime; return current.count() / 1000000000.0; } std::string getCurrentTimeString() { auto current = std::chrono::high_resolution_clock::now() - startTime; auto minutes = std::chrono::duration_cast<std::chrono::minutes>(current); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(current); auto milliseconds = (current % 1000000000) / 1000000.0; std::stringstream ss; ss << minutes.count() << ":" << seconds.count() % 60 << ":" << milliseconds.count(); return ss.str(); } StackAllocator::StackAllocator(size_t bufferSize) { buffer = new byte[bufferSize]; } StackAllocator::~StackAllocator() { delete buffer; } }
18.892857
86
0.616887
Alex-Sindledecker
a3b812b57e66c055dba5a057b6ebcc9160a66483
155
cpp
C++
src/var/Vector.cpp
bander9289/StratifyAPI
9b45091aa71a4e5718047438ea4044c1fdc814a3
[ "MIT" ]
2
2016-05-21T03:09:19.000Z
2016-08-27T03:40:51.000Z
src/var/Vector.cpp
bander9289/StratifyAPI
9b45091aa71a4e5718047438ea4044c1fdc814a3
[ "MIT" ]
75
2017-10-08T22:21:19.000Z
2020-03-30T21:13:20.000Z
src/var/Vector.cpp
StratifyLabs/StratifyLib
975a5c25a84296fd0dec64fe4dc579cf7027abe6
[ "MIT" ]
5
2018-03-27T16:44:09.000Z
2020-07-08T16:45:55.000Z
/*! \file */ // Copyright 2011-2020 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md for rights. #include "var/Vector.hpp" u32 sapi_vector_unused;
19.375
100
0.722581
bander9289
a3c22d61a97af366a588930da800140f0b680760
1,582
hpp
C++
Differential_Equations/C++/RK/RK_class.hpp
dkaramit/ASAP
afade2737b332e7dbf0ea06eb4f31564a478ee40
[ "MIT" ]
null
null
null
Differential_Equations/C++/RK/RK_class.hpp
dkaramit/ASAP
afade2737b332e7dbf0ea06eb4f31564a478ee40
[ "MIT" ]
null
null
null
Differential_Equations/C++/RK/RK_class.hpp
dkaramit/ASAP
afade2737b332e7dbf0ea06eb4f31564a478ee40
[ "MIT" ]
1
2021-12-15T02:03:01.000Z
2021-12-15T02:03:01.000Z
#ifndef RK_class #define RK_class //This is a general implementation of explicit RK solver of // a system of differential equations in the interval [0,1]. template<class diffeq, int number_of_eqs, class RK_method> //Note that you can use template to pass the method class RK { /* This is a class that defines an explicit Runge-Kutta solver for system of differential equations. The idea is to have a simple code that one can expand and experiment with. On how to use it, read the comments within the .hpp files, and the RK.cpp. On how the RK solver works, have a look at the jupyter notebook in the python directory. */ private://There is no reason to make things private (if you break it it's not my fault)... public: int No_steps, current_step; bool End; double step_size,tn; diffeq dydt; double* steps; double** solution; RK_method method; //these are here to hold the k's, sum_i b_i*k_i and sum_j a_{ij}*k_j double** k; double* ak; double* bk; double yn[number_of_eqs];//this is here to hold the current steps double fyn[number_of_eqs];//this is here to get dydt in each step RK(diffeq dydt , double (&init)[number_of_eqs] , int N=10000); ~RK(); /*-------------------it would be nice to have a way to define these sums more generaly-----------------*/ void sum_bk();// calculate sum_i b_i*k_i and passit to this->bk void sum_ak(int stage); // calculate sum_j a_{ij}*k_j and passit to this->ak void next_step(); void solve(); }; #endif
28.25
110
0.666245
dkaramit
a3c30e8579142714db6f85b58a257ab49fe725be
3,242
cpp
C++
Source/ProceduralDungeon/Private/TriggerDoor.cpp
davchezt/ProceduralDungeon
12d77598a03de22ea479dc25b6e288d1097dc5b0
[ "MIT" ]
1
2021-03-14T07:27:56.000Z
2021-03-14T07:27:56.000Z
Source/ProceduralDungeon/Private/TriggerDoor.cpp
davchezt/ProceduralDungeon
12d77598a03de22ea479dc25b6e288d1097dc5b0
[ "MIT" ]
null
null
null
Source/ProceduralDungeon/Private/TriggerDoor.cpp
davchezt/ProceduralDungeon
12d77598a03de22ea479dc25b6e288d1097dc5b0
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2019-2021 Benoit Pelletier * * 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 "TriggerDoor.h" #include "Components/BoxComponent.h" #include "GameFramework/Character.h" #include "Room.h" #include "RoomLevel.h" ATriggerDoor::ATriggerDoor() { BoxComponent = CreateDefaultSubobject<UBoxComponent>(TEXT("BoxComponent")); if (RootComponent != nullptr) { BoxComponent->SetupAttachment(RootComponent); } } void ATriggerDoor::BeginPlay() { Super::BeginPlay(); if (nullptr != BoxComponent) { BoxComponent->OnComponentBeginOverlap.AddUniqueDynamic(this, &ATriggerDoor::OnTriggerEnter); BoxComponent->OnComponentEndOverlap.AddUniqueDynamic(this, &ATriggerDoor::OnTriggerExit); } } void ATriggerDoor::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (CharacterList.Num() > 0) { OpenDoor(); } else { CloseDoor(); } } void ATriggerDoor::SetRoomsAlwaysVisible(bool _visible) { if (nullptr != RoomA && nullptr != RoomA->GetLevelScript()) { RoomA->GetLevelScript()->AlwaysVisible = _visible; } if (nullptr != RoomB && nullptr != RoomB->GetLevelScript()) { RoomB->GetLevelScript()->AlwaysVisible = _visible; } } void ATriggerDoor::OnTriggerEnter(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult) { ACharacter* OtherCharacter = Cast<ACharacter>(OtherActor); UCapsuleComponent* OtherCapsule = Cast<UCapsuleComponent>(OtherComp); if (OtherCharacter != nullptr && OtherCapsule != nullptr && OtherCapsule == OtherCharacter->GetCapsuleComponent() && !CharacterList.Contains(OtherCharacter)) { CharacterList.Add(OtherCharacter); } } void ATriggerDoor::OnTriggerExit(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex) { ACharacter* OtherCharacter = Cast<ACharacter>(OtherActor); UCapsuleComponent* OtherCapsule = Cast<UCapsuleComponent>(OtherComp); if (OtherCharacter != nullptr && OtherCapsule != nullptr && OtherCapsule == OtherCharacter->GetCapsuleComponent() && CharacterList.Contains(OtherCharacter)) { CharacterList.Remove(OtherCharacter); } }
32.42
198
0.761258
davchezt
a3c822213e41395f88bec6d3bcfa59a4ce4fdd28
2,578
cpp
C++
Source/FourPlayerCoop/Private/Items/SImpactEffect.cpp
roy-sourish/FourPlayerCoop
22703b29fa0fb6e6f718bbd68ac50daa97be6bdf
[ "MIT" ]
1
2021-06-29T16:27:43.000Z
2021-06-29T16:27:43.000Z
Source/FourPlayerCoop/Private/Items/SImpactEffect.cpp
roy-sourish/FourPlayerCoop
22703b29fa0fb6e6f718bbd68ac50daa97be6bdf
[ "MIT" ]
null
null
null
Source/FourPlayerCoop/Private/Items/SImpactEffect.cpp
roy-sourish/FourPlayerCoop
22703b29fa0fb6e6f718bbd68ac50daa97be6bdf
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "Items/SImpactEffect.h" #include "Components/DecalComponent.h" #include "Sound/SoundCue.h" #include "PhysicalMaterials/PhysicalMaterial.h" #include "Kismet/GameplayStatics.h" #include "FourPlayerCoop/FourPlayerCoop.h" // Sets default values ASImpactEffect::ASImpactEffect() { SetAutoDestroyWhenFinished(true); PrimaryActorTick.bCanEverTick = true; DecalLifeSpan = 10.0f; DecalSize = 16.0f; } void ASImpactEffect::PostInitializeComponents() { Super::PostInitializeComponents(); /* Figure out what we hit. (SurfaceHit is set during actor instantiation in the weapon class */ UPhysicalMaterial* HitPhysMat = SurfaceHit.PhysMaterial.Get(); EPhysicalSurface HitSurfaceType = UPhysicalMaterial::DetermineSurfaceType(HitPhysMat); UParticleSystem* ImpactEffect = GetImpactFX(HitSurfaceType); if (ImpactEffect) { //UE_LOG(LogTemp, Error, TEXT("Impact")); UGameplayStatics::SpawnEmitterAtLocation(this, ImpactEffect, GetActorLocation(), GetActorRotation()); } USoundCue* ImpactSound = GetImpactSound(HitSurfaceType); if (ImpactSound) { UGameplayStatics::PlaySoundAtLocation(this, ImpactSound, GetActorLocation()); } if (DecalMaterial) { FVector ImpactNormal = SurfaceHit.ImpactNormal; ImpactNormal.Normalize(); /* Inverse to point towards the wall. Invert to get the correct orientation of the decal (pointing into the surface instead of away, messing with the normals, and lighting) */ ImpactNormal = -ImpactNormal; FRotator RandomDecalRotation = ImpactNormal.ToOrientationRotator(); RandomDecalRotation.Roll = FMath::FRandRange(-180.0f, 180.0f); UDecalComponent* DecalComp = UGameplayStatics::SpawnDecalAttached(DecalMaterial, FVector(DecalSize), SurfaceHit.Component.Get(), SurfaceHit.BoneName, SurfaceHit.ImpactPoint, RandomDecalRotation, EAttachLocation::KeepWorldPosition, DecalLifeSpan); if (DecalComp) { DecalComp->SetFadeOut(DecalLifeSpan, 0.5f, false); } } } UParticleSystem* ASImpactEffect::GetImpactFX(EPhysicalSurface SurfaceType) const { switch (SurfaceType) { case SURFACE_DEFAULT: return DefaultImpactFX; case SURFACE_BODY: case SURFACE_HEAD: case SURFACE_LIMB: return PlayerFleshFX; default: return nullptr; } } USoundCue* ASImpactEffect::GetImpactSound(EPhysicalSurface SurfaceType) const { switch (SurfaceType) { case SURFACE_DEFAULT: return DefaultSound; case SURFACE_BODY: case SURFACE_HEAD: case SURFACE_LIMB: return PlayerFleshSound; default: return nullptr; } }
26.57732
103
0.776571
roy-sourish
a3cb10fea82cca00de29233dbd276b5ab701bd24
4,124
hpp
C++
include/dtc/event/select.hpp
tsung-wei-huang/DtCraft
80cc9e1195adc0026107814243401a1fc47b5be2
[ "MIT" ]
69
2019-03-16T20:13:26.000Z
2022-03-24T14:12:19.000Z
include/dtc/event/select.hpp
Tsung-Wei/DtCraft
80cc9e1195adc0026107814243401a1fc47b5be2
[ "MIT" ]
12
2017-12-02T05:38:30.000Z
2019-02-08T11:16:12.000Z
include/dtc/event/select.hpp
Tsung-Wei/DtCraft
80cc9e1195adc0026107814243401a1fc47b5be2
[ "MIT" ]
12
2019-04-13T16:27:29.000Z
2022-01-07T14:42:46.000Z
/****************************************************************************** * * * Copyright (c) 2016, Tsung-Wei Huang and Martin D. F. Wong, * * University of Illinois at Urbana-Champaign (UIUC), IL, USA. * * * * All Rights Reserved. * * * * This program is free software. You can redistribute and/or modify * * it in accordance with the terms of the accompanying license agreement. * * See LICENSE in the top-level directory for details. * * * ******************************************************************************/ #ifndef DTC_EVENT_SELECT_HPP_ #define DTC_EVENT_SELECT_HPP_ // Class: Select // // Select allows a program to monitor multiple file descriptors, waiting until one or more of the // file descriptors become "ready" for some class of IO operations. Below are function signarues: // // The time structures involved are defined in <sys/time.h> and look like // // struct timeval { // long tv_sec; // seconds // long tv_usec; // microseconds // }; // // int select(int nfds, fd_set *rfds, fd_set *wfds, fd_set *exceptfds, struct timeval *timeout); // void FD_CLR(int fd, fd_set *set); // int FD_ISSET(int fd, fd_set *set); // void FD_SET(int fd, fd_set *set); // void FD_ZERO(fd_set *set); // #include <dtc/event/event.hpp> namespace dtc { // Class: Select class Select { friend class Reactor; ~Select(); inline size_t num_fds_per_mask() const; inline size_t num_masks(const size_t) const; int _max_fd {-1}; size_t _cap[2] {0, 0}; // in/out fd_set* _R[2] {nullptr, nullptr}; // in/out fd_set* _W[2] {nullptr, nullptr}; // in/out Event** _fd2ev[2] {nullptr, nullptr}; // read/write template <typename D, typename C> void _poll(D&&, C&&); void _prepare_select(); void _recap(const int); void _make_pollee(uint8_t*, const uint8_t*, const size_t); void _insert(Event*); void _remove(Event*); void _clear(); }; // Function: num_fds_per_mask // Each byte can accommodate eight bits (eight file descriptors). inline size_t Select::num_fds_per_mask() const { return sizeof(fd_mask)*8; } // Function: num_masks // Perform the ceil operation to find the number of required masks for a given // number of file descriptors. inline size_t Select::num_masks(const size_t num_fds) const { return (num_fds + num_fds_per_mask() - 1) / num_fds_per_mask(); } // Procedure: poll template <typename D, typename C> void Select::_poll(D&& d, C&& on) { if(_max_fd == -1) return; _prepare_select(); // Privatize the storage that is going to be used by the select system call. const auto pmax_fd = _max_fd; auto tv = duration_cast<struct timeval>(std::forward<D>(d)); // Here the caller goes to the sleep. auto ret = ::select(pmax_fd + 1, _R[1], _W[1], nullptr, &tv); // Let's move to the next dispatch cycle. if(ret == -1) { throw std::system_error(std::make_error_code(static_cast<std::errc>(errno)), "Select failed"); } // Invoke the handler for every active read/write event. for(int fd=pmax_fd; fd >= 0; --fd) { if(FD_ISSET(fd, _R[1]) && _fd2ev[0][fd]) { on(_fd2ev[0][fd]); } if(FD_ISSET(fd, _W[1]) && _fd2ev[1][fd]) { on(_fd2ev[1][fd]); } } } //------------------------------------------------------------------------------------------------- bool select_on_write(int, struct timeval&&); template <typename T> bool select_on_write(int fd, T&& d) { return select_on_write(fd, duration_cast<struct timeval>(std::forward<T>(d))); } bool select_on_write(int, int, std::error_code&); }; // End of namespace dtc. --------------------------------------------------------------- #endif
32.472441
99
0.542919
tsung-wei-huang
a3cf6132b3aca45adcbdaf54178666f979296042
571
hpp
C++
pythran/pythonic/__builtin__/oct.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/__builtin__/oct.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/__builtin__/oct.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_BUILTIN_OCT_HPP #define PYTHONIC_BUILTIN_OCT_HPP #include "pythonic/include/__builtin__/oct.hpp" #include "pythonic/types/str.hpp" #include "pythonic/utils/functor.hpp" #include <sstream> namespace pythonic { namespace __builtin__ { template <class T> types::str oct(T const &v) { std::ostringstream oss; oss << #if defined(__PYTHRAN__) && __PYTHRAN__ == 3 "0o" #else '0' #endif << std::oct << v; return oss.str(); } DEFINE_FUNCTOR(pythonic::__builtin__, oct); } } #endif
15.861111
47
0.637478
xmar
a3d77419242e7d41e4928e47c4197007175a6deb
2,265
cpp
C++
src/Compiler/Parser/VarDecl.cpp
feral-lang/feral
1ce8eb72eec7c8a5ac19d3767e907b86387e29e0
[ "MIT" ]
131
2020-03-19T15:22:37.000Z
2021-12-19T02:37:01.000Z
src/Compiler/Parser/VarDecl.cpp
Electrux/feral
1ce8eb72eec7c8a5ac19d3767e907b86387e29e0
[ "BSD-3-Clause" ]
14
2020-04-06T05:50:15.000Z
2021-06-26T06:19:04.000Z
src/Compiler/Parser/VarDecl.cpp
Electrux/feral
1ce8eb72eec7c8a5ac19d3767e907b86387e29e0
[ "BSD-3-Clause" ]
20
2020-04-06T07:28:30.000Z
2021-09-05T14:46:25.000Z
/* MIT License Copyright (c) 2020 Feral Language repositories 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. */ #include "Compiler/CodeGen/Internal.hpp" Errors parse_var_decl(phelper_t &ph, stmt_base_t *&loc) { std::vector<const stmt_var_decl_base_t *> decls; stmt_base_t *decl = nullptr; size_t idx = ph.peak()->pos; if(!ph.accept(TOK_LET)) { err::set(E_PARSE_FAIL, ph.peak()->pos, "expected keyword 'let' here, but found: '%s'", TokStrs[ph.peakt()]); goto fail; } ph.next(); begin: if(parse_var_decl_base(ph, decl) != E_OK) { goto fail; } decls.push_back((stmt_var_decl_base_t *)decl); decl = nullptr; if(ph.accept(TOK_COMMA)) { ph.next(); goto begin; } if(!ph.accept(TOK_COLS)) { err::set(E_PARSE_FAIL, ph.peak(-1)->pos, "expected semicolon after variable declaration, found: '%s'", TokStrs[ph.peakt()]); goto fail; } ph.next(); loc = new stmt_var_decl_t(decls, idx); return E_OK; fail: for(auto &decl : decls) delete decl; return E_PARSE_FAIL; } Errors parse_var_decl_base(phelper_t &ph, stmt_base_t *&loc) { const lex::tok_t *lhs = nullptr; stmt_base_t *in = nullptr, *rhs = nullptr; // iden index size_t idx = ph.peak()->pos; // the variable in which data is to be stored, must be a const str ph.sett(TOK_STR); lhs = ph.peak(); ph.next(); if(ph.peakt() == TOK_IN) { ph.next(); // 01 = parenthesized expression, func call, subscript, dot if(parse_expr_01(ph, in) != E_OK) { goto fail; } } if(!ph.accept(TOK_ASSN)) { err::set(E_PARSE_FAIL, ph.peak()->pos, "expected assignment operator here for var decl, but found: '%s'", TokStrs[ph.peakt()]); goto fail; } ph.next(); // 15 = everything excluding comma if(parse_expr_15(ph, rhs) != E_OK) { goto fail; } loc = new stmt_var_decl_base_t(new stmt_simple_t(lhs), in, rhs); return E_OK; fail: if(in) delete in; if(rhs) delete rhs; return E_PARSE_FAIL; }
23.842105
78
0.685651
feral-lang
a3e06aab1e0f45b8b2bc4fa5865cd5b100b20139
6,465
cpp
C++
libprecompiled/SystemConfigPrecompiled.cpp
imtypist/FISCO-BCOS
30a281d31e83ca666ef203193963a6d32e39e36a
[ "Apache-2.0" ]
null
null
null
libprecompiled/SystemConfigPrecompiled.cpp
imtypist/FISCO-BCOS
30a281d31e83ca666ef203193963a6d32e39e36a
[ "Apache-2.0" ]
null
null
null
libprecompiled/SystemConfigPrecompiled.cpp
imtypist/FISCO-BCOS
30a281d31e83ca666ef203193963a6d32e39e36a
[ "Apache-2.0" ]
null
null
null
/* This file is part of FISCO-BCOS. FISCO-BCOS 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. FISCO-BCOS 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 FISCO-BCOS. If not, see <http://www.gnu.org/licenses/>. */ /** @file SystemConfigPrecompiled.cpp * @author chaychen * @date 20181211 */ #include "SystemConfigPrecompiled.h" #include "libprecompiled/EntriesPrecompiled.h" #include "libprecompiled/TableFactoryPrecompiled.h" #include <libethcore/ABI.h> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> using namespace dev; using namespace dev::blockverifier; using namespace dev::storage; using namespace dev::precompiled; const char* const SYSCONFIG_METHOD_SET_STR = "setValueByKey(string,string)"; SystemConfigPrecompiled::SystemConfigPrecompiled() { name2Selector[SYSCONFIG_METHOD_SET_STR] = getFuncSelector(SYSCONFIG_METHOD_SET_STR); } PrecompiledExecResult::Ptr SystemConfigPrecompiled::call( ExecutiveContext::Ptr context, bytesConstRef param, Address const& origin, Address const&) { // parse function name uint32_t func = getParamFunc(param); bytesConstRef data = getParamData(param); dev::eth::ContractABI abi; auto callResult = m_precompiledExecResultFactory->createPrecompiledResult(); int count = 0; int result = 0; if (func == name2Selector[SYSCONFIG_METHOD_SET_STR]) { // setValueByKey(string,string) std::string configKey, configValue; abi.abiOut(data, configKey, configValue); // Uniform lowercase configKey boost::to_lower(configKey); PRECOMPILED_LOG(DEBUG) << LOG_BADGE("SystemConfigPrecompiled") << LOG_DESC("setValueByKey func") << LOG_KV("configKey", configKey) << LOG_KV("configValue", configValue); if (!checkValueValid(configKey, configValue)) { PRECOMPILED_LOG(DEBUG) << LOG_BADGE("SystemConfigPrecompiled") << LOG_DESC("set invalid value") << LOG_KV("configKey", configKey) << LOG_KV("configValue", configValue); getErrorCodeOut(callResult->mutableExecResult(), CODE_INVALID_CONFIGURATION_VALUES); return callResult; } storage::Table::Ptr table = openTable(context, SYS_CONFIG); auto condition = table->newCondition(); auto entries = table->select(configKey, condition); auto entry = table->newEntry(); entry->setField(SYSTEM_CONFIG_KEY, configKey); entry->setField(SYSTEM_CONFIG_VALUE, configValue); entry->setField(SYSTEM_CONFIG_ENABLENUM, boost::lexical_cast<std::string>(context->blockInfo().number + 1)); if (entries->size() == 0u) { count = table->insert(configKey, entry, std::make_shared<AccessOptions>(origin)); if (count == storage::CODE_NO_AUTHORIZED) { PRECOMPILED_LOG(DEBUG) << LOG_BADGE("SystemConfigPrecompiled") << LOG_DESC("permission denied"); result = storage::CODE_NO_AUTHORIZED; } else { PRECOMPILED_LOG(DEBUG) << LOG_BADGE("SystemConfigPrecompiled") << LOG_DESC("setValueByKey successfully"); result = count; } } else { count = table->update(configKey, entry, condition, std::make_shared<AccessOptions>(origin)); if (count == storage::CODE_NO_AUTHORIZED) { PRECOMPILED_LOG(DEBUG) << LOG_BADGE("SystemConfigPrecompiled") << LOG_DESC("permission denied"); result = storage::CODE_NO_AUTHORIZED; } else { PRECOMPILED_LOG(DEBUG) << LOG_BADGE("SystemConfigPrecompiled") << LOG_DESC("update value by key successfully"); result = count; } } } else { PRECOMPILED_LOG(ERROR) << LOG_BADGE("SystemConfigPrecompiled") << LOG_DESC("call undefined function") << LOG_KV("func", func); } getErrorCodeOut(callResult->mutableExecResult(), result); return callResult; } bool SystemConfigPrecompiled::checkValueValid(std::string const& key, std::string const& value) { int64_t configuredValue = 0; try { configuredValue = boost::lexical_cast<int64_t>(value); } catch (std::exception const& e) { PRECOMPILED_LOG(ERROR) << LOG_BADGE("SystemConfigPrecompiled") << LOG_DESC("checkValueValid failed") << LOG_KV("key", key) << LOG_KV("value", value) << LOG_KV("errorInfo", e.what()); return false; } if (SYSTEM_KEY_TX_COUNT_LIMIT == key) { return (configuredValue >= TX_COUNT_LIMIT_MIN); } else if (SYSTEM_KEY_TX_GAS_LIMIT == key) { return (configuredValue >= TX_GAS_LIMIT_MIN); } else if (SYSTEM_KEY_RPBFT_EPOCH_SEALER_NUM == key) { return (configuredValue >= RPBFT_EPOCH_SEALER_NUM_MIN); } else if (SYSTEM_KEY_RPBFT_EPOCH_BLOCK_NUM == key) { if (g_BCOSConfig.version() < V2_6_0) { return (configuredValue >= RPBFT_EPOCH_BLOCK_NUM_MIN); } else { // epoch_block_num is at least 2 when supported_version >= v2.6.0 return (configuredValue > RPBFT_EPOCH_BLOCK_NUM_MIN); } } else if (SYSTEM_KEY_CONSENSUS_TIMEOUT == key) { if (g_BCOSConfig.version() < V2_6_0) { return false; } return (configuredValue >= SYSTEM_CONSENSUS_TIMEOUT_MIN && configuredValue < SYSTEM_CONSENSUS_TIMEOUT_MAX); } // only can insert tx_count_limit and tx_gas_limit, rpbft_epoch_sealer_num, // rpbft_epoch_block_num as system config return false; }
36.732955
100
0.625367
imtypist
9cb6364923774cdf38500b7f7e6e6cb4cc93c783
79,300
hpp
C++
data_compression/L1/include/hw/zstd_fse_decoder.hpp
dycz0fx/Vitis_Libraries
d3fc414b552493657101ddb5245f24528720823d
[ "Apache-2.0" ]
1
2021-09-11T01:05:01.000Z
2021-09-11T01:05:01.000Z
data_compression/L1/include/hw/zstd_fse_decoder.hpp
maxpark/Vitis_Libraries
4bd100518d93a8842d1678046ad7457f94eb355c
[ "Apache-2.0" ]
null
null
null
data_compression/L1/include/hw/zstd_fse_decoder.hpp
maxpark/Vitis_Libraries
4bd100518d93a8842d1678046ad7457f94eb355c
[ "Apache-2.0" ]
null
null
null
/* * (c) Copyright 2019-2021 Xilinx, Inc. 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 _XFCOMPRESSION_ZSTD_FSE_DECODER_HPP_ #define _XFCOMPRESSION_ZSTD_FSE_DECODER_HPP_ /** * @file zstd_fse_decoder.hpp * @brief Header for modules used in ZSTD decompress kernel. This file contains * modules used for FSE and Huffman bitstream decoding and table generation. * * This file is part of Vitis Data Compression Library. */ #include <stdint.h> #include "hls_stream.h" #include <ap_int.h> #include "zstd_specs.hpp" #include "compress_utils.hpp" namespace xf { namespace compression { namespace details { template <uint8_t PARALLEL_BYTE> inline void sendData(hls::stream<ap_uint<8 * PARALLEL_BYTE> >& inStream, ap_uint<8 * PARALLEL_BYTE * 2>& accRegister, uint8_t& bytesInAcc, hls::stream<ap_uint<8 * PARALLEL_BYTE> >& outStream, uint64_t size2Write) { #pragma HLS INLINE const uint16_t c_streamWidth = 8 * PARALLEL_BYTE; const uint16_t c_accRegWidthx3 = c_streamWidth * 3; // transfer data module ap_uint<c_accRegWidthx3> wbuf = accRegister; uint8_t bytesWritten = 0; uint8_t updBInAcc = bytesInAcc; uint8_t bitsInAcc = bytesInAcc * 8; // write block data send_data_main_loop: for (int i = 0; i < size2Write; i += PARALLEL_BYTE) { #pragma HLS PIPELINE II = 1 if (i < (const int)(size2Write - bytesInAcc)) { wbuf.range((bitsInAcc + c_streamWidth - 1), bitsInAcc) = inStream.read(); updBInAcc += PARALLEL_BYTE; } ap_uint<c_streamWidth> tmpV = wbuf; outStream << tmpV; if (i > (const int)(size2Write - PARALLEL_BYTE)) { bytesWritten = size2Write - i; break; } wbuf >>= c_streamWidth; updBInAcc -= PARALLEL_BYTE; } accRegister = (wbuf >> (bytesWritten * 8)); bytesInAcc = updBInAcc - bytesWritten; } template <uint8_t IN_BYTES> int generateFSETable(hls::stream<uint32_t>& fseTableStream, hls::stream<ap_uint<IN_BYTES * 8> >& inStream, ap_uint<IN_BYTES * 8 * 2>& fseAcc, uint8_t& bytesInAcc, uint8_t& tableLog, uint16_t maxChar, xfSymbolCompMode_t fseMode, xfSymbolCompMode_t prevFseMode, const int16_t* defDistTable, int16_t* prevDistribution) { const uint16_t c_inputByte = IN_BYTES; const uint16_t c_streamWidth = 8 * c_inputByte; const uint16_t c_accRegWidth = c_streamWidth * 2; uint32_t bytesAvailable = bytesInAcc; uint8_t bitsAvailable = bytesInAcc * 8; uint32_t bitsConsumed = 0; int totalBytesConsumed = 0; uint32_t totalBitsConsumed = 0; int remaining = 0; int threshold = 0; bool previous0 = false; uint16_t charnum = 0; int16_t normalizedCounter[64]; // initialize normalized counter for (int i = 0; i < 64; ++i) normalizedCounter[i] = 0; if (fseMode == FSE_COMPRESSED_MODE) { // read input bytes if (bytesAvailable < c_inputByte) { fseAcc.range((bitsAvailable + c_streamWidth - 1), bitsAvailable) = inStream.read(); bytesAvailable += c_inputByte; bitsAvailable += c_streamWidth; } uint8_t accuracyLog = (fseAcc & 0xF) + 5; tableLog = accuracyLog; fseAcc >>= 4; bitsAvailable -= 4; totalBitsConsumed = 4; remaining = (1 << accuracyLog) + 1; threshold = 1 << accuracyLog; accuracyLog += 1; fsegenNormDistTable: while ((remaining > 1) & (charnum <= maxChar)) { #pragma HLS PIPELINE II = 1 bitsConsumed = 0; // read input bytes if (bytesAvailable < c_inputByte - 1) { fseAcc.range((bitsAvailable + c_streamWidth - 1), bitsAvailable) = inStream.read(); bytesAvailable += c_inputByte; bitsAvailable += c_streamWidth; } if (previous0) { unsigned n0 = 0; if ((fseAcc & 0xFFFF) == 0xFFFF) { n0 += 24; bitsConsumed += 16; } else if ((fseAcc & 3) == 3) { n0 += 3; bitsConsumed += 2; } else { n0 += fseAcc & 3; bitsConsumed += 2; previous0 = false; } charnum += n0; } else { int16_t max = (2 * threshold - 1) - remaining; int count; uint8_t c1 = 0; if ((fseAcc & (threshold - 1)) < max) { c1 = 1; count = fseAcc & (threshold - 1); bitsConsumed += accuracyLog - 1; } else { c1 = 2; count = fseAcc & (2 * threshold - 1); if (count >= threshold) count -= max; bitsConsumed += accuracyLog; } --count; /* extra accuracy */ remaining -= ((count < 0) ? -count : count); /* -1 means +1 */ normalizedCounter[charnum++] = count; previous0 = ((count == 0) ? 1 : 0); genDTableIntLoop: while (remaining < threshold) { --accuracyLog; threshold >>= 1; } } fseAcc >>= bitsConsumed; bitsAvailable -= bitsConsumed; totalBitsConsumed += bitsConsumed; bytesAvailable = bitsAvailable >> 3; } totalBytesConsumed += (totalBitsConsumed + 7) >> 3; bytesInAcc = bytesAvailable; // clear accumulator, so that it is byte aligned fseAcc >>= (bitsAvailable & 7); // copy to prevDistribution table for (int i = 0; i < 64; ++i) prevDistribution[i] = normalizedCounter[i]; } else if (fseMode == PREDEFINED_MODE) { /*TODO: use fixed table directly*/ for (int i = 0; i < maxChar + 1; ++i) { normalizedCounter[i] = defDistTable[i]; prevDistribution[i] = defDistTable[i]; } charnum = maxChar + 1; } else if (fseMode == RLE_MODE) { // next state for entire table is 0 // accuracy log is 0 // read input bytes if (bytesAvailable < 1) { fseAcc.range((bitsAvailable + c_streamWidth - 1), bitsAvailable) = inStream.read(); bytesAvailable += c_inputByte; bitsAvailable += c_streamWidth; } uint8_t symbol = (uint8_t)fseAcc; fseAcc >>= 8; bytesInAcc = bytesAvailable - 1; fseTableStream << 1; // tableSize fseTableStream << symbol; tableLog = 0; return 1; } else if (fseMode == REPEAT_MODE) { // check if previous mode was RLE fseTableStream << 0xFFFFFFFF; // all 1's to indicate use previous table return 0; } else { // else -> Error: invalid fse mode return 0; } // Table Generation const uint32_t tableSize = 1 << tableLog; uint32_t highThreshold = tableSize - 1; uint16_t symbolNext[64]; int16_t symTable[513]; // initialize table for (uint32_t i = 0; i < tableSize; ++i) symTable[i] = 0; fse_gen_next_symbol_table: for (uint16_t i = 0; i < charnum; i++) { #pragma HLS PIPELINE II = 1 if (normalizedCounter[i] == -1) { symTable[highThreshold] = i; // symbol, assign lower 8-bits --highThreshold; symbolNext[i] = 1; } else { symbolNext[i] = normalizedCounter[i]; } } uint32_t mask = tableSize - 1; const uint32_t step = (tableSize >> 1) + (tableSize >> 3) + 3; uint32_t pos = 0; fse_gen_symbol_table_outer: for (uint16_t i = 0; i < charnum; ++i) { fse_gen_symbol_table: for (int j = 0; j < normalizedCounter[i];) { #pragma HLS PIPELINE II = 1 if (pos > highThreshold) { pos = (pos + step) & mask; } else { symTable[pos] = i; pos = (pos + step) & mask; ++j; } } } // FSE table fseTableStream << tableSize; gen_fse_final_table: for (uint32_t i = 0; i < tableSize; i++) { #pragma HLS PIPELINE II = 1 uint8_t symbol = (uint8_t)symTable[i]; uint16_t nextState = symbolNext[symbol]++; uint16_t nBits = (uint8_t)(tableLog - (31 - __builtin_clz(nextState))); uint32_t tblVal = ((uint32_t)((nextState << nBits) - tableSize) << 16) + ((uint32_t)nBits << 8) + symbol; fseTableStream << tblVal; } return totalBytesConsumed; } template <uint8_t IN_BYTES, uint8_t BLOCK_SIZE_KB> void fseStreamStatesLL(uint32_t* litFSETable, uint32_t* oftFSETable, uint32_t* mlnFSETable, ap_uint<IN_BYTES * 8>* bitStream, int byteIndx, uint8_t lastByteValidBits, uint32_t seqCnt, uint8_t* accuracyLog, hls::stream<uint8_t>& litsymbolStream, hls::stream<uint8_t>& mlsymbolStream, hls::stream<uint8_t>& ofsymbolStream, hls::stream<ap_uint<32> >& litbsWordStream, hls::stream<ap_uint<32> >& mlbsWordStream, hls::stream<ap_uint<32> >& ofbsWordStream, hls::stream<ap_uint<5> >& litextraBitStream, hls::stream<ap_uint<5> >& mlextraBitStream) { // fetch fse states from fse sequence bitstream and stream out for further processing const uint8_t c_inputByte = IN_BYTES; const uint16_t c_streamWidth = 8 * c_inputByte; const uint16_t c_accRegWidth = c_streamWidth * 2; const uint8_t c_bsBytes = c_streamWidth / 8; uint16_t fseStateLL, fseStateOF, fseStateML; // literal_length, offset, match_length states FseBSState bsStateLL, bsStateOF, bsStateML; // offset, match_length and literal_length ap_uint<c_accRegWidth> acchbs; uint8_t bitsInAcc = lastByteValidBits; uint8_t bitsToRead = 0; uint8_t bytesToRead = 0; acchbs.range(c_streamWidth - 1, 0) = bitStream[byteIndx--]; uint8_t byte_0 = acchbs.range(bitsInAcc - 1, bitsInAcc - 8); // find valid last bit, bitstream read in reverse order fsedseq_skip_zero: for (uint8_t i = 7; i >= 0; --i) { #pragma HLS UNROLL #pragma HLS LOOP_TRIPCOUNT min = 1 max = 7 if ((byte_0 & (1 << i)) > 0) { --bitsInAcc; break; } --bitsInAcc; // discount higher bits which are zero } fsedseq_fill_acc: while ((bitsInAcc + c_streamWidth < c_accRegWidth) && (byteIndx > -1)) { #pragma HLS PIPELINE II = 1 acchbs <<= c_streamWidth; acchbs.range(c_streamWidth - 1, 0) = bitStream[byteIndx--]; bitsInAcc += c_streamWidth; } // Read literal_length, offset and match_length states from input stream // get *accuracyLog bits from higher position in accuracyLog, mask out higher scrap bits uint16_t mskLL = ((1 << accuracyLog[0]) - 1); fseStateLL = ((acchbs >> (bitsInAcc - accuracyLog[0])) & mskLL); uint16_t mskOF = ((1 << accuracyLog[1]) - 1); fseStateOF = ((acchbs >> (bitsInAcc - (accuracyLog[0] + accuracyLog[1]))) & mskOF); uint16_t mskML = ((1 << accuracyLog[2]) - 1); fseStateML = ((acchbs >> (bitsInAcc - (accuracyLog[0] + accuracyLog[1] + accuracyLog[2]))) & mskML); bitsInAcc -= (accuracyLog[0] + accuracyLog[1] + accuracyLog[2]); enum FSEDState_t { READ_FSE = 0, GET_FSE }; FSEDState_t smState = READ_FSE; uint8_t bitCntLML, bitCntLMO; uint32_t bswLL, bswML, bswOF; // read data to bitstream if necessary if (bitsInAcc < c_streamWidth && byteIndx > -1) { auto tmp = bitStream[byteIndx--]; acchbs = (acchbs << c_streamWidth) + tmp; bitsInAcc += c_streamWidth; } decode_sequence_bitStream: while (seqCnt) { #pragma HLS PIPELINE II = 1 uint8_t processedBits = 0; if (smState == READ_FSE) { // get state values and stream // stream fse metadata to decoding unit // get the state codes for offset, match_length and literal_length ap_uint<32> ofstateVal = oftFSETable[fseStateOF]; // offset bsStateOF.symbol = ofstateVal.range(7, 0); bsStateOF.bitCount = ofstateVal.range(15, 8); bsStateOF.nextState = ofstateVal.range(31, 16); uint8_t ofSymBits = bsStateOF.symbol; // also represents extra bits to be read, max 31-bits ofsymbolStream << bsStateOF.symbol; bswOF = acchbs >> (bitsInAcc - ofSymBits); litbsWordStream << bswLL; bitCntLMO = bsStateOF.bitCount; ap_uint<32> mlstateVal = mlnFSETable[fseStateML]; // match_length bsStateML.symbol = mlstateVal.range(7, 0); bsStateML.bitCount = mlstateVal.range(15, 8); bsStateML.nextState = mlstateVal.range(31, 16); uint8_t mlextraBits = c_extraBitsML[bsStateML.symbol]; // max 16-bits bswML = acchbs >> (bitsInAcc - ofSymBits - mlextraBits); mlsymbolStream << bsStateML.symbol; mlextraBitStream << mlextraBits; bitCntLML = bsStateML.bitCount; bitCntLMO += bsStateML.bitCount; ofbsWordStream << bswOF; ap_uint<32> litstateVal = litFSETable[fseStateLL]; // literal_length bsStateLL.symbol = litstateVal.range(7, 0); bsStateLL.bitCount = litstateVal.range(15, 8); bsStateLL.nextState = litstateVal.range(31, 16); uint8_t litextraBits = c_extraBitsLL[bsStateLL.symbol]; // max 16-bits bswLL = acchbs >> (bitsInAcc - ofSymBits - mlextraBits - litextraBits); litsymbolStream << bsStateLL.symbol; litextraBitStream << litextraBits; bitCntLML += bsStateLL.bitCount; bitCntLMO += bsStateLL.bitCount; mlbsWordStream << bswML; processedBits = ofSymBits + litextraBits + mlextraBits; mskLL = (((uint16_t)1 << bsStateLL.bitCount) - 1); mskML = (((uint16_t)1 << bsStateML.bitCount) - 1); mskOF = (((uint16_t)1 << bsStateOF.bitCount) - 1); smState = GET_FSE; } else if (smState == GET_FSE) { processedBits = bitCntLMO; // update state for next sequence // read bits to get states for literal_length, match_length, offset // accumulator must contain these many bits can be max 26-bits fseStateLL = ((acchbs >> (bitsInAcc - bsStateLL.bitCount)) & mskLL); fseStateLL += bsStateLL.nextState; fseStateML = ((acchbs >> (bitsInAcc - bitCntLML)) & mskML); fseStateML += bsStateML.nextState; fseStateOF = ((acchbs >> (bitsInAcc - bitCntLMO)) & mskOF); fseStateOF += bsStateOF.nextState; --seqCnt; smState = READ_FSE; } // read data to bitstream if necessary if ((bitsInAcc - processedBits) < c_streamWidth && byteIndx > -1) { auto tmp = bitStream[byteIndx--]; acchbs = (acchbs << c_streamWidth) + tmp; bitsInAcc += c_streamWidth - processedBits; } else { bitsInAcc -= processedBits; } } litbsWordStream << bswLL; } template <int LMO_WIDTH> void fseDecodeStatesLL(hls::stream<uint8_t>& litsymbolStream, hls::stream<uint8_t>& mlsymbolStream, hls::stream<uint8_t>& ofsymbolStream, hls::stream<ap_uint<32> >& litbsWordStream, hls::stream<ap_uint<32> >& mlbsWordStream, hls::stream<ap_uint<32> >& ofbsWordStream, hls::stream<ap_uint<5> >& litextraBitStream, hls::stream<ap_uint<5> >& mlextraBitStream, uint32_t seqCnt, uint32_t litCnt, ap_uint<LMO_WIDTH>* prevOffsets, hls::stream<ap_uint<LMO_WIDTH> >& litLenStream, hls::stream<ap_uint<LMO_WIDTH> >& offsetStream, hls::stream<ap_uint<LMO_WIDTH> >& matLenStream, hls::stream<bool>& litlenValidStream) { // calculate literal length, match length and offset values, stream them for sequence execution ap_uint<LMO_WIDTH> offsetVal; ap_uint<LMO_WIDTH> litLenCode; uint8_t ofi; bool checkLL = false; litbsWordStream.read(); // dump first word decode_sequence_codes: while (seqCnt) { #pragma HLS PIPELINE II = 1 // calculate offset and set prev offsets auto symbol = ofsymbolStream.read(); auto bsWord = ofbsWordStream.read(); auto extBit = symbol; uint32_t extVal = bsWord & (((uint64_t)1 << extBit) - 1); offsetVal = (1 << symbol) + extVal; ofi = 3; if (offsetVal > 3) { offsetVal -= 3; checkLL = false; } else { checkLL = true; } // calculate match length symbol = mlsymbolStream.read(); bsWord = mlbsWordStream.read(); extBit = mlextraBitStream.read(); uint16_t extVal1 = (bsWord & (((uint64_t)1 << extBit) - 1)); ap_uint<LMO_WIDTH> matchLenCode = c_baseML[symbol] + extVal1; matLenStream << matchLenCode; // calculate literal length symbol = litsymbolStream.read(); bsWord = litbsWordStream.read(); extBit = litextraBitStream.read(); extVal1 = (bsWord & (((uint64_t)1 << extBit) - 1)); litLenCode = c_baseLL[symbol] + extVal1; litlenValidStream << 1; litLenStream << litLenCode; litCnt -= litLenCode; // update offset as per literal length if (checkLL) { // repeat offsets 1 - 3 if (litLenCode == 0) { if (offsetVal == 3) { offsetVal = prevOffsets[0] - 1; ofi = 2; } else { ofi = offsetVal; offsetVal = prevOffsets[offsetVal]; } } else { ofi = offsetVal - 1; offsetVal = prevOffsets[offsetVal - 1]; } } checkLL = false; // OFFSET_WNU: write offset and update previous offsets offsetStream << offsetVal; // shift previous offsets auto prev1 = prevOffsets[1]; if (ofi > 1) { prevOffsets[2] = prev1; } if (ofi > 0) { prevOffsets[1] = prevOffsets[0]; prevOffsets[0] = offsetVal; } --seqCnt; } if (litCnt > 0) { litlenValidStream << 1; litLenStream << litCnt; matLenStream << 0; offsetStream << 0; } } template <uint8_t IN_BYTES = 4, uint8_t BLOCK_SIZE_KB, uint8_t LMO_WIDTH> void decodeSeqCoreLL(uint32_t* litFSETable, uint32_t* oftFSETable, uint32_t* mlnFSETable, ap_uint<IN_BYTES * 8>* bitStream, int bsIndx, uint8_t lastByteValidBits, uint32_t seqCnt, uint32_t litCnt, uint8_t* accuracyLog, ap_uint<LMO_WIDTH>* prevOffsets, hls::stream<ap_uint<LMO_WIDTH> >& litLenStream, hls::stream<ap_uint<LMO_WIDTH> >& offsetStream, hls::stream<ap_uint<LMO_WIDTH> >& matLenStream, hls::stream<bool>& litlenValidStream) { // core module for decoding fse sequences const uint8_t c_intlStreamDepth = 16; // Internal streams hls::stream<uint8_t> litsymbolStream("litsymbolStream"); hls::stream<uint8_t> mlsymbolStream("mlsymbolStream"); hls::stream<uint8_t> ofsymbolStream("ofsymbolStream"); hls::stream<ap_uint<32> > litbsWordStream("litbsWordStream"); hls::stream<ap_uint<32> > mlbsWordStream("mlbsWordStream"); hls::stream<ap_uint<32> > ofbsWordStream("ofbsWordStream"); hls::stream<ap_uint<5> > litextraBitStream("litextraBitStream"); hls::stream<ap_uint<5> > mlextraBitStream("mlextraBitStream"); #pragma HLS STREAM variable = litsymbolStream depth = c_intlStreamDepth #pragma HLS STREAM variable = mlsymbolStream depth = c_intlStreamDepth #pragma HLS STREAM variable = ofsymbolStream depth = c_intlStreamDepth #pragma HLS STREAM variable = litbsWordStream depth = c_intlStreamDepth #pragma HLS STREAM variable = mlbsWordStream depth = c_intlStreamDepth #pragma HLS STREAM variable = ofbsWordStream depth = c_intlStreamDepth #pragma HLS STREAM variable = litextraBitStream depth = c_intlStreamDepth #pragma HLS STREAM variable = mlextraBitStream depth = c_intlStreamDepth #pragma HLS dataflow fseStreamStatesLL<IN_BYTES, BLOCK_SIZE_KB>(litFSETable, oftFSETable, mlnFSETable, bitStream, bsIndx, lastByteValidBits, seqCnt, accuracyLog, litsymbolStream, mlsymbolStream, ofsymbolStream, litbsWordStream, mlbsWordStream, ofbsWordStream, litextraBitStream, mlextraBitStream); fseDecodeStatesLL<LMO_WIDTH>(litsymbolStream, mlsymbolStream, ofsymbolStream, litbsWordStream, mlbsWordStream, ofbsWordStream, litextraBitStream, mlextraBitStream, seqCnt, litCnt, prevOffsets, litLenStream, offsetStream, matLenStream, litlenValidStream); } template <uint8_t IN_BYTES, uint8_t BLOCK_SIZE_KB> void fseStreamStates(uint32_t* litFSETable, uint32_t* oftFSETable, uint32_t* mlnFSETable, ap_uint<IN_BYTES * 8>* bitStream, int byteIndx, uint8_t lastByteValidBits, uint32_t seqCnt, uint8_t* accuracyLog, hls::stream<uint8_t>& symbolStream, hls::stream<ap_uint<32> >& bsWordStream, hls::stream<ap_uint<5> >& extraBitStream) { // fetch fse states from fse sequence bitstream and stream out for further processing const uint8_t c_inputByte = IN_BYTES; const uint16_t c_streamWidth = 8 * c_inputByte; const uint16_t c_accRegWidth = c_streamWidth * 2; const uint8_t c_bsBytes = c_streamWidth / 8; uint16_t fseStateLL, fseStateOF, fseStateML; // literal_length, offset, match_length states FseBSState bsStateLL, bsStateOF, bsStateML; // offset, match_length and literal_length ap_uint<c_accRegWidth> acchbs; uint8_t bitsInAcc = lastByteValidBits; uint8_t bitsToRead = 0; uint8_t bytesToRead = 0; acchbs.range(c_streamWidth - 1, 0) = bitStream[byteIndx--]; uint8_t byte_0 = acchbs.range(bitsInAcc - 1, bitsInAcc - 8); // find valid last bit, bitstream read in reverse order fsedseq_skip_zero: for (uint8_t i = 7; i >= 0; --i) { #pragma HLS UNROLL #pragma HLS LOOP_TRIPCOUNT min = 1 max = 7 if ((byte_0 & (1 << i)) > 0) { --bitsInAcc; break; } --bitsInAcc; // discount higher bits which are zero } fsedseq_fill_acc: while ((bitsInAcc + c_streamWidth < c_accRegWidth) && (byteIndx > -1)) { #pragma HLS PIPELINE II = 1 acchbs <<= c_streamWidth; acchbs.range(c_streamWidth - 1, 0) = bitStream[byteIndx--]; bitsInAcc += c_streamWidth; } // Read literal_length, offset and match_length states from input stream // get *accuracyLog bits from higher position in accuracyLog, mask out higher scrap bits uint64_t mskLL = ((1 << accuracyLog[0]) - 1); fseStateLL = ((acchbs >> (bitsInAcc - accuracyLog[0])) & mskLL); uint64_t mskOF = ((1 << accuracyLog[1]) - 1); fseStateOF = ((acchbs >> (bitsInAcc - (accuracyLog[0] + accuracyLog[1]))) & mskOF); uint64_t mskML = ((1 << accuracyLog[2]) - 1); fseStateML = ((acchbs >> (bitsInAcc - (accuracyLog[0] + accuracyLog[1] + accuracyLog[2]))) & mskML); bitsInAcc -= (accuracyLog[0] + accuracyLog[1] + accuracyLog[2]); enum FSEDState_t { LITLEN = 0, MATLEN, OFFSET, NEXTSTATE }; FSEDState_t smState = OFFSET; uint8_t bitCntLML, bitCntLMO; uint32_t bswLL, bswML, bswOF; decode_sequence_bitStream: while (seqCnt) { #pragma HLS PIPELINE II = 1 // read data to bitstream if necessary if (bitsInAcc < c_streamWidth && byteIndx > -1) { auto tmp = bitStream[byteIndx--]; acchbs = (acchbs << c_streamWidth) + tmp; bitsInAcc += c_streamWidth; } uint32_t stateVal; uint8_t extraBits; // get state values and stream // stream fse metadata to decoding unit if (smState == LITLEN) { bsWordStream << bswOF; stateVal = litFSETable[fseStateLL]; // literal_length bsStateLL.symbol = stateVal & 0x000000FF; bsStateLL.nextState = (stateVal >> 16) & 0x0000FFFF; bsStateLL.bitCount = (stateVal >> 8) & 0x000000FF; extraBits = c_extraBitsLL[bsStateLL.symbol]; // max 16-bits bitsInAcc -= extraBits; symbolStream << bsStateLL.symbol; bswLL = acchbs >> bitsInAcc; extraBitStream << extraBits; bitCntLML += bsStateLL.bitCount; bitCntLMO += bsStateLL.bitCount; smState = NEXTSTATE; } else if (smState == MATLEN) { stateVal = mlnFSETable[fseStateML]; // match_length bsStateML.symbol = stateVal & 0x000000FF; bsStateML.nextState = (stateVal >> 16) & 0x0000FFFF; bsStateML.bitCount = (stateVal >> 8) & 0x000000FF; extraBits = c_extraBitsML[bsStateML.symbol]; // max 16-bits bitsInAcc -= extraBits; symbolStream << bsStateML.symbol; bswML = acchbs >> bitsInAcc; extraBitStream << extraBits; bitCntLML = bsStateML.bitCount; bitCntLMO += bsStateML.bitCount; smState = LITLEN; } else if (smState == OFFSET) { // get the state codes for offset, match_length and literal_length stateVal = oftFSETable[fseStateOF]; // offset bsStateOF.symbol = stateVal & 0x000000FF; bsStateOF.nextState = (stateVal >> 16) & 0x0000FFFF; bsStateOF.bitCount = (stateVal >> 8) & 0x000000FF; extraBits = bsStateOF.symbol; // also represents extra bits to be read, max 31-bits bitsInAcc -= extraBits; symbolStream << bsStateOF.symbol; bswOF = acchbs >> bitsInAcc; bsWordStream << bswLL; bitCntLMO = bsStateOF.bitCount; smState = MATLEN; } else { bsWordStream << bswML; // update state for next sequence // read bits to get states for literal_length, match_length, offset // accumulator must contain these many bits can be max 26-bits mskLL = (((uint64_t)1 << bsStateLL.bitCount) - 1); fseStateLL = ((acchbs >> (bitsInAcc - bsStateLL.bitCount)) & mskLL); fseStateLL += bsStateLL.nextState; mskML = (((uint64_t)1 << bsStateML.bitCount) - 1); fseStateML = ((acchbs >> (bitsInAcc - bitCntLML)) & mskML); fseStateML += bsStateML.nextState; mskOF = (((uint64_t)1 << bsStateOF.bitCount) - 1); fseStateOF = ((acchbs >> (bitsInAcc - bitCntLMO)) & mskOF); fseStateOF += bsStateOF.nextState; bitsInAcc -= bitCntLMO; --seqCnt; smState = OFFSET; } } bsWordStream << bswLL; } template <int LMO_WIDTH> void fseDecodeStates(hls::stream<uint8_t>& symbolStream, hls::stream<ap_uint<32> >& bsWordStream, hls::stream<ap_uint<5> >& extraBitStream, uint32_t seqCnt, uint32_t litCnt, ap_uint<LMO_WIDTH>* prevOffsets, hls::stream<ap_uint<LMO_WIDTH> >& litLenStream, hls::stream<ap_uint<LMO_WIDTH> >& offsetStream, hls::stream<ap_uint<LMO_WIDTH> >& matLenStream, hls::stream<bool>& litlenValidStream) { // calculate literal length, match length and offset values, stream them for sequence execution enum FSEDecode_t { LITLEN = 0, MATLEN, OFFSET_CALC, OFFSET_WNU }; FSEDecode_t sqdState = OFFSET_CALC; ap_uint<LMO_WIDTH> offsetVal; ap_uint<LMO_WIDTH> litLenCode; uint8_t ofi; bool checkLL = false; bsWordStream.read(); // dump first word decode_sequence_codes: while (seqCnt) { #pragma HLS PIPELINE II = 1 if (sqdState == OFFSET_CALC) { // calculate offset and set prev offsets auto symbol = symbolStream.read(); auto bsWord = bsWordStream.read(); auto extBit = symbol; uint32_t extVal = bsWord & (((uint64_t)1 << extBit) - 1); offsetVal = (1 << symbol) + extVal; ofi = 3; if (offsetVal > 3) { offsetVal -= 3; checkLL = false; } else { checkLL = true; } sqdState = MATLEN; } else if (sqdState == MATLEN) { // calculate match length auto symbol = symbolStream.read(); auto bsWord = bsWordStream.read(); auto extBit = extraBitStream.read(); uint16_t extVal = (bsWord & (((uint64_t)1 << extBit) - 1)); ap_uint<LMO_WIDTH> matchLenCode = c_baseML[symbol] + extVal; matLenStream << matchLenCode; sqdState = LITLEN; } else if (sqdState == LITLEN) { // calculate literal length auto symbol = symbolStream.read(); auto bsWord = bsWordStream.read(); auto extBit = extraBitStream.read(); uint16_t extVal = (bsWord & (((uint64_t)1 << extBit) - 1)); litLenCode = c_baseLL[symbol] + extVal; litlenValidStream << 1; litLenStream << litLenCode; litCnt -= litLenCode; // update offset as per literal length if (checkLL) { // repeat offsets 1 - 3 if (litLenCode == 0) { if (offsetVal == 3) { offsetVal = prevOffsets[0] - 1; ofi = 2; } else { ofi = offsetVal; offsetVal = prevOffsets[offsetVal]; } } else { ofi = offsetVal - 1; offsetVal = prevOffsets[offsetVal - 1]; } } checkLL = false; sqdState = OFFSET_WNU; } else { // OFFSET_WNU: write offset and update previous offsets offsetStream << offsetVal; // shift previous offsets auto prev1 = prevOffsets[1]; if (ofi > 1) { prevOffsets[2] = prev1; } if (ofi > 0) { prevOffsets[1] = prevOffsets[0]; prevOffsets[0] = offsetVal; } sqdState = OFFSET_CALC; --seqCnt; } } if (litCnt > 0) { litlenValidStream << 1; litLenStream << litCnt; matLenStream << 0; offsetStream << 0; } } template <uint8_t IN_BYTES, uint8_t BLOCK_SIZE_KB, uint8_t LMO_WIDTH> void decodeSeqCore(uint32_t* litFSETable, uint32_t* oftFSETable, uint32_t* mlnFSETable, ap_uint<IN_BYTES * 8>* bitStream, int bsIndx, uint8_t lastByteValidBits, uint32_t seqCnt, uint32_t litCnt, uint8_t* accuracyLog, ap_uint<LMO_WIDTH>* prevOffsets, hls::stream<ap_uint<LMO_WIDTH> >& litLenStream, hls::stream<ap_uint<LMO_WIDTH> >& offsetStream, hls::stream<ap_uint<LMO_WIDTH> >& matLenStream, hls::stream<bool>& litlenValidStream) { // core module for decoding fse sequences const uint8_t c_intlStreamDepth = 16; // Internal streams hls::stream<uint8_t> symbolStream("symbolStream"); hls::stream<ap_uint<32> > bsWordStream("bsWordStream"); hls::stream<ap_uint<5> > extraBitStream("extraBitStream"); #pragma HLS STREAM variable = symbolStream depth = c_intlStreamDepth #pragma HLS STREAM variable = bsWordStream depth = c_intlStreamDepth #pragma HLS STREAM variable = extraBitStream depth = c_intlStreamDepth #pragma HLS dataflow fseStreamStates<IN_BYTES, BLOCK_SIZE_KB>(litFSETable, oftFSETable, mlnFSETable, bitStream, bsIndx, lastByteValidBits, seqCnt, accuracyLog, symbolStream, bsWordStream, extraBitStream); fseDecodeStates<LMO_WIDTH>(symbolStream, bsWordStream, extraBitStream, seqCnt, litCnt, prevOffsets, litLenStream, offsetStream, matLenStream, litlenValidStream); } template <uint8_t IN_BYTES, uint8_t BLOCK_SIZE_KB, uint8_t LMO_WIDTH, bool LOW_LATENCY = false> inline void fseDecode(ap_uint<IN_BYTES * 8 * 2> accword, uint8_t bytesInAcc, hls::stream<ap_uint<IN_BYTES * 8> >& inStream, uint32_t* litFSETable, uint32_t* oftFSETable, uint32_t* mlnFSETable, uint32_t seqCnt, uint32_t litCount, uint32_t remBlockSize, uint8_t* accuracyLog, ap_uint<LMO_WIDTH>* prevOffsets, hls::stream<ap_uint<LMO_WIDTH> >& litLenStream, hls::stream<ap_uint<LMO_WIDTH> >& offsetStream, hls::stream<ap_uint<LMO_WIDTH> >& matLenStream, hls::stream<bool>& litlenValidStream) { // decode fse encoded bitstream using prebuilt fse tables const uint8_t c_inputByte = IN_BYTES; const uint8_t c_streamWidth = 8 * c_inputByte; const uint16_t c_accRegWidth = c_streamWidth * 2; const uint8_t c_bsBytes = c_streamWidth / 8; ap_uint<c_streamWidth> bitStream[(BLOCK_SIZE_KB * 1024) / c_bsBytes]; #pragma HLS BIND_STORAGE variable = bitStream type = ram_t2p impl = uram uint8_t bitsInAcc = bytesInAcc * 8; // copy data from bitstream to buffer ap_uint<c_accRegWidth> bsbuff = accword; int bsIdx = 0; uint8_t bytesWritten = c_bsBytes; uint8_t updBInAcc = bytesInAcc; // write block data fsedseq_fill_bitstream: for (int i = 0; i < remBlockSize; i += c_bsBytes) { // TODO: biggest culprit as of now #pragma HLS pipeline II = 1 if (i < (const int)(remBlockSize - bytesInAcc)) { if (bytesInAcc < c_bsBytes) { bsbuff.range(bitsInAcc + c_streamWidth - 1, bitsInAcc) = inStream.read(); updBInAcc += c_inputByte; } } ap_uint<c_streamWidth> tmpv = bsbuff.range(c_streamWidth - 1, 0); bitStream[bsIdx++] = tmpv; if (i > (const int)(remBlockSize - c_bsBytes)) { bytesWritten = (remBlockSize - i); bsbuff >>= (bytesWritten * 8); updBInAcc -= bytesWritten; } else { bsbuff >>= c_streamWidth; updBInAcc -= c_bsBytes; } } if (LOW_LATENCY) { decodeSeqCoreLL<IN_BYTES, BLOCK_SIZE_KB, LMO_WIDTH>( litFSETable, oftFSETable, mlnFSETable, bitStream, bsIdx - 1, 8 * bytesWritten, seqCnt, litCount, accuracyLog, prevOffsets, litLenStream, offsetStream, matLenStream, litlenValidStream); } else { decodeSeqCore<IN_BYTES, BLOCK_SIZE_KB, LMO_WIDTH>(litFSETable, oftFSETable, mlnFSETable, bitStream, bsIdx - 1, 8 * bytesWritten, seqCnt, litCount, accuracyLog, prevOffsets, litLenStream, offsetStream, matLenStream, litlenValidStream); } } template <uint8_t IN_BYTES> void fseDecodeHuffWeight(hls::stream<ap_uint<IN_BYTES * 8> >& inStream, uint32_t remSize, ap_uint<IN_BYTES * 8 * 2>& accHuff, uint8_t& bytesInAcc, uint8_t accuracyLog, uint32_t* fseTable, uint8_t* weights, uint16_t& weightCnt, uint8_t& huffDecoderTableLog) { //#pragma HLS INLINE const uint8_t c_inputByte = IN_BYTES; const uint8_t c_streamWidth = 8 * c_inputByte; uint8_t bitsInAcc = bytesInAcc * 8; uint8_t bitStream[128]; int bsByteIndx = remSize - 1; // copy data from bitstream to buffer uint32_t itrCnt = 1 + ((remSize - 1) / c_inputByte); uint32_t k = 0; ap_uint<c_streamWidth> input; fseDecHF_read_input: for (uint32_t i = 0; i < itrCnt; ++i) { input = inStream.read(); bitsInAcc += c_streamWidth; for (uint8_t j = 0; j < c_inputByte && k < remSize; ++j, ++k) { #pragma HLS PIPELINE II = 1 bitStream[k] = input.range(7, 0); input >>= 8; bitsInAcc -= 8; } } accHuff = input; bytesInAcc = bitsInAcc >> 3; // decode FSE bitStream using fse table to get huffman weights // skip initial 0 bits and single 1 bit uint32_t accState; uint32_t codeIdx = 0; uint8_t bitsToRead = 0; bitsInAcc = 0; int32_t rembits = remSize * 8; uint8_t fseState[2]; FseBSState bsState[2]; // find beginning of the stream accState = bitStream[bsByteIndx--]; bitsInAcc = 8; for (ap_uint<4> i = 7; i >= 0; --i) { #pragma HLS UNROLL if ((accState & (1 << i)) > 0) { --bitsInAcc; break; } --bitsInAcc; // discount higher bits which are zero } rembits -= (8 - bitsInAcc); // Read bits needed for first two states bitsToRead = accuracyLog * 2; if (bitsToRead > bitsInAcc) { uint8_t bytesToRead = 1 + ((bitsToRead - bitsInAcc - 1) / 8); for (uint8_t i = 0; i < bytesToRead; ++i) { uint8_t tmp = bitStream[bsByteIndx--]; accState <<= 8; accState += tmp; bitsInAcc += 8; } } // Read initial state1 and state2 // get readBits bits from higher position in accuracyLog, mask out higher scrap bits // read state 1 bitsInAcc -= accuracyLog; uint16_t msk = ((1 << accuracyLog) - 1); fseState[0] = ((accState >> bitsInAcc) & msk); // read state 2 bitsInAcc -= accuracyLog; msk = ((1 << accuracyLog) - 1); fseState[1] = ((accState >> bitsInAcc) & msk); rembits -= (accuracyLog * 2); bool stateIdx = 0; // 0 for even, 1 for odd bool overflow = false; uint32_t totalWeights = 0; // get the weight, bitCount and nextState uint32_t stateVal = fseTable[fseState[stateIdx]]; uint8_t cw = (uint8_t)(stateVal & 0xFF); weights[codeIdx++] = cw; totalWeights += (1 << cw) >> 1; fse_decode_huff_weights: for (; rembits >= 0;) { #pragma HLS PIPELINE II = 1 // get other values bsState[stateIdx].nextState = (stateVal >> 16) & 0x0000FFFF; bsState[stateIdx].bitCount = (stateVal >> 8) & 0x000000FF; uint8_t bitsToRead = bsState[stateIdx].bitCount; if (bitsToRead > bitsInAcc) { uint8_t tmp = 0; if (bsByteIndx > -1) { // max 1 read is required, since accuracy log <= 6 tmp = bitStream[bsByteIndx--]; } accState <<= 8; accState += tmp; bitsInAcc += 8; } // get next fse state bitsInAcc -= bitsToRead; uint8_t msk = ((1 << bitsToRead) - 1); fseState[stateIdx] = ((accState >> bitsInAcc) & msk); fseState[stateIdx] += bsState[stateIdx].nextState; rembits -= bitsToRead; // switch state flow stateIdx = (stateIdx + 1) & 1; // 0 if 1, 1 if 0 stateVal = fseTable[fseState[stateIdx]]; cw = (uint8_t)(stateVal & 0xFF); weights[codeIdx++] = cw; totalWeights += (1 << cw) >> 1; } huffDecoderTableLog = 1 + (31 - __builtin_clz(totalWeights)); // add last weight uint16_t lw = (1 << huffDecoderTableLog) - totalWeights; weights[codeIdx++] = 1 + (31 - __builtin_clz(lw)); weightCnt = codeIdx; } template <int MAX_CODELEN> void huffGenLookupTable(uint8_t* weights, HuffmanTable* huffTable, uint8_t accuracyLog, uint16_t weightCnt) { // create huffman lookup table // regenerate huffman tree using literal bit-lengths typedef ap_uint<MAX_CODELEN + 1> LCL_Code_t; LCL_Code_t first_codeword[MAX_CODELEN + 1]; ap_uint<32> bitlen_histogram[MAX_CODELEN + 1]; ap_uint<4> bitlens[256]; #pragma HLS ARRAY_PARTITION variable = first_codeword complete #pragma HLS ARRAY_PARTITION variable = bitlen_histogram complete uint16_t codes[256]; // initialize first_codeword and bitlength histogram hflkpt_init_blen_hist: for (uint8_t i = 0; i < MAX_CODELEN + 1; ++i) { #pragma HLS PIPELINE II = 1 #pragma HLS LOOP_TRIPCOUNT min = MAX_CODELEN max = MAX_CODELEN bitlen_histogram[i] = 0; } // read bit-lengths hflkpt_fill_blen_hist: for (uint16_t i = 0; i < weightCnt; ++i) { #pragma HLS PIPELINE II = 1 // convert weight to bitlen uint8_t cblen = weights[i]; bitlen_histogram[cblen]++; if (cblen > 0) cblen = (accuracyLog + 1 - cblen); bitlens[i] = cblen; } // generate first codes first_codeword[0] = bitlen_histogram[0]; uint16_t nextCode = 0; hflkpt_initial_codegen: for (uint8_t i = 1; i < accuracyLog + 1; ++i) { #pragma HLS PIPELINE II = 1 #pragma HLS LOOP_TRIPCOUNT min = 0 max = 8 uint16_t cur = nextCode; nextCode += (bitlen_histogram[i] << (i - 1)); first_codeword[i] = cur; } hflkpt_codegen_outer: for (int i = 0; i < weightCnt; ++i) { uint32_t hfw = weights[i]; const uint32_t len = (1 << hfw) >> 1; const auto fcw = first_codeword[hfw]; hflkpt_codegen: for (uint16_t u = fcw; u < fcw + len; ++u) { #pragma HLS PIPELINE II = 1 huffTable[u].symbol = i; huffTable[u].bitlen = bitlens[i]; } first_codeword[hfw] = fcw + len; } } template <int MAX_CODELEN> void code_generator(uint8_t* weights, ap_uint<MAX_CODELEN + 1>* codeOffsets, ap_uint<8>* bl1Codes, ap_uint<8>* bl2Codes, ap_uint<8>* bl3Codes, ap_uint<8>* bl4Codes, ap_uint<8>* bl5Codes, ap_uint<8>* bl6Codes, ap_uint<8>* bl7Codes, ap_uint<8>* bl8Codes, ap_uint<8>* bl9Codes, ap_uint<8>* bl10Codes, ap_uint<8>* bl11Codes, uint8_t accuracyLog, uint16_t weightCnt) { // regenerate huffman tree using literal bit-lengths typedef ap_uint<MAX_CODELEN + 1> LCL_Code_t; LCL_Code_t first_codeword[MAX_CODELEN + 1]; ap_uint<8> bitlen_histogram[MAX_CODELEN + 1]; ap_uint<4> bitlens[256]; #pragma HLS ARRAY_PARTITION variable = first_codeword complete #pragma HLS ARRAY_PARTITION variable = bitlen_histogram complete uint16_t codes[256]; // initialize first_codeword and bitlength histogram hflkpt_init_blen_hist: for (uint8_t i = 0; i < MAX_CODELEN + 1; ++i) { #pragma HLS PIPELINE II = 1 #pragma HLS LOOP_TRIPCOUNT min = MAX_CODELEN max = MAX_CODELEN bitlen_histogram[i] = 0; } // read bit-lengths hflkpt_fill_blen_hist: for (uint16_t i = 0; i < weightCnt; ++i) { #pragma HLS PIPELINE II = 1 // convert weight to bitlen uint8_t cblen = weights[i]; if (cblen > 0) cblen = (accuracyLog + 1 - cblen); bitlens[i] = cblen; bitlen_histogram[cblen]++; } // generate first codes first_codeword[0] = 0; codeOffsets[0] = 0; uint16_t nextCode = 0; hflkpt_initial_codegen: for (int8_t i = accuracyLog - 1; i >= 0; --i) { #pragma HLS PIPELINE II = 1 #pragma HLS LOOP_TRIPCOUNT min = 0 max = 11 uint16_t cur = nextCode; nextCode += (bitlen_histogram[i + 1]); nextCode >>= 1; first_codeword[i] = cur; codeOffsets[i] = cur; } uint16_t blen = 0; CodeGen: for (uint16_t i = 0; i < weightCnt; i++) { #pragma HLS PIPELINE II = 1 blen = bitlens[i]; if (blen != 0) { switch (blen) { case 1: bl1Codes[first_codeword[0]] = i; break; case 2: bl2Codes[first_codeword[1]] = i; break; case 3: bl3Codes[first_codeword[2]] = i; break; case 4: bl4Codes[first_codeword[3]] = i; break; case 5: bl5Codes[first_codeword[4]] = i; break; case 6: bl6Codes[first_codeword[5]] = i; break; case 7: bl7Codes[first_codeword[6]] = i; break; case 8: bl8Codes[first_codeword[7]] = i; break; case 9: bl9Codes[ap_uint<8>(first_codeword[8])] = i; break; case 10: bl10Codes[ap_uint<8>(first_codeword[9])] = i; break; case 11: bl11Codes[ap_uint<8>(first_codeword[10])] = i; break; default: assert(0); break; } first_codeword[blen - 1]++; } } } template <uint8_t PARALLEL_BYTE> void huffDecodeLiteralsSeq(hls::stream<ap_uint<8 * PARALLEL_BYTE> >& inStream, bool quadStream, ap_uint<8 * PARALLEL_BYTE * 2> accHuff, uint8_t bytesInAcc, uint32_t remSize, uint32_t regeneratedSize, uint8_t accuracyLog, uint16_t weightCnt, uint8_t* weights, hls::stream<ap_uint<8 * PARALLEL_BYTE> >& literalStream) { const uint16_t c_streamWidth = 8 * PARALLEL_BYTE; const uint16_t c_BSWidth = 16; const uint16_t c_accRegWidth = c_streamWidth * 2; const uint16_t c_accRegWidthx3 = c_streamWidth * 3; const uint16_t c_maxCodeLen = 11; // huffman lookup table HuffmanTable huffTable[2048]; #pragma HLS BIND_STORAGE variable = huffTable type = ram_t2p impl = bram ap_uint<c_BSWidth> bitStream[16 * 1024]; #pragma HLS BIND_STORAGE variable = bitStream type = ram_t2p impl = bram uint16_t decSize[4]; uint16_t cmpSize[4]; #pragma HLS ARRAY_PARTITION variable = cmpSize complete #pragma HLS ARRAY_PARTITION variable = decSize complete uint8_t streamCnt = 1; // get stream sizes if 4 streams are present if (quadStream) { streamCnt = 4; // Jump table is 6 bytes long // read from input if needed if (bytesInAcc < PARALLEL_BYTE) { accHuff.range(((PARALLEL_BYTE + bytesInAcc) * 8) - 1, bytesInAcc * 8) = inStream.read(); bytesInAcc += PARALLEL_BYTE; } // use 4 bytes // get decompressed size uint32_t dcmpSize = (regeneratedSize + 3) / 4; decSize[0] = decSize[1] = decSize[2] = dcmpSize; decSize[3] = regeneratedSize - (dcmpSize * 3); // get compressed size cmpSize[0] = accHuff; accHuff >>= 16; cmpSize[1] = accHuff; accHuff >>= 16; bytesInAcc -= 4; // read from input if needed if (bytesInAcc < 2) { accHuff.range(((PARALLEL_BYTE + bytesInAcc) * 8) - 1, bytesInAcc * 8) = inStream.read(); bytesInAcc += PARALLEL_BYTE; } cmpSize[2] = accHuff; accHuff >>= 16; bytesInAcc -= 2; cmpSize[3] = remSize - (6 + cmpSize[0] + cmpSize[1] + cmpSize[2]); } else { decSize[0] = regeneratedSize; cmpSize[0] = remSize; } // generate huffman lookup table huffGenLookupTable<c_maxCodeLen>(weights, huffTable, accuracyLog, weightCnt); // decode bitstreams ap_uint<(8 * PARALLEL_BYTE)> outBuffer; uint8_t obbytes = 0; ap_uint<c_accRegWidth> bsbuff = accHuff; uint8_t bitsInAcc = bytesInAcc * 8; ap_uint<c_streamWidth> bsacc[c_maxCodeLen + 1]; #pragma HLS ARRAY_PARTITION variable = bsacc complete decode_huff_bitstream_outer: for (uint8_t si = 0; si < streamCnt; ++si) { // copy data from bitstream to buffer uint32_t bsIdx = 0; uint8_t bitsWritten = c_BSWidth; const int bsPB = c_BSWidth / 8; int sIdx = 0; // write block data hufdlit_fill_bitstream: for (int i = 0; i < cmpSize[si]; i += bsPB) { #pragma HLS PIPELINE II = 1 if (i + bytesInAcc < cmpSize[si] && bytesInAcc < bsPB) { bsbuff.range(((bytesInAcc + PARALLEL_BYTE) * 8) - 1, bytesInAcc * 8) = inStream.read(); bitsInAcc += c_streamWidth; } bitStream[bsIdx++] = bsbuff.range(c_BSWidth - 1, 0); if (i + bsPB > cmpSize[si]) bitsWritten = 8 * (cmpSize[si] - i); bsbuff >>= bitsWritten; bitsInAcc -= bitsWritten; bytesInAcc = bitsInAcc >> 3; } // generate decompressed bytes from huffman encoded stream ap_uint<c_streamWidth> acchbs = 0; uint8_t bitcnt = 0; int byteIndx = bsIdx - 1; uint32_t outBytes = 0; acchbs.range(c_BSWidth - 1, 0) = bitStream[byteIndx--]; bitcnt = bitsWritten; uint8_t byte_0 = acchbs.range(bitcnt - 1, bitcnt - 8); // find valid last bit, bitstream read in reverse order hufdlit_skip_zero: for (uint8_t i = 7; i >= 0; --i) { #pragma HLS PIPELINE II = 1 #pragma HLS LOOP_TRIPCOUNT min = 1 max = 7 if ((byte_0 & (1 << i)) > 0) { --bitcnt; break; } --bitcnt; // discount higher bits which are zero } // shift to higher end acchbs <<= (c_streamWidth - bitcnt); const int msbBitCnt = c_streamWidth - c_BSWidth; uint8_t shiftCnt = c_streamWidth - accuracyLog; uint8_t sym, blen = 0; // decode huffman bitstream huf_dec_bitstream: while (outBytes < decSize[si]) { #pragma HLS PIPELINE II = 1 // fill the acchbs in reverse if (bitcnt < 16 && byteIndx > -1) { uint32_t tmp = bitStream[byteIndx--]; acchbs += tmp << (msbBitCnt - bitcnt); bitcnt += c_BSWidth; } uint16_t code = acchbs >> shiftCnt; sym = huffTable[code].symbol; blen = huffTable[code].bitlen; hfdbs_shift_acc: for (int s = 1; s < c_maxCodeLen + 1; ++s) { #pragma HLS UNROLL #pragma HLS LOOP_TRIPCOUNT min = c_maxCodeLen max = c_maxCodeLen bsacc[s] = acchbs << s; } bitcnt -= blen; acchbs = bsacc[blen]; // write the literal to output stream outBuffer.range(((obbytes + 1) * 8) - 1, obbytes * 8) = sym; ++obbytes; if (obbytes == PARALLEL_BYTE) { literalStream << outBuffer; obbytes = 0; outBuffer = 0; } ++outBytes; } } if (obbytes > 0) { literalStream << outBuffer; } } template <int IN_BYTES, int BS_WIDTH> void hfdDataFeader(hls::stream<ap_uint<IN_BYTES * 8> >& inStream, uint8_t streamCnt, uint16_t* cmpSize, ap_uint<IN_BYTES * 8 * 2> accHuff, uint8_t bytesInAcc, hls::stream<IntVectorStream_dt<BS_WIDTH, 1> >& huffBitStream, hls::stream<ap_uint<8> >& validBitCntStream) { const uint8_t c_inputByte = IN_BYTES; const uint16_t c_streamWidth = 8 * c_inputByte; const uint16_t c_BSWidth = BS_WIDTH; const uint16_t c_accRegWidth = c_streamWidth * 2; const int c_bsPB = c_BSWidth / 8; const int c_bsUpperLim = (((32 / c_bsPB) / 2) * 1024); ap_uint<c_BSWidth> bitStream[c_bsUpperLim]; #pragma HLS BIND_STORAGE variable = bitStream type = ram_t2p impl = bram // internal registers ap_uint<c_accRegWidth> bsbuff = accHuff; // must not contain more than 3 bytes uint8_t bitsInAcc = bytesInAcc * 8; int wIdx = 0; int rIdx = 0; int fmInc = 1; // can be +1 or -1 int smInc = 1; uint8_t bitsWritten = c_BSWidth; int streamRBgn[4]; // starting index for BRAM read int streamRLim[4 + 1]; // point/index till which the BRAM can be read, 1 extra buffer entry #pragma HLS ARRAY_PARTITION variable = streamRBgn complete #pragma HLS ARRAY_PARTITION variable = streamRLim complete uint8_t wsi = 0, rsi = 0; int inIdx = 0; // modes bool fetchMode = 1; bool streamMode = 0; bool done = 0; // initialize streamRLim[wsi] = 0; // initial stream will stream from higher to lower address hfdl_dataStreamer: while (!done) { #pragma HLS PIPELINE II = 1 // stream data, bitStream buffer width is equal to inStream width for simplicity if (fetchMode) { // fill bitstream in direction specified by increment variable if (inIdx + bytesInAcc < cmpSize[wsi] && bytesInAcc < c_bsPB) { bsbuff.range(bitsInAcc + c_streamWidth - 1, bitsInAcc) = inStream.read(); bitsInAcc += c_streamWidth; } bitStream[wIdx] = bsbuff.range(c_BSWidth - 1, 0); if (inIdx + c_bsPB >= cmpSize[wsi]) { auto bw = 8 * (cmpSize[wsi] - inIdx); bitsWritten = (bw == 0) ? bitsWritten : bw; validBitCntStream << bitsWritten; bsbuff >>= bitsWritten; bitsInAcc -= bitsWritten; bytesInAcc = bitsInAcc >> 3; // update fetch mode state if (streamMode == 0) { streamMode = 1; rIdx = wIdx; } inIdx = 0; // just an index, not directional fmInc = (~fmInc) + 1; // flip 1 and -1 streamRBgn[wsi] = wIdx; ++wsi; if (wsi & 1) { streamRLim[wsi] = c_bsUpperLim - 1; wIdx = c_bsUpperLim - 1; } else { streamRLim[wsi] = 0; wIdx = 0; } // post increment checks if ((wsi == streamCnt) || (wsi - rsi > 1)) fetchMode = 0; // reset default value bitsWritten = c_BSWidth; continue; } bsbuff >>= bitsWritten; bitsInAcc -= bitsWritten; bytesInAcc = bitsInAcc >> 3; inIdx += c_bsPB; wIdx += fmInc; } if (streamMode) { // write data to output stream uint32_t tmp = bitStream[rIdx]; // output register IntVectorStream_dt<BS_WIDTH, 1> outValue; outValue.data[0] = tmp; // update stream mode state if (rIdx == streamRLim[rsi]) { outValue.strobe = 0; ++rsi; rIdx = streamRBgn[rsi]; smInc = (~smInc) + 1; // flip 1 and -1 // no need to check if fetchMode == 0 if (wsi < streamCnt) fetchMode = 1; // either previous streamMode ended quicker than next fetchMode or streamCnt reached if (wsi == rsi) streamMode = 0; } else { outValue.strobe = 1; rIdx -= smInc; } huffBitStream << outValue; } // end condition if (!(fetchMode | streamMode)) done = 1; } } template <int MAX_CODELEN, int BS_WIDTH> void hfdGetCodesStreamLiteralsLL(uint16_t* decSize, uint8_t accuracyLog, uint8_t streamCnt, uint16_t weightCnt, uint8_t* weights, hls::stream<IntVectorStream_dt<BS_WIDTH, 1> >& huffBitStream, hls::stream<ap_uint<8> >& validBitCntStream, hls::stream<ap_uint<17> >& literalStream) { const uint16_t c_HBFSize = 48; const uint16_t c_BSWidth = BS_WIDTH; const int c_bsPB = c_BSWidth / 8; ap_uint<11> validCodeOffset[MAX_CODELEN + 1]; ap_uint<4> bitLen[MAX_CODELEN + 1]; ap_uint<8> symbol[2][MAX_CODELEN + 1]; #pragma HLS ARRAY_PARTITION variable = validCodeOffset complete dim = 0 #pragma HLS ARRAY_PARTITION variable = bitLen complete dim = 0 #pragma HLS ARRAY_PARTITION variable = symbol complete dim = 0 // New huffman code ap_uint<MAX_CODELEN + 1> codeOffsets[MAX_CODELEN + 1]; #pragma HLS ARRAY_PARTITION variable = codeOffsets dim = 1 complete ap_uint<8> bl1Code[2]; ap_uint<8> bl2Code[4]; ap_uint<8> bl3Code[8]; ap_uint<8> bl4Code[16]; ap_uint<8> bl5Code[32]; ap_uint<8> bl6Code[64]; ap_uint<8> bl7Code[128]; ap_uint<8> bl8Code[256]; ap_uint<8> bl9Code[256]; ap_uint<8> bl10Code[256]; ap_uint<8> bl11Code[256]; #pragma HLS BIND_STORAGE variable = bl1Code type = ram_2p impl = lutram #pragma HLS BIND_STORAGE variable = bl2Code type = ram_2p impl = lutram #pragma HLS BIND_STORAGE variable = bl3Code type = ram_2p impl = lutram #pragma HLS BIND_STORAGE variable = bl4Code type = ram_2p impl = lutram #pragma HLS BIND_STORAGE variable = bl5Code type = ram_2p impl = lutram #pragma HLS BIND_STORAGE variable = bl6Code type = ram_2p impl = lutram #pragma HLS BIND_STORAGE variable = bl7Code type = ram_2p impl = lutram #pragma HLS BIND_STORAGE variable = bl8Code type = ram_2p impl = lutram #pragma HLS BIND_STORAGE variable = bl9Code type = ram_2p impl = lutram #pragma HLS BIND_STORAGE variable = bl10Code type = ram_2p impl = lutram #pragma HLS BIND_STORAGE variable = bl11Code type = ram_2p impl = lutram // generate codes code_generator<MAX_CODELEN>(weights, codeOffsets, bl1Code, bl2Code, bl3Code, bl4Code, bl5Code, bl6Code, bl7Code, bl8Code, bl9Code, bl10Code, bl11Code, accuracyLog, weightCnt); ap_uint<17> outBuffer; decode_huff_bitstream_outer: for (ap_uint<3> si = 0; si < streamCnt; ++si) { // generate decompressed bytes from huffman encoded stream ap_uint<c_HBFSize> acchbs = 0; ap_uint<7> bitcnt = 0; bitcnt = validBitCntStream.read(); // input register auto inValue = huffBitStream.read(); acchbs.range(c_BSWidth - 1, 0) = inValue.data[0]; uint8_t byte_0 = acchbs.range(bitcnt - 1, bitcnt - 8); // find valid last bit, bitstream read in reverse order hufdlit_skip_zero: for (uint8_t i = 7; i >= 0; --i) { #pragma HLS UNROLL #pragma HLS LOOP_TRIPCOUNT min = 1 max = 7 if ((byte_0 & (1 << i)) > 0) { --bitcnt; break; } --bitcnt; // discount higher bits which are zero } // shift to higher end acchbs <<= (c_HBFSize - bitcnt); const int c_msbBitCnt = c_HBFSize - c_BSWidth; ap_uint<11> parallelAcc[MAX_CODELEN + 1]; #pragma HLS ARRAY_PARTITION variable = parallelAcc complete ap_uint<8> tmpBitLen = bitcnt; bool readUpdFlag = ((tmpBitLen < 22) && (inValue.strobe == 1)); uint8_t shiftCnt = c_msbBitCnt - tmpBitLen; ap_uint<c_HBFSize> tmp = 0; if (readUpdFlag) { inValue = huffBitStream.read(); tmp = inValue.data[0]; bitcnt += c_BSWidth; } ap_uint<c_HBFSize> acchbs1 = acchbs; ap_uint<c_HBFSize> acchbs2 = tmp << shiftCnt; acchbs = acchbs1 | acchbs2; // pre-read one data inValue = huffBitStream.read(); // decode huffman bitstreams huf_dec_bitstream: for (uint32_t outBytes = 0; outBytes < decSize[si]; outBytes += 2) { #pragma HLS PIPELINE II = 1 for (ap_uint<4> i = 0; i < MAX_CODELEN + 1; ++i) { #pragma HLS UNROLL parallelAcc[i] = acchbs.range(c_HBFSize - 1 - i, c_HBFSize - MAX_CODELEN - i); for (ap_uint<4> j = 0; j < MAX_CODELEN; ++j) { #pragma HLS UNROLL validCodeOffset[i].range(j, j) = (parallelAcc[i].range(10, 10 - j) >= codeOffsets[j]) ? 1 : 0; } bitLen[i] = 1 + ap_uint<6>(__builtin_ctz((unsigned int)(validCodeOffset[i]))); } ap_uint<5> totalBitLen = bitLen[0] + bitLen[bitLen[0]]; ap_uint<7> tmpBitLen = bitcnt - totalBitLen; ap_uint<5> shiftCnt = c_msbBitCnt - tmpBitLen; if (tmpBitLen < 22) { tmp = inValue.data[0]; bitcnt = c_BSWidth + tmpBitLen; } else { tmp = 0; bitcnt = tmpBitLen; } ap_uint<c_HBFSize> acchbs1 = acchbs << totalBitLen; ap_uint<c_HBFSize> acchbs2 = tmp << shiftCnt; acchbs = acchbs1 | acchbs2; bool readUpdFlag = ((tmpBitLen < 22) && (inValue.strobe == 1)); if (readUpdFlag) { inValue = huffBitStream.read(); } symbol[0][1] = bl1Code[parallelAcc[0].range(10, 10)]; symbol[0][2] = bl2Code[parallelAcc[0].range(10, 9)]; symbol[0][3] = bl3Code[parallelAcc[0].range(10, 8)]; symbol[0][4] = bl4Code[parallelAcc[0].range(10, 7)]; symbol[0][5] = bl5Code[parallelAcc[0].range(10, 6)]; symbol[0][6] = bl6Code[parallelAcc[0].range(10, 5)]; symbol[0][7] = bl7Code[parallelAcc[0].range(10, 4)]; symbol[0][8] = bl8Code[parallelAcc[0].range(10, 3)]; symbol[0][9] = bl9Code[ap_uint<8>(parallelAcc[0].range(10, 2))]; symbol[0][10] = bl10Code[ap_uint<8>(parallelAcc[0].range(10, 1))]; symbol[0][11] = bl11Code[ap_uint<8>(parallelAcc[0].range(10, 0))]; symbol[1][1] = bl1Code[parallelAcc[bitLen[0]].range(10, 10)]; symbol[1][2] = bl2Code[parallelAcc[bitLen[0]].range(10, 9)]; symbol[1][3] = bl3Code[parallelAcc[bitLen[0]].range(10, 8)]; symbol[1][4] = bl4Code[parallelAcc[bitLen[0]].range(10, 7)]; symbol[1][5] = bl5Code[parallelAcc[bitLen[0]].range(10, 6)]; symbol[1][6] = bl6Code[parallelAcc[bitLen[0]].range(10, 5)]; symbol[1][7] = bl7Code[parallelAcc[bitLen[0]].range(10, 4)]; symbol[1][8] = bl8Code[parallelAcc[bitLen[0]].range(10, 3)]; symbol[1][9] = bl9Code[ap_uint<8>(parallelAcc[bitLen[0]].range(10, 2))]; symbol[1][10] = bl10Code[ap_uint<8>(parallelAcc[bitLen[0]].range(10, 1))]; symbol[1][11] = bl11Code[ap_uint<8>(parallelAcc[bitLen[0]].range(10, 0))]; outBuffer.range(7, 0) = symbol[0][bitLen[0]]; outBuffer.range(15, 8) = symbol[1][bitLen[bitLen[0]]]; outBuffer.range(16, 16) = true; // write the literal to output stream literalStream << outBuffer; } } outBuffer = 0; literalStream << outBuffer; } template <int MAX_CODELEN, int BS_WIDTH> void hfdGetCodesStreamLiterals(uint16_t* decSize, uint8_t accuracyLog, uint8_t streamCnt, uint16_t weightCnt, uint8_t* weights, hls::stream<IntVectorStream_dt<BS_WIDTH, 1> >& huffBitStream, hls::stream<ap_uint<8> >& validBitCntStream, hls::stream<ap_uint<9> >& literalStream) { const uint16_t c_HBFSize = 32; const uint16_t c_BSWidth = BS_WIDTH; const int c_bsPB = c_BSWidth / 8; ap_uint<11> validCodeOffset; ap_uint<4> bitLen; ap_uint<8> symbol[MAX_CODELEN + 1]; #pragma HLS ARRAY_PARTITION variable = symbol complete dim = 0 // New huffman code ap_uint<MAX_CODELEN + 1> codeOffsets[MAX_CODELEN + 1]; #pragma HLS ARRAY_PARTITION variable = codeOffsets dim = 1 complete ap_uint<8> bl1Code[2]; ap_uint<8> bl2Code[4]; ap_uint<8> bl3Code[8]; ap_uint<8> bl4Code[16]; ap_uint<8> bl5Code[32]; ap_uint<8> bl6Code[64]; ap_uint<8> bl7Code[128]; ap_uint<8> bl8Code[256]; ap_uint<8> bl9Code[256]; ap_uint<8> bl10Code[256]; ap_uint<8> bl11Code[256]; #pragma HLS BIND_STORAGE variable = bl1Code type = ram_1p impl = lutram #pragma HLS BIND_STORAGE variable = bl2Code type = ram_1p impl = lutram #pragma HLS BIND_STORAGE variable = bl3Code type = ram_1p impl = lutram #pragma HLS BIND_STORAGE variable = bl4Code type = ram_1p impl = lutram #pragma HLS BIND_STORAGE variable = bl5Code type = ram_1p impl = lutram #pragma HLS BIND_STORAGE variable = bl6Code type = ram_1p impl = lutram #pragma HLS BIND_STORAGE variable = bl7Code type = ram_1p impl = lutram #pragma HLS BIND_STORAGE variable = bl8Code type = ram_1p impl = lutram #pragma HLS BIND_STORAGE variable = bl9Code type = ram_1p impl = lutram #pragma HLS BIND_STORAGE variable = bl10Code type = ram_1p impl = lutram #pragma HLS BIND_STORAGE variable = bl11Code type = ram_1p impl = lutram // generate codes code_generator<MAX_CODELEN>(weights, codeOffsets, bl1Code, bl2Code, bl3Code, bl4Code, bl5Code, bl6Code, bl7Code, bl8Code, bl9Code, bl10Code, bl11Code, accuracyLog, weightCnt); ap_uint<9> outBuffer; uint8_t obbytes = 0; decode_huff_bitstream_outer: for (uint8_t si = 0; si < streamCnt; ++si) { // generate decompressed bytes from huffman encoded stream ap_uint<c_HBFSize> acchbs = 0; ap_uint<8> bitcnt = 0; uint32_t outBytes = 0; bitcnt = validBitCntStream.read(); // input register auto inValue = huffBitStream.read(); acchbs.range(c_BSWidth - 1, 0) = inValue.data[0]; uint8_t byte_0 = acchbs.range(bitcnt - 1, bitcnt - 8); // find valid last bit, bitstream read in reverse order hufdlit_skip_zero: for (uint8_t i = 7; i >= 0; --i) { #pragma HLS UNROLL #pragma HLS LOOP_TRIPCOUNT min = 1 max = 7 if ((byte_0 & (1 << i)) > 0) { --bitcnt; break; } --bitcnt; // discount higher bits which are zero } // shift to higher end acchbs <<= (c_HBFSize - bitcnt); uint16_t byteIndx = c_bsPB; // just to verify with the compressed size const int msbBitCnt = c_HBFSize - c_BSWidth; if ((bitcnt.range(4, 4) != 1) && (inValue.strobe == 1)) { inValue = huffBitStream.read(); uint32_t tmp = inValue.data[0]; acchbs += tmp << (msbBitCnt - bitcnt); bitcnt += c_BSWidth; byteIndx += c_bsPB; } // decode huffman bitstreams huf_dec_bitstream: for (uint32_t outBytes = 0; outBytes < decSize[si]; outBytes += 1) { #pragma HLS PIPELINE II = 1 for (uint8_t i = 0; i < MAX_CODELEN; ++i) { #pragma HLS UNROLL validCodeOffset.range(i, i) = (acchbs.range(31, 31 - i) >= codeOffsets[i]) ? 1 : 0; } bitLen = 1 + ap_uint<6>(__builtin_ctz((unsigned int)(validCodeOffset))); symbol[1] = bl1Code[acchbs.range(31, 31)]; symbol[2] = bl2Code[acchbs.range(31, 30)]; symbol[3] = bl3Code[acchbs.range(31, 29)]; symbol[4] = bl4Code[acchbs.range(31, 28)]; symbol[5] = bl5Code[acchbs.range(31, 27)]; symbol[6] = bl6Code[acchbs.range(31, 26)]; symbol[7] = bl7Code[acchbs.range(31, 25)]; symbol[8] = bl8Code[acchbs.range(31, 24)]; symbol[9] = bl9Code[ap_uint<8>(acchbs.range(31, 23))]; symbol[10] = bl10Code[ap_uint<8>(acchbs.range(31, 22))]; symbol[11] = bl11Code[ap_uint<8>(acchbs.range(31, 21))]; bitcnt -= bitLen; acchbs <<= bitLen; // write the literal to output stream outBuffer.range(7, 0) = symbol[bitLen]; outBuffer.range(8, 8) = true; literalStream << outBuffer; if ((bitcnt.range(4, 4) != 1) && (inValue.strobe == 1)) { inValue = huffBitStream.read(); uint32_t tmp = inValue.data[0]; acchbs += tmp << (msbBitCnt - bitcnt); bitcnt += c_BSWidth; byteIndx += c_bsPB; } } } outBuffer = 0; literalStream << outBuffer; } template <uint8_t OUT_BYTES> void writeAccLiteralDataLL(hls::stream<ap_uint<17> >& byteStream, hls::stream<IntVectorStream_dt<OUT_BYTES * 8, 1> >& literalStream, uint16_t* decSize) { const uint8_t c_outputByte = OUT_BYTES; const int c_streamWidth = c_outputByte * 8; ap_uint<c_streamWidth + 16> outBuffer; ap_uint<4> writeIdx = 0; uint8_t i = 0; uint32_t outBytes = 0; IntVectorStream_dt<OUT_BYTES * 8, 1> outValue; writeAccLiterals: for (ap_uint<17> inData = byteStream.read(); inData.range(16, 16) == 1; inData = byteStream.read()) { #pragma HLS PIPELINE II = 1 outBytes += 2; outBuffer.range((writeIdx + 1) * 8 - 1, writeIdx * 8) = inData.range(7, 0); outBuffer.range((writeIdx + 2) * 8 - 1, (writeIdx + 1) * 8) = inData.range(15, 8); if (outBytes <= decSize[i]) { writeIdx += 2; } else { writeIdx += 1; } if (outBytes >= decSize[i]) { i += 1; outBytes = 0; } if (writeIdx >= c_outputByte) { outValue.data[0] = outBuffer; outValue.strobe = 1; literalStream << outValue; outBuffer >>= c_streamWidth; writeIdx -= c_outputByte; } } if (writeIdx) { outValue.data[0] = outBuffer; outValue.strobe = 1; literalStream << outValue; } outValue.strobe = 0; literalStream << outValue; } template <uint8_t OUT_BYTES> void writeAccLiteralData(hls::stream<ap_uint<9> >& byteStream, hls::stream<IntVectorStream_dt<OUT_BYTES * 8, 1> >& literalStream) { ap_uint<OUT_BYTES * 8> outBuffer; IntVectorStream_dt<OUT_BYTES * 8, 1> outValue; ap_uint<4> writeIdx = 0; huffLitUpsizer: for (ap_uint<9> inData = byteStream.read(); inData.range(8, 8) == 1; inData = byteStream.read()) { #pragma HLS PIPELINE II = 1 outBuffer.range((writeIdx + 1) * 8 - 1, writeIdx * 8) = inData.range(7, 0); writeIdx++; if (writeIdx == OUT_BYTES) { outValue.data[0] = outBuffer; outValue.strobe = 1; literalStream << outValue; writeIdx = 0; } } if (writeIdx) { outValue.data[0] = outBuffer; outValue.strobe = 1; literalStream << outValue; } outValue.strobe = 0; literalStream << outValue; } template <int IN_BYTES, int OUT_BYTES, int MAX_CODELEN> void huffDecodeLitInternalLL(hls::stream<ap_uint<IN_BYTES * 8> >& inStream, ap_uint<IN_BYTES * 8 * 2> accHuff, uint8_t bytesInAcc, uint16_t* cmpSize, uint16_t* decSize, uint16_t* decSize1, uint8_t accuracyLog, uint8_t streamCnt, uint16_t weightCnt, uint8_t* weights, hls::stream<IntVectorStream_dt<OUT_BYTES * 8, 1> >& literalStream) { const uint8_t c_BSWidth = 24; const uint8_t c_symWidth = 17; // internal streams hls::stream<IntVectorStream_dt<c_BSWidth, 1> > huffBitStream("huffBitStream"); hls::stream<ap_uint<8> > validBitCntStream("validBitCntStream"); hls::stream<ap_uint<c_symWidth> > byteLiteralStream("byteLiteralStream"); #pragma HLS STREAM variable = huffBitStream depth = 32 #pragma HLS STREAM variable = validBitCntStream depth = 8 #pragma HLS STREAM variable = byteLiteralStream depth = 8 #pragma HLS DATAFLOW hfdDataFeader<IN_BYTES, c_BSWidth>(inStream, streamCnt, cmpSize, accHuff, bytesInAcc, huffBitStream, validBitCntStream); hfdGetCodesStreamLiteralsLL<MAX_CODELEN, c_BSWidth>(decSize, accuracyLog, streamCnt, weightCnt, weights, huffBitStream, validBitCntStream, byteLiteralStream); writeAccLiteralDataLL<OUT_BYTES>(byteLiteralStream, literalStream, decSize1); } template <int IN_BYTES, int OUT_BYTES, int MAX_CODELEN> void huffDecodeLitInternal(hls::stream<ap_uint<IN_BYTES * 8> >& inStream, ap_uint<IN_BYTES * 8 * 2> accHuff, uint8_t bytesInAcc, uint16_t* cmpSize, uint16_t* decSize, uint8_t accuracyLog, uint8_t streamCnt, uint16_t weightCnt, uint8_t* weights, hls::stream<IntVectorStream_dt<OUT_BYTES * 8, 1> >& literalStream) { const uint8_t c_BSWidth = 16; const uint8_t c_symWidth = 9; // internal streams hls::stream<IntVectorStream_dt<c_BSWidth, 1> > huffBitStream("huffBitStream"); hls::stream<ap_uint<8> > validBitCntStream("validBitCntStream"); hls::stream<ap_uint<c_symWidth> > byteLiteralStream("byteLiteralStream"); #pragma HLS STREAM variable = huffBitStream depth = 32 #pragma HLS STREAM variable = validBitCntStream depth = 8 #pragma HLS STREAM variable = byteLiteralStream depth = 8 #pragma HLS DATAFLOW hfdDataFeader<IN_BYTES, c_BSWidth>(inStream, streamCnt, cmpSize, accHuff, bytesInAcc, huffBitStream, validBitCntStream); hfdGetCodesStreamLiterals<MAX_CODELEN, c_BSWidth>(decSize, accuracyLog, streamCnt, weightCnt, weights, huffBitStream, validBitCntStream, byteLiteralStream); writeAccLiteralData<OUT_BYTES>(byteLiteralStream, literalStream); } template <uint8_t IN_BYTES, uint8_t OUT_BYTES, int LMO_WIDTH, bool LOW_LATENCY = false> void huffDecodeLiterals(hls::stream<ap_uint<IN_BYTES * 8> >& inStream, bool quadStream, ap_uint<IN_BYTES * 8 * 2> accHuff, uint8_t bytesInAcc, ap_uint<LMO_WIDTH> remSize, ap_uint<LMO_WIDTH> regeneratedSize, uint8_t accuracyLog, uint16_t weightCnt, uint8_t* weights, hls::stream<IntVectorStream_dt<OUT_BYTES * 8, 1> >& literalStream) { const uint8_t c_inputByte = IN_BYTES; const uint16_t c_streamWidth = 8 * c_inputByte; const uint16_t c_maxCodeLen = 11; uint8_t streamCnt = 1; uint16_t decSize[4]; uint16_t decSize1[4]; uint16_t cmpSize[4]; #pragma HLS ARRAY_PARTITION variable = decSize complete #pragma HLS ARRAY_PARTITION variable = decSize1 complete #pragma HLS ARRAY_PARTITION variable = cmpSize complete // get stream sizes if 4 streams are present if (quadStream) { streamCnt = 4; // Jump table is 6 bytes long // read from input if needed if (bytesInAcc < c_inputByte) { accHuff.range(((c_inputByte + bytesInAcc) * 8) - 1, bytesInAcc * 8) = inStream.read(); bytesInAcc += c_inputByte; } // use 4 bytes // get decompressed size ap_uint<LMO_WIDTH> dcmpSize = (regeneratedSize + 3) / 4; decSize[0] = decSize[1] = decSize[2] = dcmpSize; decSize1[0] = decSize1[1] = decSize1[2] = dcmpSize; decSize[3] = regeneratedSize - (dcmpSize * 3); decSize1[3] = decSize[3]; // get compressed size cmpSize[0] = accHuff; accHuff >>= 16; cmpSize[1] = accHuff; accHuff >>= 16; bytesInAcc -= 4; // read from input if needed if (bytesInAcc < 2) { accHuff.range(((c_inputByte + bytesInAcc) * 8) - 1, bytesInAcc * 8) = inStream.read(); bytesInAcc += c_inputByte; } cmpSize[2] = accHuff; accHuff >>= 16; bytesInAcc -= 2; remSize -= 6; cmpSize[3] = remSize - (cmpSize[0] + cmpSize[1] + cmpSize[2]); } else { decSize[0] = regeneratedSize; decSize1[0] = regeneratedSize; cmpSize[0] = remSize; } // parallel huffman decoding if (LOW_LATENCY) { huffDecodeLitInternalLL<IN_BYTES, OUT_BYTES, c_maxCodeLen>(inStream, accHuff, bytesInAcc, cmpSize, decSize, decSize1, accuracyLog, streamCnt, weightCnt, weights, literalStream); } else { huffDecodeLitInternal<IN_BYTES, OUT_BYTES, c_maxCodeLen>( inStream, accHuff, bytesInAcc, cmpSize, decSize, accuracyLog, streamCnt, weightCnt, weights, literalStream); } } } // details } // compression } // xf #endif // _XFCOMPRESSION_ZSTD_FSE_DECODER_HPP_
39.531406
120
0.569445
dycz0fx
9cb65eb648d491adb75ac33b8d882cddd7949473
3,041
hpp
C++
library/ATF/CTransportShip.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/CTransportShip.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/CTransportShip.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <CMapData.hpp> #include <CMyTimer.hpp> #include <CNetIndexList.hpp> START_ATF_NAMESPACE struct CTransportShip { struct __mgr_member { struct CPlayer *pPtr; unsigned int dwSerial; public: __mgr_member(); void ctor___mgr_member(); void init(); bool is_fill(); }; struct __mgr_ticket { int nCurTicketNum; int nReserTicketNum; unsigned int dwNextUpdateTime; struct _TicketItem_fld *pLinkTicketItem; public: __mgr_ticket(); void ctor___mgr_ticket(); void init(); }; bool m_bAnchor; char m_byDirect; bool m_bHurry; unsigned int m_dwNextHurryTime; unsigned int m_dwEventCreateTime; char m_byRaceCode_Layer; CMapData *m_pLinkShipMap; CMapData *m_pLinkPortMap[2]; CMyTimer m_tmrCheckState; __mgr_member m_NewMember[2532]; __mgr_member m_OldMember[2532]; CNetIndexList m_listLogoffMember; __mgr_ticket m_MgrTicket[2]; public: void AlterState(bool bAnchor, char byDirect, int nPassMin, int nNextSubEventTerm); void ApplyTicketReserver(); CTransportShip(); void ctor_CTransportShip(); void CheckHurry(); void CheckTicket(); void CheckTicket_Kick(struct CPlayer* pPtr, int nPortalIndex); void CheckTicket_Pass(struct CPlayer* pPtr, int nPortalIndex); void EnterMember(struct CPlayer* pEnter); void ExitMember(struct CPlayer* pExiter, bool bLogoff); bool GetCurRideShipThisTicket(struct _TicketItem_fld* pTicketFld); struct __mgr_member* GetEmptyNewMember(); int GetLeftTicketIncludeReserNum(char* pszTarMapCode, int nAdd); struct CMapData* GetMapCurDirect(); int GetOutPortalIndex(int nRaceCode, char byExitDirect); int GetRideLimLevel(); int GetRideUpLimLevel(); void GetStartPosInShip(float* pfPos); bool InitShip(struct CMapData* pLinkShipMap, struct CMapData* pLinkMainbaseMap, struct CMapData* pLinkPlatformMap, char byRaceCode_Layer); void InitTicketReserver(); bool IsMemberBeforeLogoff(unsigned int dwPlayerSerial); bool IsOldMember(struct CPlayer* pMember); void KickFreeMember(); void KickOldMember(char byKickDirectCode); void Loop(); void ReEnterMember(struct CPlayer* pExiter); bool RenewOldMember(struct CPlayer* pMember); void SendMsg_KickForSail(int n); void SendMsg_TicketCheck(int n, bool bPass, uint16_t wTicketSerial); void SendMsg_TransportShipState(int n); bool Ticketting(struct CPlayer* pExiter); ~CTransportShip(); void dtor_CTransportShip(); }; END_ATF_NAMESPACE
36.638554
146
0.655048
lemkova
9cbb5a7a25e4bade21326da0ae97e1af3375f5ca
3,868
cpp
C++
src/FastaTools.cpp
infphilo/tophat
37540ce3f0c10e0f0bfafa2f29450055fc5da384
[ "BSL-1.0" ]
113
2015-04-07T13:21:43.000Z
2021-08-20T01:52:43.000Z
src/FastaTools.cpp
infphilo/tophat
37540ce3f0c10e0f0bfafa2f29450055fc5da384
[ "BSL-1.0" ]
47
2015-04-09T09:37:59.000Z
2018-12-12T11:49:30.000Z
src/FastaTools.cpp
infphilo/tophat
37540ce3f0c10e0f0bfafa2f29450055fc5da384
[ "BSL-1.0" ]
59
2015-04-01T13:48:59.000Z
2021-11-15T09:27:30.000Z
// // FastaTools.cpp // TopHat // // Created by Harold Pimentel on 10/27/11. // #include "FastaTools.h" FastaReader::FastaReader() { isPrimed_ = false; } FastaReader::FastaReader(std::string fname) { isPrimed_ = false; init(fname); } FastaReader::~FastaReader() { ifstream_.close(); } void FastaReader::init(std::string fname) { if (isPrimed_) { std::cerr << "Warning: object has already FastaReader has already been " << "initialized with file: " << fname_ << std::endl; return; } std::ios::sync_with_stdio(false); //to speed up slow iostream reading fname_ = fname; ifstream_.open(fname_.c_str(), std::ios::in); if (!ifstream_.good()) { std::cerr << "ERROR: Could not open file " << fname_ << " in FastaReader" << std::endl; exit(1); } // Check the first character to see if it is valid char c = ifstream_.peek(); if (c != '>') { std::cerr << "ERROR: Invalid format for FASTA file. Begins with a '" << c << "'instead of a '>'" << std::endl; exit(1); } isPrimed_ = true; } bool FastaReader::good() const { return ifstream_.good() && !ifstream_.eof(); } // Up to caller to allocate memory. // Only deallocates memory when there are no more records left bool FastaReader::next(FastaRecord& rec) { if (!isPrimed_) { std::cerr << "ERROR: Stream has not been primed (FastaReader)" << std::endl; exit(1); } // Get the entire first line and description //ifstream_.getline(line_buf_, LINE_BUF_SIZE); if (ifstream_.eof() || !std::getline(ifstream_, line_buf_)) { rec.clear(); return false; } if (line_buf_.empty() || !good()) { rec.clear(); return false; } if (line_buf_.length()>0 && line_buf_[0]!='>') { std::cerr << "ERROR: no FASTA record start found (FastaReader)" << std::endl; exit(1); } size_t sp_pos = line_buf_.find(' '); if (sp_pos != std::string::npos) { rec.id_=line_buf_.substr(1, sp_pos-1); rec.desc_=line_buf_.substr(sp_pos+1); } else { rec.id_=line_buf_.substr(1); rec.desc_.clear(); } rec.seq_.clear(); // Read until you see another ">" while (ifstream_.peek() != '>') { //ifstream_ >> cur_line >> std::ws; if (std::getline(ifstream_, line_buf_)) rec.seq_ += line_buf_; else { break; // if ifstream_.good() && !ifstream_.eof() && } } return true; } FastaWriter::FastaWriter() { isPrimed_ = false; } FastaWriter::FastaWriter(std::string fname) { isPrimed_ = false; init(fname); } FastaWriter::~FastaWriter() { ofstream_.close(); } void FastaWriter::init(std::string fname) { if (isPrimed_) { std::cerr << "Warning: Cannot allocate FastaWriter to file '" << fname << "'. It has already been allocated to file '" << fname_ << "'" << std::endl; return; } ofstream_.open(fname.c_str(), std::ios::out); if (!ofstream_.good()) { std::cerr << "ERROR: Could not open " << fname << " for writing in " << "FastaWriter" << std::endl; exit(1); } fname_ = fname; isPrimed_ = true; } void FastaWriter::write(FastaRecord& rec, size_t column_size) { if (rec.seq_.length() == 0) return; //don't write empty records ofstream_ << ">" << rec.id_; //<< std::endl; if (rec.desc_.length()) { ofstream_ << " " << rec.desc_; } ofstream_ << std::endl; // iterate throught the string and print out the string size_t start = 0; while (start < rec.seq_.length()) { ofstream_ << rec.seq_.substr(start, column_size) << std::endl; start += column_size; } }
23.442424
83
0.559979
infphilo
9cbcfbf2cd9041af48d09c2d0e6f0e4de2020568
5,901
cpp
C++
WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/UIProcess/CredentialManagement/WebCredentialsMessengerProxy.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
1
2021-05-27T07:29:31.000Z
2021-05-27T07:29:31.000Z
WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/UIProcess/CredentialManagement/WebCredentialsMessengerProxy.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
null
null
null
WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/UIProcess/CredentialManagement/WebCredentialsMessengerProxy.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
null
null
null
/* * Copyright (C) 2018 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. */ #include "config.h" #include "WebCredentialsMessengerProxy.h" #if ENABLE(WEB_AUTHN) #include "WebCredentialsMessengerMessages.h" #include "WebCredentialsMessengerProxyMessages.h" #include "WebPageProxy.h" #include "WebProcessProxy.h" #include <WebCore/ExceptionData.h> #include <WebCore/LocalAuthenticator.h> namespace WebKit { WebCredentialsMessengerProxy::WebCredentialsMessengerProxy(WebPageProxy& webPageProxy) : m_webPageProxy(webPageProxy) { m_webPageProxy.process().addMessageReceiver(Messages::WebCredentialsMessengerProxy::messageReceiverName(), m_webPageProxy.pageID(), *this); m_authenticator = std::make_unique<WebCore::LocalAuthenticator>(); } WebCredentialsMessengerProxy::~WebCredentialsMessengerProxy() { m_webPageProxy.process().removeMessageReceiver(Messages::WebCredentialsMessengerProxy::messageReceiverName(), m_webPageProxy.pageID()); } void WebCredentialsMessengerProxy::makeCredential(uint64_t messageId, const Vector<uint8_t>& hash, const WebCore::PublicKeyCredentialCreationOptions& options) { // FIXME(182767) if (!m_authenticator) { exceptionReply(messageId, { WebCore::NotAllowedError, "No avaliable authenticators."_s }); return; } // FIXME(183534): Weak pointers doesn't work in another thread because of race condition. // FIXME(183534): Unify callbacks. auto weakThis = makeWeakPtr(*this); auto callback = [weakThis, messageId] (const Vector<uint8_t>& credentialId, const Vector<uint8_t>& attestationObject) { if (!weakThis) return; weakThis->makeCredentialReply(messageId, credentialId, attestationObject); }; auto exceptionCallback = [weakThis, messageId] (const WebCore::ExceptionData& exception) { if (!weakThis) return; weakThis->exceptionReply(messageId, exception); }; m_authenticator->makeCredential(hash, options, WTFMove(callback), WTFMove(exceptionCallback)); } void WebCredentialsMessengerProxy::getAssertion(uint64_t messageId, const Vector<uint8_t>& hash, const WebCore::PublicKeyCredentialRequestOptions& options) { // FIXME(182767) if (!m_authenticator) exceptionReply(messageId, { WebCore::NotAllowedError, "No avaliable authenticators."_s }); // FIXME(183534): Weak pointers doesn't work in another thread because of race condition. // FIXME(183534): Unify callbacks. auto weakThis = makeWeakPtr(*this); auto callback = [weakThis, messageId] (const Vector<uint8_t>& credentialId, const Vector<uint8_t>& authenticatorData, const Vector<uint8_t>& signature, const Vector<uint8_t>& userHandle) { if (weakThis) weakThis->getAssertionReply(messageId, credentialId, authenticatorData, signature, userHandle); }; auto exceptionCallback = [weakThis, messageId] (const WebCore::ExceptionData& exception) { if (weakThis) weakThis->exceptionReply(messageId, exception); }; m_authenticator->getAssertion(hash, options, WTFMove(callback), WTFMove(exceptionCallback)); } void WebCredentialsMessengerProxy::isUserVerifyingPlatformAuthenticatorAvailable(uint64_t messageId) { if (!m_authenticator) { isUserVerifyingPlatformAuthenticatorAvailableReply(messageId, false); return; } isUserVerifyingPlatformAuthenticatorAvailableReply(messageId, m_authenticator->isAvailable()); } void WebCredentialsMessengerProxy::exceptionReply(uint64_t messageId, const WebCore::ExceptionData& exception) { m_webPageProxy.send(Messages::WebCredentialsMessenger::ExceptionReply(messageId, exception)); } void WebCredentialsMessengerProxy::makeCredentialReply(uint64_t messageId, const Vector<uint8_t>& credentialId, const Vector<uint8_t>& attestationObject) { m_webPageProxy.send(Messages::WebCredentialsMessenger::MakeCredentialReply(messageId, credentialId, attestationObject)); } void WebCredentialsMessengerProxy::getAssertionReply(uint64_t messageId, const Vector<uint8_t>& credentialId, const Vector<uint8_t>& authenticatorData, const Vector<uint8_t>& signature, const Vector<uint8_t>& userHandle) { m_webPageProxy.send(Messages::WebCredentialsMessenger::GetAssertionReply(messageId, credentialId, authenticatorData, signature, userHandle)); } void WebCredentialsMessengerProxy::isUserVerifyingPlatformAuthenticatorAvailableReply(uint64_t messageId, bool result) { m_webPageProxy.send(Messages::WebCredentialsMessenger::IsUserVerifyingPlatformAuthenticatorAvailableReply(messageId, result)); } } // namespace WebKit #endif // ENABLE(WEB_AUTHN)
46.833333
220
0.771225
mlcldh
9cbf1c9f8454bcf6acd4fce4de730c65ddca4ee1
942
cpp
C++
src/zxing/zxing/oned/rss/expanded/decoders/AI01392xDecoder.cpp
favoritas37/qzxing
6ea2b31e26db9d43db027ba207f5c73dc9d759fc
[ "Apache-2.0" ]
483
2016-08-26T00:53:51.000Z
2022-03-30T16:08:49.000Z
src/zxing/zxing/oned/rss/expanded/decoders/AI01392xDecoder.cpp
favoritas37/qzxing
6ea2b31e26db9d43db027ba207f5c73dc9d759fc
[ "Apache-2.0" ]
185
2016-09-08T08:48:46.000Z
2022-03-29T11:55:38.000Z
src/zxing/zxing/oned/rss/expanded/decoders/AI01392xDecoder.cpp
favoritas37/qzxing
6ea2b31e26db9d43db027ba207f5c73dc9d759fc
[ "Apache-2.0" ]
281
2016-09-15T08:42:26.000Z
2022-03-21T17:55:00.000Z
#include "AI01392xDecoder.h" #include <zxing/common/StringUtils.h> namespace zxing { namespace oned { namespace rss { AI01392xDecoder::AI01392xDecoder(QSharedPointer<BitArray> information) : AI01decoder(information) { } String AI01392xDecoder::parseInformation() { if (getInformation()->getSize() < HEADER_SIZE + GTIN_SIZE) { throw NotFoundException(); } String buf(""); encodeCompressedGtin(buf, HEADER_SIZE); int lastAIdigit = getGeneralDecoder().extractNumericValueFromBitArray(HEADER_SIZE + GTIN_SIZE, LAST_DIGIT_SIZE); buf.append("(392"); buf.append(common::StringUtils::intToStr(lastAIdigit)); buf.append(')'); String stub(""); DecodedInformation decodedInformation = getGeneralDecoder().decodeGeneralPurposeField(HEADER_SIZE + GTIN_SIZE + LAST_DIGIT_SIZE, stub); buf.append(decodedInformation.getNewString().getText()); return buf; } } } }
22.428571
107
0.708068
favoritas37
9cc1157138bb7d195fc30a3becae144e49dbb01f
13,194
cpp
C++
unittest/frames.cpp
mkatliar/pinocchio
b755b9cf2567eab39de30a68b2a80fac802a4042
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
unittest/frames.cpp
mkatliar/pinocchio
b755b9cf2567eab39de30a68b2a80fac802a4042
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
unittest/frames.cpp
mkatliar/pinocchio
b755b9cf2567eab39de30a68b2a80fac802a4042
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
// // Copyright (c) 2016-2018 CNRS // #include "pinocchio/multibody/model.hpp" #include "pinocchio/multibody/data.hpp" #include "pinocchio/algorithm/jacobian.hpp" #include "pinocchio/algorithm/frames.hpp" #include "pinocchio/algorithm/rnea.hpp" #include "pinocchio/spatial/act-on-set.hpp" #include "pinocchio/parsers/sample-models.hpp" #include "pinocchio/utils/timer.hpp" #include "pinocchio/algorithm/joint-configuration.hpp" #include <iostream> #include <boost/test/unit_test.hpp> #include <boost/utility/binary.hpp> template<typename Derived> inline bool isFinite(const Eigen::MatrixBase<Derived> & x) { return ((x - x).array() == (x - x).array()).all(); } BOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE ) BOOST_AUTO_TEST_CASE(frame_basic) { using namespace pinocchio; Model model; buildModels::humanoidRandom(model); BOOST_CHECK(model.frames.size() >= size_t(model.njoints)); for(Model::FrameVector::const_iterator it = model.frames.begin(); it != model.frames.end(); ++it) { const Frame & frame = *it; BOOST_CHECK(frame == frame); Frame frame_copy(frame); BOOST_CHECK(frame_copy == frame); } std::ostringstream os; os << Frame() << std::endl; BOOST_CHECK(!os.str().empty()); } BOOST_AUTO_TEST_CASE(cast) { using namespace pinocchio; Frame frame("toto",0,0,SE3::Random(),OP_FRAME); BOOST_CHECK(frame.cast<double>() == frame); BOOST_CHECK(frame.cast<long double>().cast<double>() == frame); } BOOST_AUTO_TEST_CASE ( test_kinematics ) { using namespace Eigen; using namespace pinocchio; pinocchio::Model model; pinocchio::buildModels::humanoidRandom(model); Model::Index parent_idx = model.existJointName("rarm2_joint")?model.getJointId("rarm2_joint"):(Model::Index)(model.njoints-1); const std::string & frame_name = std::string( model.names[parent_idx]+ "_frame"); const SE3 & framePlacement = SE3::Random(); model.addFrame(Frame (frame_name, parent_idx, 0, framePlacement, OP_FRAME)); pinocchio::Data data(model); VectorXd q = VectorXd::Ones(model.nq); q.middleRows<4> (3).normalize(); framesForwardKinematics(model, data, q); BOOST_CHECK(data.oMf[model.getFrameId(frame_name)].isApprox(data.oMi[parent_idx]*framePlacement)); } BOOST_AUTO_TEST_CASE ( test_update_placements ) { using namespace Eigen; using namespace pinocchio; pinocchio::Model model; pinocchio::buildModels::humanoidRandom(model); Model::Index parent_idx = model.existJointName("rarm2_joint")?model.getJointId("rarm2_joint"):(Model::Index)(model.njoints-1); const std::string & frame_name = std::string( model.names[parent_idx]+ "_frame"); const SE3 & framePlacement = SE3::Random(); model.addFrame(Frame (frame_name, parent_idx, 0, framePlacement, OP_FRAME)); Model::FrameIndex frame_idx = model.getFrameId(frame_name); pinocchio::Data data(model); pinocchio::Data data_ref(model); VectorXd q = VectorXd::Ones(model.nq); q.middleRows<4> (3).normalize(); forwardKinematics(model, data, q); updateFramePlacements(model, data); framesForwardKinematics(model, data_ref, q); BOOST_CHECK(data.oMf[frame_idx].isApprox(data_ref.oMf[frame_idx])); } BOOST_AUTO_TEST_CASE ( test_update_single_placement ) { using namespace Eigen; using namespace pinocchio; pinocchio::Model model; pinocchio::buildModels::humanoidRandom(model); Model::Index parent_idx = model.existJointName("rarm2_joint")?model.getJointId("rarm2_joint"):(Model::Index)(model.njoints-1); const std::string & frame_name = std::string( model.names[parent_idx]+ "_frame"); const SE3 & framePlacement = SE3::Random(); model.addFrame(Frame (frame_name, parent_idx, 0, framePlacement, OP_FRAME)); Model::FrameIndex frame_idx = model.getFrameId(frame_name); pinocchio::Data data(model); pinocchio::Data data_ref(model); VectorXd q = VectorXd::Ones(model.nq); q.middleRows<4> (3).normalize(); forwardKinematics(model, data, q); updateFramePlacement(model, data, frame_idx); framesForwardKinematics(model, data_ref, q); BOOST_CHECK(data.oMf[frame_idx].isApprox(data_ref.oMf[frame_idx])); } BOOST_AUTO_TEST_CASE ( test_velocity ) { using namespace Eigen; using namespace pinocchio; pinocchio::Model model; pinocchio::buildModels::humanoidRandom(model); Model::Index parent_idx = model.existJointName("rarm2_joint")?model.getJointId("rarm2_joint"):(Model::Index)(model.njoints-1); const std::string & frame_name = std::string( model.names[parent_idx]+ "_frame"); const SE3 & framePlacement = SE3::Random(); model.addFrame(Frame (frame_name, parent_idx, 0, framePlacement, OP_FRAME)); Model::FrameIndex frame_idx = model.getFrameId(frame_name); pinocchio::Data data(model); VectorXd q = VectorXd::Ones(model.nq); q.middleRows<4> (3).normalize(); VectorXd v = VectorXd::Ones(model.nv); forwardKinematics(model, data, q, v); Motion vf = getFrameVelocity(model, data, frame_idx); BOOST_CHECK(vf.isApprox(framePlacement.actInv(data.v[parent_idx]))); } BOOST_AUTO_TEST_CASE ( test_acceleration ) { using namespace Eigen; using namespace pinocchio; pinocchio::Model model; pinocchio::buildModels::humanoidRandom(model); Model::Index parent_idx = model.existJointName("rarm2_joint")?model.getJointId("rarm2_joint"):(Model::Index)(model.njoints-1); const std::string & frame_name = std::string( model.names[parent_idx]+ "_frame"); const SE3 & framePlacement = SE3::Random(); model.addFrame(Frame (frame_name, parent_idx, 0, framePlacement, OP_FRAME)); Model::FrameIndex frame_idx = model.getFrameId(frame_name); pinocchio::Data data(model); VectorXd q = VectorXd::Ones(model.nq); q.middleRows<4> (3).normalize(); VectorXd v = VectorXd::Ones(model.nv); VectorXd a = VectorXd::Ones(model.nv); forwardKinematics(model, data, q, v, a); Motion af = getFrameAcceleration(model, data, frame_idx); BOOST_CHECK(af.isApprox(framePlacement.actInv(data.a[parent_idx]))); } BOOST_AUTO_TEST_CASE ( test_get_frame_jacobian ) { using namespace Eigen; using namespace pinocchio; Model model; buildModels::humanoidRandom(model); Model::Index parent_idx = model.existJointName("rarm2_joint")?model.getJointId("rarm2_joint"):(Model::Index)(model.njoints-1); const std::string & frame_name = std::string( model.names[parent_idx]+ "_frame"); const SE3 & framePlacement = SE3::Random(); model.addFrame(Frame (frame_name, parent_idx, 0, framePlacement, OP_FRAME)); BOOST_CHECK(model.existFrame(frame_name)); pinocchio::Data data(model); pinocchio::Data data_ref(model); model.lowerPositionLimit.head<7>().fill(-1.); model.upperPositionLimit.head<7>().fill( 1.); VectorXd q = randomConfiguration(model); VectorXd v = VectorXd::Ones(model.nv); /// In local frame Model::Index idx = model.getFrameId(frame_name); const Frame & frame = model.frames[idx]; BOOST_CHECK(frame.placement.isApprox_impl(framePlacement)); Data::Matrix6x Jjj(6,model.nv); Jjj.fill(0); Data::Matrix6x Jff(6,model.nv); Jff.fill(0); computeJointJacobians(model,data,q); updateFramePlacement(model, data, idx); getFrameJacobian(model, data, idx, LOCAL, Jff); computeJointJacobians(model,data_ref,q); getJointJacobian(model, data_ref, parent_idx, LOCAL, Jjj); Motion nu_frame = Motion(Jff*v); Motion nu_joint = Motion(Jjj*v); const SE3::ActionMatrixType jXf = frame.placement.toActionMatrix(); Data::Matrix6x Jjj_from_frame(jXf * Jff); BOOST_CHECK(Jjj_from_frame.isApprox(Jjj)); BOOST_CHECK(nu_frame.isApprox(frame.placement.actInv(nu_joint), 1e-12)); // In world frame getFrameJacobian(model,data,idx,WORLD,Jff); getJointJacobian(model, data_ref, parent_idx,WORLD, Jjj); BOOST_CHECK(Jff.isApprox(Jjj)); } BOOST_AUTO_TEST_CASE ( test_frame_jacobian ) { using namespace Eigen; using namespace pinocchio; Model model; buildModels::humanoidRandom(model); Model::Index parent_idx = model.existJointName("rarm2_joint")?model.getJointId("rarm2_joint"):(Model::Index)(model.njoints-1); const std::string & frame_name = std::string( model.names[parent_idx]+ "_frame"); const SE3 & framePlacement = SE3::Random(); model.addFrame(Frame (frame_name, parent_idx, 0, framePlacement, OP_FRAME)); BOOST_CHECK(model.existFrame(frame_name)); pinocchio::Data data(model); pinocchio::Data data_ref(model); model.lowerPositionLimit.head<7>().fill(-1.); model.upperPositionLimit.head<7>().fill( 1.); VectorXd q = randomConfiguration(model); VectorXd v = VectorXd::Ones(model.nv); Model::Index idx = model.getFrameId(frame_name); const Frame & frame = model.frames[idx]; BOOST_CHECK(frame.placement.isApprox_impl(framePlacement)); Data::Matrix6x Jf(6,model.nv); Jf.fill(0); Data::Matrix6x Jf_ref(6,model.nv); Jf_ref.fill(0); frameJacobian(model, data_ref, q, idx, Jf); computeJointJacobians(model, data_ref, q); updateFramePlacement(model, data_ref, idx); getFrameJacobian(model, data_ref, idx, LOCAL, Jf_ref); BOOST_CHECK(Jf.isApprox(Jf_ref)); } BOOST_AUTO_TEST_CASE ( test_frame_jacobian_time_variation ) { using namespace Eigen; using namespace pinocchio; pinocchio::Model model; pinocchio::buildModels::humanoidRandom(model); Model::Index parent_idx = model.existJointName("rarm2_joint")?model.getJointId("rarm2_joint"):(Model::Index)(model.njoints-1); const std::string & frame_name = std::string( model.names[parent_idx]+ "_frame"); const SE3 & framePlacement = SE3::Random(); model.addFrame(Frame (frame_name, parent_idx, 0, framePlacement, OP_FRAME)); pinocchio::Data data(model); pinocchio::Data data_ref(model); VectorXd q = randomConfiguration(model, -1 * Eigen::VectorXd::Ones(model.nq), Eigen::VectorXd::Ones(model.nq) ); VectorXd v = VectorXd::Random(model.nv); VectorXd a = VectorXd::Random(model.nv); computeJointJacobiansTimeVariation(model,data,q,v); updateFramePlacements(model,data); forwardKinematics(model,data_ref,q,v,a); updateFramePlacements(model,data_ref); BOOST_CHECK(isFinite(data.dJ)); Model::Index idx = model.getFrameId(frame_name); const Frame & frame = model.frames[idx]; BOOST_CHECK(frame.placement.isApprox_impl(framePlacement)); Data::Matrix6x J(6,model.nv); J.fill(0.); Data::Matrix6x dJ(6,model.nv); dJ.fill(0.); // Regarding to the world origin getFrameJacobian(model,data,idx,WORLD,J); getFrameJacobianTimeVariation(model,data,idx,WORLD,dJ); Motion v_idx(J*v); const Motion & v_ref_local = frame.placement.actInv(data_ref.v[parent_idx]); const Motion & v_ref = data_ref.oMf[idx].act(v_ref_local); BOOST_CHECK(v_idx.isApprox(v_ref)); Motion a_idx(J*a + dJ*v); const Motion & a_ref_local = frame.placement.actInv(data_ref.a[parent_idx]); const Motion & a_ref = data_ref.oMf[idx].act(a_ref_local); BOOST_CHECK(a_idx.isApprox(a_ref)); J.fill(0.); dJ.fill(0.); // Regarding to the local frame getFrameJacobian(model,data,idx,LOCAL,J); getFrameJacobianTimeVariation(model,data,idx,LOCAL,dJ); v_idx = (Motion::Vector6)(J*v); BOOST_CHECK(v_idx.isApprox(v_ref_local)); a_idx = (Motion::Vector6)(J*a + dJ*v); BOOST_CHECK(a_idx.isApprox(a_ref_local)); // compare to finite differencies { Data data_ref(model), data_ref_plus(model); const double alpha = 1e-8; Eigen::VectorXd q_plus(model.nq); q_plus = integrate(model,q,alpha*v); //data_ref Data::Matrix6x J_ref_world(6,model.nv), J_ref_local(6,model.nv); J_ref_world.fill(0.); J_ref_local.fill(0.); computeJointJacobians(model,data_ref,q); updateFramePlacements(model,data_ref); const SE3 & oMf_q = data_ref.oMf[idx]; getFrameJacobian(model,data_ref,idx,WORLD,J_ref_world); getFrameJacobian(model,data_ref,idx,LOCAL,J_ref_local); //data_ref_plus Data::Matrix6x J_ref_plus_world(6,model.nv), J_ref_plus_local(6,model.nv); J_ref_plus_world.fill(0.); J_ref_plus_local.fill(0.); computeJointJacobians(model,data_ref_plus,q_plus); updateFramePlacements(model,data_ref_plus); const SE3 & oMf_qplus = data_ref_plus.oMf[idx]; getFrameJacobian(model,data_ref_plus,idx,WORLD,J_ref_plus_world); getFrameJacobian(model,data_ref_plus,idx,LOCAL,J_ref_plus_local); //Move J_ref_plus_local to reference frame J_ref_plus_local = (oMf_q.inverse()*oMf_qplus).toActionMatrix()*(J_ref_plus_local); Data::Matrix6x dJ_ref_world(6,model.nv), dJ_ref_local(6,model.nv); dJ_ref_world.fill(0.); dJ_ref_local.fill(0.); dJ_ref_world = (J_ref_plus_world - J_ref_world)/alpha; dJ_ref_local = (J_ref_plus_local - J_ref_local)/alpha; //data computeJointJacobiansTimeVariation(model,data,q,v); forwardKinematics(model,data,q,v); updateFramePlacements(model,data); Data::Matrix6x dJ_world(6,model.nv), dJ_local(6,model.nv); dJ_world.fill(0.); dJ_local.fill(0.); getFrameJacobianTimeVariation(model,data,idx,WORLD,dJ_world); getFrameJacobianTimeVariation(model,data,idx,LOCAL,dJ_local); BOOST_CHECK(dJ_world.isApprox(dJ_ref_world,sqrt(alpha))); BOOST_CHECK(dJ_local.isApprox(dJ_ref_local,sqrt(alpha))); } } BOOST_AUTO_TEST_SUITE_END ()
35.184
128
0.729422
mkatliar
9cc199dc596089246d7a3aec04a6b2a86ccb61cf
8,026
cpp
C++
BuffManager/Motor2D/j1BuffManager.cpp
JosepLleal/Research_Buff_Manager
ce2664155bea8cc38567ed1c9d505cd7b717a6a4
[ "MIT" ]
null
null
null
BuffManager/Motor2D/j1BuffManager.cpp
JosepLleal/Research_Buff_Manager
ce2664155bea8cc38567ed1c9d505cd7b717a6a4
[ "MIT" ]
null
null
null
BuffManager/Motor2D/j1BuffManager.cpp
JosepLleal/Research_Buff_Manager
ce2664155bea8cc38567ed1c9d505cd7b717a6a4
[ "MIT" ]
2
2019-03-11T14:47:12.000Z
2021-03-31T23:16:01.000Z
#include "j1App.h" #include "j1Player.h" #include "j1Input.h" #include "j1Timer.h" #include "j1BuffManager.h" #include "p2Log.h" j1BuffManager::j1BuffManager(): j1Module() { name.assign("BuffManager"); } j1BuffManager::~j1BuffManager() { } bool j1BuffManager::Awake() { return true; } bool j1BuffManager::Start() { pugi::xml_parse_result res = buffmanager_xml.load_file("buff_manager.xml");; node = buffmanager_xml.document_element(); LoadEffects(node); return true; } bool j1BuffManager::Update(float dt) { // better optimization if this is done on the update of every entity --> (&effect, this) // TEMPORARY EFFECT RestartAttribute(&effects[WAR_CRY], App->player); // PER TICK ApplyEachTick(&effects[POISON], App->player); // LIMIT THE ATTRIBUTES OF Entities LimitAttributes(App->player); return true; } bool j1BuffManager::CleanUp() { delete effects; return true; } void j1BuffManager::ApplyEffect(Effect* effect, j1Player *entity) { if (effect->duration_type == PERMANENT) { switch (effect->attribute_to_change) { case HEALTH: DoMath(entity->health, effect->bonus, effect->method, effect->type); DoMath(entity->og_health, effect->bonus, effect->method, effect->type); break; case STRENGTH: DoMath(entity->strength, effect->bonus, effect->method, effect->type); DoMath(entity->og_strength, effect->bonus, effect->method, effect->type); break; case ARMOR: DoMath(entity->armor, effect->bonus, effect->method, effect->type); DoMath(entity->og_armor, effect->bonus, effect->method, effect->type); break; case SPEED: DoMath(entity->speed, effect->bonus, effect->method, effect->type); DoMath(entity->og_speed, effect->bonus, effect->method, effect->type); break; } } else if (effect->duration_type == TEMPORARY) // we have to put manually every NEW EFFECT that has a TIMER (and create the timer in entity.h or in this case in Player.h) { switch (effect->attribute_to_change) { case HEALTH: if (effect->name == effects[HEAL].name) { if (entity->heal_active == false) { DoMath(entity->health, effect->bonus, effect->method, effect->type); entity->heal_active = true; } entity->healing.Start(); // timer starts } break; case STRENGTH: if (effect->name == effects[WAR_CRY].name) { if (entity->war_cry_active == false) { DoMath(entity->strength, effect->bonus, effect->method, effect->type); entity->war_cry_active = true; } entity->war_cry.Start(); } break; case ARMOR: DoMath(entity->armor, effect->bonus, effect->method, effect->type); break; case SPEED: DoMath(entity->speed, effect->bonus, effect->method, effect->type); break; } } else if (effect->duration_type == PER_TICK)// we have to put manually every NEW EFFECT that has a TIMER (and create the timer in entity.h or in this case Player.h) { switch (effect->attribute_to_change) { case HEALTH: if (effect->name == effects[POISON].name) { if (entity->poison_tick_active == false) { entity->poison_tick_active = true; } entity->poison_tick.Start(); // start or restart timer entity->poison_tick_iterator = 0; //restart iterator } break; case STRENGTH: break; case ARMOR: break; case SPEED: break; } } } void j1BuffManager::DoMath(int &att_value, float bonus, EffectMethod method, EffectType eff_type) { if (eff_type == BUFF) { if (method == ADD) { att_value += bonus; } else if (method == MULTIPLY) { att_value *= bonus; } else if (method == PERCENTAGE) { att_value += att_value * (bonus / 100); } } else if (eff_type == DEBUFF) { if (method == ADD) { att_value -= bonus; } else if (method == MULTIPLY) { att_value /= bonus; } else if (method == PERCENTAGE) { att_value -= att_value * (bonus / 100); } } } void j1BuffManager::RestartAttribute(Effect *effect, j1Player *entity) //Check all the TEMPORAY effects of an entity and { if (effect->name == effects[HEAL].name) { if (entity->heal_active == true && entity->healing.ReadSec() > effect->duration_value) { entity->health = entity->og_health; entity->heal_active = false; } } else if (effect->name == effects[WAR_CRY].name) { if (entity->war_cry_active == true && entity->war_cry.ReadSec() > effect->duration_value) { entity->strength = entity->og_strength; entity->war_cry_active = false; } } } void j1BuffManager::ApplyEachTick(Effect * effect, j1Player * entity) //Check all the PER_TICK effects of an entity { if (effect->name == effects[POISON].name) { if (entity->poison_tick_active == true) { if (entity->poison_tick.ReadSec() > effect->duration_value) { entity->poison_tick_active = false; entity->poison_tick_iterator = 0; } if (entity->poison_tick.ReadSec() > entity->poison_tick_iterator) { DoMath(entity->health, effect->bonus, effect->method, effect->type); DoMath(entity->og_health, effect->bonus, effect->method, effect->type); entity->poison_tick_iterator++; } } } } void j1BuffManager::LimitAttributes(j1Player * entity) { // HEALTH ATT if (entity->og_health > MAX_HEALTH) entity->og_health = MAX_HEALTH; else if (entity->og_health < MIN_HEALTH) entity->og_health = MIN_HEALTH; if (entity->health > MAX_HEALTH) entity->health = MAX_HEALTH; else if (entity->health < MIN_HEALTH) entity->health = MIN_HEALTH; // STRENGTH ATT if (entity->og_strength > MAX_STRENGTH) entity->og_strength = MAX_STRENGTH; else if (entity->og_strength < MIN_STRENGTH) entity->og_strength = MIN_STRENGTH; if (entity->strength > MAX_STRENGTH) entity->strength = MAX_STRENGTH; else if (entity->strength < MIN_STRENGTH) entity->strength = MIN_STRENGTH; // ARMOR ATT if (entity->og_armor > MAX_ARMOR) entity->og_armor = MAX_ARMOR; else if (entity->og_armor < MIN_ARMOR) entity->og_armor = MIN_ARMOR; if (entity->armor > MAX_ARMOR) entity->armor = MAX_ARMOR; else if (entity->armor < MIN_ARMOR) entity->armor = MIN_ARMOR; // SPEED ATT if (entity->og_speed > MAX_SPEED) entity->og_speed = MAX_SPEED; else if (entity->og_speed < MIN_SPEED) entity->og_speed = MIN_SPEED; if (entity->speed > MAX_SPEED) entity->speed = MAX_SPEED; else if (entity->speed < MIN_SPEED) entity->speed = MIN_SPEED; } void j1BuffManager::LoadEffects(pugi::xml_node & data) { pugi::xml_node iterator; Effect effect; for (iterator = data.child("effect"); iterator; iterator = iterator.next_sibling("effect")) { effect.name = iterator.attribute("name").as_string(); SetValue(effect, iterator.attribute("type").as_string()); SetValue(effect, iterator.attribute("duration_type").as_string()); SetValue(effect, iterator.attribute("method").as_string()); SetValue(effect, iterator.attribute("att_to_change").as_string()); effect.bonus = iterator.attribute("bonus").as_int(); effect.duration_value = iterator.attribute("duration_value").as_int(); effects[iterator.attribute("id").as_int()] = effect; CreatedEffects++; } } void j1BuffManager::SetValue(Effect &effect, std::string string) { if (string == "BUFF" ) { effect.type = BUFF; } else if (string == "DEBUFF") { effect.type = DEBUFF; } else if (string == "PERMANENT") { effect.duration_type = PERMANENT; } else if (string == "TEMPORARY") { effect.duration_type = TEMPORARY; } else if (string == "PER_TICK") { effect.duration_type = PER_TICK; } else if (string == "ADD") { effect.method = ADD; } else if (string == "MULTIPLY") { effect.method = MULTIPLY; } else if (string == "PERCENTAGE") { effect.method = PERCENTAGE; } else if (string == "HEALTH") { effect.attribute_to_change = HEALTH; } else if (string == "ARMOR") { effect.attribute_to_change = ARMOR; } else if (string == "STRENGTH") { effect.attribute_to_change = STRENGTH; } else if (string == "SPEED") { effect.attribute_to_change = SPEED; } }
21.928962
169
0.673187
JosepLleal
9cc4004973cc2adf5de2c34cfd08284e676f4b9e
1,043
cpp
C++
sample-source/OPENCVBook/chapter03/3.1.7 RotatedRect/rotatedRect.cpp
doukhee/opencv-study
b7e8a5c916070ebc762c33d7fe307b6fcf88abf4
[ "MIT" ]
null
null
null
sample-source/OPENCVBook/chapter03/3.1.7 RotatedRect/rotatedRect.cpp
doukhee/opencv-study
b7e8a5c916070ebc762c33d7fe307b6fcf88abf4
[ "MIT" ]
null
null
null
sample-source/OPENCVBook/chapter03/3.1.7 RotatedRect/rotatedRect.cpp
doukhee/opencv-study
b7e8a5c916070ebc762c33d7fe307b6fcf88abf4
[ "MIT" ]
null
null
null
#include <opencv2/opencv.hpp> using namespace std; using namespace cv; int main() { /* ํ–‰๋ ฌ ์„ ์–ธ */ Mat image(300, 500, CV_8UC1, Scalar(255)); Point2f center(250, 150), pts[4]; Size2f size(300, 100); /* ํšŒ์ „ ์‚ฌ๊ฐํ˜• ์„ ์–ธ */ /* RotatedRect๋Š” ํšŒ์ „๋œ ์‚ฌ๊ฐํ˜•์„ ๋‚˜ํƒ€๋‚ด๊ธฐ ์œ„ํ•œ ํด๋ž˜์Šค */ /* RotatedRect(cont Point2f& center, const Size& size, float angle) */ RotatedRect rot_rect(center, size, 20); /* ํšŒ์ „ ์‚ฌ๊ฐํ˜•์˜ 4๊ฐœ ๋ชจ์„œ๋ฆฌ๋ฅผ ๋ชจ๋‘ ํฌํ•จํ•˜๋Š” ์ตœ์†Œ ํฌ๊ธฐ์˜ ์‚ฌ๊ฐํ˜• ์˜์—ญ ๋ฐ˜ํ™˜ */ Rect bound_rect = rot_rect.boundingRect(); /* ์‚ฌ๊ฐํ˜• ๊ทธ๋ฆฌ๊ธฐ */ rectangle(image, bound_rect, Scalar(0), 1); /* ์›๊ทธ๋ฆฌ๊ธฐ */ /* rot_rect์˜ ์ค‘์‹ฌ์ ์— ์› ๊ทธ๋ฆฌ๊ธฐ */ circle(image, rot_rect.center, 1, Scalar(0), 2); /* ๊ธฐ์šธ์—ฌ์ง„ ์ขŒํ‘œ ์ €์žฅ ํšŒ์ „์‚ฌ๊ฐํ˜• ๊ผญ์ง“์  ๋ฐ˜ํ™˜ */ /* ์ธ์ˆ˜๋กœ ์ž…๋ ฅ๋œ pts ๋ฐฐ์—ด์— ํšŒ์ „์‚ฌ๊ฐํ˜•์˜ 4๊ฐœ์˜ ๊ผญ์ง€์ ์„ ์ „๋‹ฌ ํ•œ๋‹ค */ rot_rect.points(pts); for(int i = 0; i < 4; i++) { /* ๊ผญ์ง“์  ํ‘œ์‹œ */ circle(image, pts[i], 4, Scalar(0), 1); /* ๊ธฐ์šธ์—ฌ์ง„ ์‚ฌ๊ฐํ˜• ๊ทธ๋ฆฌ๊ธฐ ๊ผญ์ง“์  ์žˆ๋Š” ์ง์„  */ line(image, pts[i], pts[(i+1)%4], Scalar(0), 2); } imshow("rotated rect", image); waitKey(0); return 0; }
28.189189
74
0.57047
doukhee