blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
123d90bf2a526ce9ebe633b80602b60074d7e250
2ae822aad632e46ecdd7939b878827344cf5ccf6
/lib/VM/GCBase.cpp
2b0a2df0429a64ef17bd674aa6e05e48135f6aef
[ "MIT" ]
permissive
sassembla/hermes
d39c0cb70a7981c2905945ee28daca944f922fc4
643096b07b6249f056b1645c2d7f346436f65f6c
refs/heads/master
2023-02-19T05:30:16.431391
2021-01-23T11:04:10
2021-01-23T11:06:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
40,715
cpp
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #define DEBUG_TYPE "gc" #include "hermes/VM/GC.h" #include "hermes/Platform/Logging.h" #include "hermes/Support/ErrorHandling.h" #include "hermes/Support/OSCompat.h" #include "hermes/VM/CellKind.h" #include "hermes/VM/GCBase-inline.h" #include "hermes/VM/GCPointer-inline.h" #include "hermes/VM/JSWeakMapImpl.h" #include "hermes/VM/RootAndSlotAcceptorDefault.h" #include "hermes/VM/Runtime.h" #include "hermes/VM/VTable.h" #include "llvh/Support/Debug.h" #include "llvh/Support/FileSystem.h" #include "llvh/Support/Format.h" #include "llvh/Support/NativeFormatting.h" #include "llvh/Support/raw_os_ostream.h" #include "llvh/Support/raw_ostream.h" #include <inttypes.h> #include <stdexcept> #include <system_error> using llvh::dbgs; using llvh::format; namespace hermes { namespace vm { const char GCBase::kNaturalCauseForAnalytics[] = "natural"; const char GCBase::kHandleSanCauseForAnalytics[] = "handle-san"; GCBase::GCBase( MetadataTable metaTable, GCCallbacks *gcCallbacks, PointerBase *pointerBase, const GCConfig &gcConfig, std::shared_ptr<CrashManager> crashMgr) : metaTable_(metaTable), gcCallbacks_(gcCallbacks), pointerBase_(pointerBase), crashMgr_(crashMgr), analyticsCallback_(gcConfig.getAnalyticsCallback()), recordGcStats_(gcConfig.getShouldRecordStats()), // Start off not in GC. inGC_(false), name_(gcConfig.getName()), allocationLocationTracker_(this), #ifdef HERMESVM_SANITIZE_HANDLES sanitizeRate_(gcConfig.getSanitizeConfig().getSanitizeRate()), #endif tripwireCallback_(gcConfig.getTripwireConfig().getCallback()), tripwireLimit_(gcConfig.getTripwireConfig().getLimit()) #ifndef NDEBUG , randomizeAllocSpace_(gcConfig.getShouldRandomizeAllocSpace()) #endif { #ifdef HERMESVM_PLATFORM_LOGGING hermesLog( "HermesGC", "Initialisation (Init: %dMB, Max: %dMB, Tripwire: %dMB)", gcConfig.getInitHeapSize() >> 20, gcConfig.getMaxHeapSize() >> 20, gcConfig.getTripwireConfig().getLimit() >> 20); #endif // HERMESVM_PLATFORM_LOGGING #ifdef HERMESVM_SANITIZE_HANDLES const std::minstd_rand::result_type seed = gcConfig.getSanitizeConfig().getRandomSeed() >= 0 ? gcConfig.getSanitizeConfig().getRandomSeed() : std::random_device()(); if (sanitizeRate_ > 0.0 && sanitizeRate_ < 1.0) { llvh::errs() << "Warning: you are using handle sanitization with random sampling.\n" << "Sanitize Rate: "; llvh::write_double(llvh::errs(), sanitizeRate_, llvh::FloatStyle::Percent); llvh::errs() << "\n" << "Sanitize Rate Seed: " << seed << "\n" << "Re-run with -gc-sanitize-handles-random-seed=" << seed << " for deterministic crashes.\n"; } randomEngine_.seed(seed); #endif } GCBase::GCCycle::GCCycle( GCBase *gc, OptValue<GCCallbacks *> gcCallbacksOpt, std::string extraInfo) : gc_(gc), gcCallbacksOpt_(gcCallbacksOpt), extraInfo_(std::move(extraInfo)), previousInGC_(gc_->inGC_) { if (!previousInGC_) { if (gcCallbacksOpt_.hasValue()) { gcCallbacksOpt_.getValue()->onGCEvent( GCEventKind::CollectionStart, extraInfo_); } gc_->inGC_ = true; } } GCBase::GCCycle::~GCCycle() { if (!previousInGC_) { gc_->inGC_ = false; if (gcCallbacksOpt_.hasValue()) { gcCallbacksOpt_.getValue()->onGCEvent( GCEventKind::CollectionEnd, extraInfo_); } } } void GCBase::runtimeWillExecute() { if (recordGcStats_ && !execStartTimeRecorded_) { execStartTime_ = std::chrono::steady_clock::now(); execStartCPUTime_ = oscompat::thread_cpu_time(); oscompat::num_context_switches( startNumVoluntaryContextSwitches_, startNumInvoluntaryContextSwitches_); execStartTimeRecorded_ = true; } } std::error_code GCBase::createSnapshotToFile(const std::string &fileName) { std::error_code code; llvh::raw_fd_ostream os(fileName, code, llvh::sys::fs::FileAccess::FA_Write); if (code) { return code; } createSnapshot(os); return std::error_code{}; } namespace { constexpr HeapSnapshot::NodeID objectIDForRootSection( RootAcceptor::Section section) { // Since root sections start at zero, and in IDTracker the root sections // start one past the reserved GC root, this number can be added to // do conversions. return GCBase::IDTracker::reserved( static_cast<GCBase::IDTracker::ReservedObjectID>( static_cast<HeapSnapshot::NodeID>( GCBase::IDTracker::ReservedObjectID::GCRoots) + 1 + static_cast<HeapSnapshot::NodeID>(section))); } // Abstract base class for all snapshot acceptors. struct SnapshotAcceptor : public RootAndSlotAcceptorWithNamesDefault { using RootAndSlotAcceptorWithNamesDefault::accept; SnapshotAcceptor(PointerBase *base, HeapSnapshot &snap) : RootAndSlotAcceptorWithNamesDefault(base), snap_(snap) {} void acceptHV(HermesValue &hv, const char *name) override { if (hv.isPointer()) { auto ptr = hv.getPointer(); accept(ptr, name); } } protected: HeapSnapshot &snap_; }; struct PrimitiveNodeAcceptor : public SnapshotAcceptor { using SnapshotAcceptor::accept; PrimitiveNodeAcceptor( PointerBase *base, HeapSnapshot &snap, GCBase::IDTracker &tracker) : SnapshotAcceptor(base, snap), tracker_(tracker) {} // Do nothing for any value except a number. void accept(void *&ptr, const char *name) override {} void acceptHV(HermesValue &hv, const char *) override { if (hv.isNumber()) { seenNumbers_.insert(hv.getNumber()); } } void writeAllNodes() { // Always write out the nodes for singletons. snap_.beginNode(); snap_.endNode( HeapSnapshot::NodeType::Object, "undefined", GCBase::IDTracker::reserved( GCBase::IDTracker::ReservedObjectID::Undefined), 0, 0); snap_.beginNode(); snap_.endNode( HeapSnapshot::NodeType::Object, "null", GCBase::IDTracker::reserved(GCBase::IDTracker::ReservedObjectID::Null), 0, 0); snap_.beginNode(); snap_.endNode( HeapSnapshot::NodeType::Object, "true", GCBase::IDTracker::reserved(GCBase::IDTracker::ReservedObjectID::True), 0, 0); snap_.beginNode(); snap_.endNode( HeapSnapshot::NodeType::Object, "false", GCBase::IDTracker::reserved(GCBase::IDTracker::ReservedObjectID::False), 0, 0); for (double num : seenNumbers_) { // A number never has any edges, so just make a node for it. snap_.beginNode(); // Convert the number value to a string, according to the JS conversion // routines. char buf[hermes::NUMBER_TO_STRING_BUF_SIZE]; size_t len = hermes::numberToString(num, buf, sizeof(buf)); snap_.endNode( HeapSnapshot::NodeType::Number, llvh::StringRef{buf, len}, tracker_.getNumberID(num), // Numbers are zero-sized in the heap because they're stored inline. 0, 0); } } private: GCBase::IDTracker &tracker_; // Track all numbers that are seen in a heap pass, and only emit one node for // each of them. llvh::DenseSet<double, GCBase::IDTracker::DoubleComparator> seenNumbers_; }; struct EdgeAddingAcceptor : public SnapshotAcceptor, public WeakRefAcceptor { using SnapshotAcceptor::accept; EdgeAddingAcceptor(GCBase &gc, HeapSnapshot &snap) : SnapshotAcceptor(gc.getPointerBase(), snap), gc_(gc) {} void accept(void *&ptr, const char *name) override { if (!ptr) { return; } snap_.addNamedEdge( HeapSnapshot::EdgeType::Internal, llvh::StringRef::withNullAsEmpty(name), gc_.getObjectID(ptr)); } void acceptHV(HermesValue &hv, const char *name) override { if (auto id = gc_.getSnapshotID(hv)) { snap_.addNamedEdge( HeapSnapshot::EdgeType::Internal, llvh::StringRef::withNullAsEmpty(name), id.getValue()); } } void accept(WeakRefBase &wr) override { WeakRefSlot *slot = wr.unsafeGetSlot(); if (slot->state() == WeakSlotState::Free) { // If the slot is free, there's no edge to add. return; } if (!slot->hasPointer()) { // Filter out empty refs from adding edges. return; } // Assume all weak pointers have no names, and are stored in an array-like // structure. std::string indexName = oscompat::to_string(nextEdge_++); snap_.addNamedEdge( HeapSnapshot::EdgeType::Weak, indexName, gc_.getObjectID(slot->getPointer())); } void acceptSym(SymbolID sym, const char *name) override { if (sym.isInvalid()) { return; } snap_.addNamedEdge( HeapSnapshot::EdgeType::Internal, llvh::StringRef::withNullAsEmpty(name), gc_.getObjectID(sym)); } private: GCBase &gc_; // For unnamed edges, use indices instead. unsigned nextEdge_{0}; }; struct SnapshotRootSectionAcceptor : public SnapshotAcceptor, public WeakRootAcceptorDefault { using SnapshotAcceptor::accept; using WeakRootAcceptor::acceptWeak; SnapshotRootSectionAcceptor(PointerBase *base, HeapSnapshot &snap) : SnapshotAcceptor(base, snap), WeakRootAcceptorDefault(base) {} void accept(void *&, const char *) override { // While adding edges to root sections, there's no need to do anything for // pointers. } void accept(WeakRefBase &wr) override { // Same goes for weak refs. } void acceptWeak(void *&ptr) override { // Same goes for weak pointers. } void beginRootSection(Section section) override { // Make an element edge from the super root to each root section. snap_.addIndexedEdge( HeapSnapshot::EdgeType::Element, rootSectionNum_++, objectIDForRootSection(section)); } void endRootSection() override { // Do nothing for the end of the root section. } private: // v8's roots start numbering at 1. int rootSectionNum_{1}; }; struct SnapshotRootAcceptor : public SnapshotAcceptor, public WeakRootAcceptorDefault { using SnapshotAcceptor::accept; using WeakRootAcceptor::acceptWeak; SnapshotRootAcceptor(GCBase &gc, HeapSnapshot &snap) : SnapshotAcceptor(gc.getPointerBase(), snap), WeakRootAcceptorDefault(gc.getPointerBase()), gc_(gc) {} void accept(void *&ptr, const char *name) override { pointerAccept(ptr, name, false); } void acceptWeak(void *&ptr) override { pointerAccept(ptr, nullptr, true); } void accept(WeakRefBase &wr) override { WeakRefSlot *slot = wr.unsafeGetSlot(); if (slot->state() == WeakSlotState::Free) { // If the slot is free, there's no edge to add. return; } if (!slot->hasPointer()) { // Filter out empty refs from adding edges. return; } pointerAccept(slot->getPointer(), nullptr, true); } void provideSnapshot( const std::function<void(HeapSnapshot &)> &func) override { func(snap_); } void beginRootSection(Section section) override { assert( currentSection_ == Section::InvalidSection && "beginRootSection called while previous section is open"); snap_.beginNode(); currentSection_ = section; } void endRootSection() override { // A root section creates a synthetic node with that name and makes edges // come from that root. static const char *rootNames[] = { // Parentheses around the name is adopted from V8's roots. #define ROOT_SECTION(name) "(" #name ")", #include "hermes/VM/RootSections.def" }; snap_.endNode( HeapSnapshot::NodeType::Synthetic, rootNames[static_cast<unsigned>(currentSection_)], objectIDForRootSection(currentSection_), // The heap visualizer doesn't like it when these synthetic nodes have a // size (it describes them as living in the heap). 0, 0); currentSection_ = Section::InvalidSection; // Reset the edge counter, so each root section's unnamed edges start at // zero. nextEdge_ = 0; } private: GCBase &gc_; llvh::DenseSet<HeapSnapshot::NodeID> seenIDs_; // For unnamed edges, use indices instead. unsigned nextEdge_{0}; Section currentSection_{Section::InvalidSection}; void pointerAccept(void *ptr, const char *name, bool weak) { assert( currentSection_ != Section::InvalidSection && "accept called outside of begin/end root section pair"); if (!ptr) { return; } const auto id = gc_.getObjectID(ptr); if (!seenIDs_.insert(id).second) { // Already seen this node, don't add another edge. return; } auto nameRef = llvh::StringRef::withNullAsEmpty(name); if (!nameRef.empty()) { snap_.addNamedEdge( weak ? HeapSnapshot::EdgeType::Weak : HeapSnapshot::EdgeType::Internal, nameRef, id); } else if (weak) { std::string numericName = oscompat::to_string(nextEdge_++); snap_.addNamedEdge(HeapSnapshot::EdgeType::Weak, numericName.c_str(), id); } else { // Unnamed edges get indices. snap_.addIndexedEdge(HeapSnapshot::EdgeType::Element, nextEdge_++, id); } } }; } // namespace void GCBase::createSnapshot(GC *gc, llvh::raw_ostream &os) { JSONEmitter json(os); HeapSnapshot snap(json, gcCallbacks_->getStackTracesTree()); const auto rootScan = [gc, &snap, this]() { { // Make the super root node and add edges to each root section. SnapshotRootSectionAcceptor rootSectionAcceptor(getPointerBase(), snap); // The super root has a single element pointing to the "(GC roots)" // synthetic node. v8 also has some "shortcut" edges to things like the // global object, but those don't seem necessary for correctness. snap.beginNode(); snap.addIndexedEdge( HeapSnapshot::EdgeType::Element, 1, IDTracker::reserved(IDTracker::ReservedObjectID::GCRoots)); snap.endNode( HeapSnapshot::NodeType::Synthetic, "", IDTracker::reserved(IDTracker::ReservedObjectID::SuperRoot), 0, 0); snapshotAddGCNativeNodes(snap); snap.beginNode(); gc->markRoots(rootSectionAcceptor, true); gc->markWeakRoots(rootSectionAcceptor); snapshotAddGCNativeEdges(snap); snap.endNode( HeapSnapshot::NodeType::Synthetic, "(GC roots)", static_cast<HeapSnapshot::NodeID>( IDTracker::reserved(IDTracker::ReservedObjectID::GCRoots)), 0, 0); } { // Make a node for each root section and add edges into the actual heap. // Within a root section, there might be duplicates. The root acceptor // filters out duplicate edges because there cannot be duplicate edges to // nodes reachable from the super root. SnapshotRootAcceptor rootAcceptor(*gc, snap); gc->markRoots(rootAcceptor, true); gc->markWeakRoots(rootAcceptor); } gcCallbacks_->visitIdentifiers( [gc, &snap, this](SymbolID sym, const StringPrimitive *str) { snap.beginNode(); if (str) { snap.addNamedEdge( HeapSnapshot::EdgeType::Internal, "description", gc->getObjectID(str)); } snap.endNode( HeapSnapshot::NodeType::Symbol, gc->convertSymbolToUTF8(sym), idTracker_.getObjectID(sym), sizeof(SymbolID), 0); }); }; snap.beginSection(HeapSnapshot::Section::Nodes); rootScan(); // Add all primitive values as nodes if they weren't added before. // This must be done as a step before adding any edges to these nodes. // In particular, custom edge adders might try to add edges to primitives that // haven't been recorded yet. // The acceptor is recording some state between objects, so define it outside // the loop. PrimitiveNodeAcceptor primitiveAcceptor( getPointerBase(), snap, getIDTracker()); SlotVisitorWithNames<PrimitiveNodeAcceptor> primitiveVisitor{ primitiveAcceptor}; // Add a node for each object in the heap. const auto snapshotForObject = [&snap, &primitiveVisitor, gc, this](GCCell *cell) { auto &allocationLocationTracker = gc->getAllocationLocationTracker(); // First add primitive nodes. markCellWithNames(primitiveVisitor, cell); EdgeAddingAcceptor acceptor(*gc, snap); SlotVisitorWithNames<EdgeAddingAcceptor> visitor(acceptor); // Allow nodes to add extra nodes not in the JS heap. cell->getVT()->snapshotMetaData.addNodes(cell, gc, snap); snap.beginNode(); // Add all internal edges first. markCellWithNames(visitor, cell); // Allow nodes to add custom edges not represented by metadata. cell->getVT()->snapshotMetaData.addEdges(cell, gc, snap); auto stackTracesTreeNode = allocationLocationTracker.getStackTracesTreeNodeForAlloc( gc->getObjectID(cell)); snap.endNode( cell->getVT()->snapshotMetaData.nodeType(), cell->getVT()->snapshotMetaData.nameForNode(cell, gc), gc->getObjectID(cell), cell->getAllocatedSize(), stackTracesTreeNode ? stackTracesTreeNode->id : 0); }; gc->forAllObjs(snapshotForObject); // Write the singleton number nodes into the snapshot. primitiveAcceptor.writeAllNodes(); snap.endSection(HeapSnapshot::Section::Nodes); snap.beginSection(HeapSnapshot::Section::Edges); rootScan(); // No need to run the primitive scan again, as it only adds nodes, not edges. // Add edges between objects in the heap. gc->forAllObjs(snapshotForObject); snap.endSection(HeapSnapshot::Section::Edges); snap.emitAllocationTraceInfo(); snap.beginSection(HeapSnapshot::Section::Samples); for (const auto &fragment : getAllocationLocationTracker().fragments()) { json.emitValues( {static_cast<uint64_t>(fragment.timestamp_.count()), static_cast<uint64_t>(fragment.lastSeenObjectID_)}); } snap.endSection(HeapSnapshot::Section::Samples); snap.beginSection(HeapSnapshot::Section::Locations); gc->forAllObjs([&snap, gc](GCCell *cell) { cell->getVT()->snapshotMetaData.addLocations(cell, gc, snap); }); snap.endSection(HeapSnapshot::Section::Locations); } void GCBase::snapshotAddGCNativeNodes(HeapSnapshot &snap) { snap.beginNode(); snap.endNode( HeapSnapshot::NodeType::Native, "std::deque<WeakRefSlot>", IDTracker::reserved(IDTracker::ReservedObjectID::WeakRefSlotStorage), weakSlots_.size() * sizeof(decltype(weakSlots_)::value_type), 0); } void GCBase::snapshotAddGCNativeEdges(HeapSnapshot &snap) { snap.addNamedEdge( HeapSnapshot::EdgeType::Internal, "weakRefSlots", IDTracker::reserved(IDTracker::ReservedObjectID::WeakRefSlotStorage)); } void GCBase::enableHeapProfiler( std::function<void( uint64_t, std::chrono::microseconds, std::vector<GCBase::AllocationLocationTracker::HeapStatsUpdate>)> fragmentCallback) { getAllocationLocationTracker().enable(std::move(fragmentCallback)); } void GCBase::disableHeapProfiler() { getAllocationLocationTracker().disable(); } void GCBase::checkTripwire(size_t dataSize) { if (LLVM_LIKELY(!tripwireCallback_) || LLVM_LIKELY(dataSize < tripwireLimit_) || tripwireCalled_) { return; } class Ctx : public GCTripwireContext { public: Ctx(GCBase *gc) : gc_(gc) {} std::error_code createSnapshotToFile(const std::string &path) override { return gc_->createSnapshotToFile(path); } std::error_code createSnapshot(std::ostream &os) override { llvh::raw_os_ostream ros(os); gc_->createSnapshot(ros); return std::error_code{}; } private: GCBase *gc_; } ctx(this); tripwireCalled_ = true; tripwireCallback_(ctx); } void GCBase::printAllCollectedStats(llvh::raw_ostream &os) { if (!recordGcStats_) return; dump(os); os << "GC stats:\n"; JSONEmitter json{os, /*pretty*/ true}; json.openDict(); printStats(json); json.closeDict(); os << "\n"; } void GCBase::getHeapInfo(HeapInfo &info) { info.numCollections = cumStats_.numCollections; } void GCBase::getHeapInfoWithMallocSize(HeapInfo &info) { // Assign to overwrite anything previously in the heap info. // A deque doesn't have a capacity, so the size is the lower bound. info.mallocSizeEstimate = weakSlots_.size() * sizeof(decltype(weakSlots_)::value_type); } #ifndef NDEBUG void GCBase::getDebugHeapInfo(DebugHeapInfo &info) { recordNumAllocatedObjects(); info.numAllocatedObjects = numAllocatedObjects_; info.numReachableObjects = numReachableObjects_; info.numCollectedObjects = numCollectedObjects_; info.numFinalizedObjects = numFinalizedObjects_; info.numMarkedSymbols = numMarkedSymbols_; info.numHiddenClasses = numHiddenClasses_; info.numLeafHiddenClasses = numLeafHiddenClasses_; } size_t GCBase::countUsedWeakRefs() const { size_t count = 0; for (auto &slot : weakSlots_) { if (slot.state() != WeakSlotState::Free) { ++count; } } return count; } #endif #ifndef NDEBUG void GCBase::DebugHeapInfo::assertInvariants() const { // The number of allocated objects at any time is at least the number // found reachable in the last collection. assert(numAllocatedObjects >= numReachableObjects); // The number of objects finalized in the last collection is at most the // number of objects collected. assert(numCollectedObjects >= numFinalizedObjects); } #endif void GCBase::dump(llvh::raw_ostream &, bool) { /* nop */ } void GCBase::printStats(JSONEmitter &json) { json.emitKeyValue("type", "hermes"); json.emitKeyValue("version", 0); gcCallbacks_->printRuntimeGCStats(json); std::chrono::duration<double> elapsedTime = std::chrono::steady_clock::now() - execStartTime_; auto elapsedCPUSeconds = std::chrono::duration_cast<std::chrono::duration<double>>( oscompat::thread_cpu_time()) .count() - std::chrono::duration_cast<std::chrono::duration<double>>( execStartCPUTime_) .count(); HeapInfo info; getHeapInfoWithMallocSize(info); getHeapInfo(info); #ifndef NDEBUG DebugHeapInfo debugInfo; getDebugHeapInfo(debugInfo); #endif json.emitKey("heapInfo"); json.openDict(); #ifndef NDEBUG json.emitKeyValue("Num allocated cells", debugInfo.numAllocatedObjects); json.emitKeyValue("Num reachable cells", debugInfo.numReachableObjects); json.emitKeyValue("Num collected cells", debugInfo.numCollectedObjects); json.emitKeyValue("Num finalized cells", debugInfo.numFinalizedObjects); json.emitKeyValue("Num marked symbols", debugInfo.numMarkedSymbols); json.emitKeyValue("Num hidden classes", debugInfo.numHiddenClasses); json.emitKeyValue("Num leaf classes", debugInfo.numLeafHiddenClasses); json.emitKeyValue("Num weak references", ((GC *)this)->countUsedWeakRefs()); #endif json.emitKeyValue("Peak RSS", oscompat::peak_rss()); json.emitKeyValue("Current RSS", oscompat::current_rss()); json.emitKeyValue("Current Dirty", oscompat::current_private_dirty()); json.emitKeyValue("Heap size", info.heapSize); json.emitKeyValue("Allocated bytes", info.allocatedBytes); json.emitKeyValue("Num collections", info.numCollections); json.emitKeyValue("Malloc size", info.mallocSizeEstimate); json.closeDict(); long vol = -1; long invol = -1; if (oscompat::num_context_switches(vol, invol)) { vol -= startNumVoluntaryContextSwitches_; invol -= startNumInvoluntaryContextSwitches_; } json.emitKey("general"); json.openDict(); json.emitKeyValue("numCollections", cumStats_.numCollections); json.emitKeyValue("totalTime", elapsedTime.count()); json.emitKeyValue("totalCPUTime", elapsedCPUSeconds); json.emitKeyValue("totalGCTime", formatSecs(cumStats_.gcWallTime.sum()).secs); json.emitKeyValue("volCtxSwitch", vol); json.emitKeyValue("involCtxSwitch", invol); json.emitKeyValue( "avgGCPause", formatSecs(cumStats_.gcWallTime.average()).secs); json.emitKeyValue("maxGCPause", formatSecs(cumStats_.gcWallTime.max()).secs); json.emitKeyValue( "totalGCCPUTime", formatSecs(cumStats_.gcCPUTime.sum()).secs); json.emitKeyValue( "avgGCCPUPause", formatSecs(cumStats_.gcCPUTime.average()).secs); json.emitKeyValue( "maxGCCPUPause", formatSecs(cumStats_.gcCPUTime.max()).secs); json.emitKeyValue("finalHeapSize", formatSize(cumStats_.finalHeapSize).bytes); json.emitKeyValue( "peakAllocatedBytes", formatSize(getPeakAllocatedBytes()).bytes); json.emitKeyValue("peakLiveAfterGC", formatSize(getPeakLiveAfterGC()).bytes); json.emitKeyValue( "totalAllocatedBytes", formatSize(info.totalAllocatedBytes).bytes); json.closeDict(); json.emitKey("collections"); json.openArray(); for (const auto &event : analyticsEvents_) { json.openDict(); json.emitKeyValue("runtimeDescription", event.runtimeDescription); json.emitKeyValue("gcKind", event.gcKind); json.emitKeyValue("collectionType", event.collectionType); json.emitKeyValue("cause", event.cause); json.emitKeyValue("duration", event.duration.count()); json.emitKeyValue("cpuDuration", event.cpuDuration.count()); json.emitKeyValue("preAllocated", event.preAllocated); json.emitKeyValue("preSize", event.preSize); json.emitKeyValue("postAllocated", event.postAllocated); json.emitKeyValue("postSize", event.postSize); json.emitKeyValue("survivalRatio", event.survivalRatio); json.closeDict(); } json.closeArray(); } void GCBase::recordGCStats( const GCAnalyticsEvent &event, CumulativeHeapStats *stats) { stats->gcWallTime.record( std::chrono::duration<double>(event.duration).count()); stats->gcCPUTime.record( std::chrono::duration<double>(event.cpuDuration).count()); stats->finalHeapSize = event.postSize; stats->usedBefore.record(event.preAllocated); stats->usedAfter.record(event.postAllocated); stats->numCollections++; } void GCBase::recordGCStats(const GCAnalyticsEvent &event) { if (analyticsCallback_) { analyticsCallback_(event); } if (recordGcStats_) { analyticsEvents_.push_back(event); } recordGCStats(event, &cumStats_); } void GCBase::oom(std::error_code reason) { #ifdef HERMESVM_EXCEPTION_ON_OOM HeapInfo heapInfo; getHeapInfo(heapInfo); char detailBuffer[400]; snprintf( detailBuffer, sizeof(detailBuffer), "Javascript heap memory exhausted: heap size = %d, allocated = %d.", heapInfo.heapSize, heapInfo.allocatedBytes); // No need to run finalizeAll, the exception will propagate and eventually run // ~Runtime. throw JSOutOfMemoryError( std::string(detailBuffer) + "\ncall stack:\n" + gcCallbacks_->getCallStackNoAlloc()); #else oomDetail(reason); hermes_fatal((llvh::Twine("OOM: ") + convert_error_to_message(reason)).str()); #endif } void GCBase::oomDetail(std::error_code reason) { HeapInfo heapInfo; getHeapInfo(heapInfo); // Could use a stringstream here, but want to avoid dynamic allocation. char detailBuffer[400]; snprintf( detailBuffer, sizeof(detailBuffer), "[%.20s] reason = %.150s (%d from category: %.50s), numCollections = %d, heapSize = %d, allocated = %d, va = %" PRIu64, name_.c_str(), reason.message().c_str(), reason.value(), reason.category().name(), heapInfo.numCollections, heapInfo.heapSize, heapInfo.allocatedBytes, heapInfo.va); hermesLog("HermesGC", "OOM: %s.", detailBuffer); // Record the OOM custom data with the crash manager. crashMgr_->setCustomData("HermesGCOOMDetailBasic", detailBuffer); } #ifndef NDEBUG /*static*/ bool GCBase::isMostRecentCellInFinalizerVector( const std::vector<GCCell *> &finalizables, const GCCell *cell) { return !finalizables.empty() && finalizables.back() == cell; } #endif #ifdef HERMESVM_SANITIZE_HANDLES bool GCBase::shouldSanitizeHandles() { static std::uniform_real_distribution<> dist(0.0, 1.0); return dist(randomEngine_) < sanitizeRate_ #ifdef HERMESVM_SERIALIZE && !deserializeInProgress_ #endif ; } #endif /*static*/ std::vector<detail::WeakRefKey *> GCBase::buildKeyList( GC *gc, JSWeakMap *weakMap) { std::vector<detail::WeakRefKey *> res; for (auto iter = weakMap->keys_begin(), end = weakMap->keys_end(); iter != end; iter++) { if (iter->getObject(gc)) { res.push_back(&(*iter)); } } return res; } WeakRefMutex &GCBase::weakRefMutex() { return weakRefMutex_; } /*static*/ double GCBase::clockDiffSeconds(TimePoint start, TimePoint end) { std::chrono::duration<double> elapsed = (end - start); return elapsed.count(); } /*static*/ double GCBase::clockDiffSeconds( std::chrono::microseconds start, std::chrono::microseconds end) { std::chrono::duration<double> elapsed = (end - start); return elapsed.count(); } llvh::raw_ostream &operator<<( llvh::raw_ostream &os, const DurationFormatObj &dfo) { if (dfo.secs >= 1.0) { os << format("%5.3f", dfo.secs) << " s"; } else if (dfo.secs >= 0.001) { os << format("%5.3f", dfo.secs * 1000.0) << " ms"; } else { os << format("%5.3f", dfo.secs * 1000000.0) << " us"; } return os; } llvh::raw_ostream &operator<<(llvh::raw_ostream &os, const SizeFormatObj &sfo) { double dblsize = static_cast<double>(sfo.bytes); if (sfo.bytes >= (1024 * 1024 * 1024)) { double gbs = dblsize / (1024.0 * 1024.0 * 1024.0); os << format("%0.3f GiB", gbs); } else if (sfo.bytes >= (1024 * 1024)) { double mbs = dblsize / (1024.0 * 1024.0); os << format("%0.3f MiB", mbs); } else if (sfo.bytes >= 1024) { double kbs = dblsize / 1024.0; os << format("%0.3f KiB", kbs); } else { os << sfo.bytes << " B"; } return os; } GCBase::GCCallbacks::~GCCallbacks() {} GCBase::IDTracker::IDTracker() { assert(lastID_ % 2 == 1 && "First JS object ID isn't odd"); } void GCBase::IDTracker::moveObject( BasedPointer oldLocation, BasedPointer newLocation) { if (oldLocation == newLocation) { // Don't need to do anything if the object isn't moving anywhere. This can // happen in old generations where it is compacted to the same location. return; } std::lock_guard<Mutex> lk{mtx_}; auto old = objectIDMap_.find(oldLocation.getRawValue()); if (old == objectIDMap_.end()) { // Avoid making new keys for objects that don't need to be tracked. return; } const auto oldID = old->second; assert( objectIDMap_.count(newLocation.getRawValue()) == 0 && "Moving to a location that is already tracked"); // Have to erase first, because any other access can invalidate the iterator. objectIDMap_.erase(old); objectIDMap_[newLocation.getRawValue()] = oldID; } #ifdef HERMESVM_SERIALIZE void GCBase::AllocationLocationTracker::serialize(Serializer &s) const { if (enabled_) { hermes_fatal( "Serialization not supported when AllocationLocationTracker enabled"); } } void GCBase::AllocationLocationTracker::deserialize(Deserializer &d) { if (enabled_) { hermes_fatal( "Deserialization not supported when AllocationLocationTracker enabled"); } } void GCBase::IDTracker::serialize(Serializer &s) const { s.writeInt<HeapSnapshot::NodeID>(lastID_); s.writeInt<size_t>(objectIDMap_.size()); for (auto it = objectIDMap_.begin(); it != objectIDMap_.end(); it++) { s.writeRelocation( s.getRuntime()->basedToPointerNonNull(BasedPointer{it->first})); s.writeInt<HeapSnapshot::NodeID>(it->second); } } void GCBase::IDTracker::deserialize(Deserializer &d) { lastID_ = d.readInt<HeapSnapshot::NodeID>(); size_t size = d.readInt<size_t>(); for (size_t i = 0; i < size; i++) { // Heap must have been deserialized before this function. All deserialized // pointer must be non-null at this time. GCPointer<GCCell> ptr{nullptr}; d.readRelocation(&ptr, RelocationKind::GCPointer); auto res = objectIDMap_ .try_emplace( ptr.getStorageType().getRawValue(), d.readInt<HeapSnapshot::NodeID>()) .second; (void)res; assert(res && "Shouldn't fail to insert during deserialization"); } } #endif llvh::SmallVector<HeapSnapshot::NodeID, 1> &GCBase::IDTracker::getExtraNativeIDs(HeapSnapshot::NodeID node) { std::lock_guard<Mutex> lk{mtx_}; // The operator[] will default construct the vector to be empty if it doesn't // exist. return extraNativeIDs_[node]; } HeapSnapshot::NodeID GCBase::IDTracker::getNumberID(double num) { std::lock_guard<Mutex> lk{mtx_}; auto &numberRef = numberIDMap_[num]; // If the entry didn't exist, the value was initialized to 0. if (numberRef != 0) { return numberRef; } // Else, it is a number that hasn't been seen before. return numberRef = nextNumberID(); } bool GCBase::IDTracker::hasNativeIDs() { std::lock_guard<Mutex> lk{mtx_}; return !nativeIDMap_.empty(); } void GCBase::AllocationLocationTracker::enable( std::function< void(uint64_t, std::chrono::microseconds, std::vector<HeapStatsUpdate>)> callback) { assert(!enabled_ && "Shouldn't enable twice"); enabled_ = true; std::lock_guard<Mutex> lk{mtx_}; GC *gc = static_cast<GC *>(gc_); // For correct visualization of the allocation timeline, it's necessary that // objects in the heap snapshot that existed before sampling was enabled have // numerically lower IDs than those allocated during sampling. We ensure this // by assigning IDs to everything here. uint64_t numObjects = 0; uint64_t numBytes = 0; gc->forAllObjs([gc, &numObjects, &numBytes](GCCell *cell) { numObjects++; numBytes += cell->getAllocatedSize(); gc->getObjectID(cell); }); fragmentCallback_ = std::move(callback); startTime_ = std::chrono::steady_clock::now(); fragments_.clear(); // The first fragment has all objects that were live before the profiler was // enabled. // The ID and timestamp will be filled out via flushCallback. fragments_.emplace_back(Fragment{ IDTracker::kInvalidNode, std::chrono::microseconds(), numObjects, numBytes, // Say the fragment is touched here so it is written out // automatically by flushCallback. true}); // Immediately flush the first fragment. flushCallback(); } void GCBase::AllocationLocationTracker::disable() { std::lock_guard<Mutex> lk{mtx_}; flushCallback(); enabled_ = false; fragmentCallback_ = nullptr; } void GCBase::AllocationLocationTracker::newAlloc(const void *ptr, uint32_t sz) { // Note we always get the current IP even if allocation tracking is not // enabled as it allows us to assert this feature works across many tests. // Note it's not very slow, it's slower than the non-virtual version // in Runtime though. const auto *ip = gc_->gcCallbacks_->getCurrentIPSlow(); if (!enabled_) { return; } std::lock_guard<Mutex> lk{mtx_}; // This is stateful and causes the object to have an ID assigned. const auto id = gc_->getObjectID(ptr); HERMES_SLOW_ASSERT( &findFragmentForID(id) == &fragments_.back() && "Should only ever be allocating into the newest fragment"); Fragment &lastFrag = fragments_.back(); assert( lastFrag.lastSeenObjectID_ == IDTracker::kInvalidNode && "Last fragment should not have an ID assigned yet"); lastFrag.numObjects_++; lastFrag.numBytes_ += sz; lastFrag.touchedSinceLastFlush_ = true; if (lastFrag.numBytes_ >= kFlushThreshold) { flushCallback(); } if (auto node = gc_->gcCallbacks_->getCurrentStackTracesTreeNode(ip)) { auto itAndDidInsert = stackMap_.try_emplace(id, node); assert(itAndDidInsert.second && "Failed to create a new node"); (void)itAndDidInsert; } } void GCBase::AllocationLocationTracker::updateSize( const void *ptr, uint32_t oldSize, uint32_t newSize) { int32_t delta = static_cast<int32_t>(newSize) - static_cast<int32_t>(oldSize); if (!delta || !enabled_) { // Nothing to update. return; } std::lock_guard<Mutex> lk{mtx_}; const auto id = gc_->getObjectIDMustExist(ptr); Fragment &frag = findFragmentForID(id); frag.numBytes_ += delta; frag.touchedSinceLastFlush_ = true; } void GCBase::AllocationLocationTracker::freeAlloc( const void *ptr, uint32_t sz) { if (!enabled_) { // Fragments won't exist if the heap profiler isn't enabled. return; } // Hold a lock during freeAlloc because concurrent Hades might be creating an // alloc (newAlloc) at the same time. std::lock_guard<Mutex> lk{mtx_}; // The ID must exist here since the memory profiler guarantees everything has // an ID (it does a heap pass at the beginning to assign them all). const auto id = gc_->getObjectIDMustExist(ptr); stackMap_.erase(id); Fragment &frag = findFragmentForID(id); assert( frag.numObjects_ >= 1 && "Num objects decremented too much for fragment"); frag.numObjects_--; assert(frag.numBytes_ >= sz && "Num bytes decremented too much for fragment"); frag.numBytes_ -= sz; frag.touchedSinceLastFlush_ = true; } GCBase::AllocationLocationTracker::Fragment & GCBase::AllocationLocationTracker::findFragmentForID(HeapSnapshot::NodeID id) { assert(fragments_.size() >= 1 && "Must have at least one fragment available"); for (auto it = fragments_.begin(); it != fragments_.end() - 1; ++it) { if (it->lastSeenObjectID_ >= id) { return *it; } } // Since no previous fragments matched, it must be the last fragment. return fragments_.back(); } void GCBase::AllocationLocationTracker::flushCallback() { Fragment &lastFrag = fragments_.back(); const auto lastID = gc_->getIDTracker().lastID(); const auto duration = std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::steady_clock::now() - startTime_); assert( lastFrag.lastSeenObjectID_ == IDTracker::kInvalidNode && "Last fragment should not have an ID assigned yet"); // In case a flush happens without any allocations occurring, don't add a new // fragment. if (lastFrag.touchedSinceLastFlush_) { lastFrag.lastSeenObjectID_ = lastID; lastFrag.timestamp_ = duration; // Place an empty fragment at the end, for any new allocs. fragments_.emplace_back(Fragment{ IDTracker::kInvalidNode, std::chrono::microseconds(), 0, 0, false}); } if (fragmentCallback_) { std::vector<HeapStatsUpdate> updatedFragments; // Don't include the last fragment, which is newly created (or has no // objects in it). for (size_t i = 0; i < fragments_.size() - 1; ++i) { auto &fragment = fragments_[i]; if (fragment.touchedSinceLastFlush_) { updatedFragments.emplace_back( i, fragment.numObjects_, fragment.numBytes_); fragment.touchedSinceLastFlush_ = false; } } fragmentCallback_(lastID, duration, std::move(updatedFragments)); } } llvh::Optional<HeapSnapshot::NodeID> GCBase::getSnapshotID(HermesValue val) { if (val.isPointer() && val.getPointer()) { // Make nullptr HermesValue look like a JS null. // This should be rare, but is occasionally used by some parts of the VM. return val.getPointer() ? getObjectID(val.getPointer()) : IDTracker::reserved(IDTracker::ReservedObjectID::Null); } else if (val.isNumber()) { return idTracker_.getNumberID(val.getNumber()); } else if (val.isSymbol() && val.getSymbol().isValid()) { return idTracker_.getObjectID(val.getSymbol()); } else if (val.isUndefined()) { return IDTracker::reserved(IDTracker::ReservedObjectID::Undefined); } else if (val.isNull()) { return static_cast<HeapSnapshot::NodeID>( IDTracker::reserved(IDTracker::ReservedObjectID::Null)); } else if (val.isBool()) { return static_cast<HeapSnapshot::NodeID>( val.getBool() ? IDTracker::reserved(IDTracker::ReservedObjectID::True) : IDTracker::reserved(IDTracker::ReservedObjectID::False)); } else { return llvh::None; } } } // namespace vm } // namespace hermes
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
e639e2748a2a1398ce2aa59cf27ddb763dfe5cdd
1e7349202ff77ca285db35103dc40653e11235ba
/resample.cpp
8c38921c3d29e9f97bc65b6e27556d132c868652
[]
no_license
busygin/morlet
1247f799421dbfd42d6924e0985e71d41e6ceec0
564c1ed0047dad81c2af1b9e42ae2845eeed21cc
refs/heads/master
2021-01-17T14:30:43.856421
2016-02-12T17:20:25
2016-02-12T17:20:25
49,468,315
0
0
null
null
null
null
UTF-8
C++
false
false
509
cpp
// // Created by busygin on 1/12/16. // #include "resample.h" void Resampler::run(double* signal, double* downsampled_signal) { memcpy(signal_, signal, signal_len_*sizeof(double)); fftw_execute(plan_for_signal); for(size_t i=resample_len_/2+1; i<resample_len_; ++i) { fft[i][0] = fft[resample_len_-i][0]; fft[i][1] = -fft[resample_len_-i][1]; } fftw_execute(plan_for_reduced_fft); for(size_t i=0; i<resample_len_; ++i) downsampled_signal[i] = downsampled_signal_[i][0]; }
[ "busygin@gmail.com" ]
busygin@gmail.com
1323446a56f4a2ccf0bcf2f61c71a8fdcc59be15
069d4d60ed3bded70ad32e8b19371c453efb6655
/src/ppl/nn/engines/cuda/pmx/utils.h
92caf513b756f74c750adb8455eb57343672ca1d
[ "Apache-2.0" ]
permissive
openppl-public/ppl.nn
5f3e4f0c1a10bd2ba267fdc27ff533fb9074f1ed
99a2fdf6e4879862da5cac0167af5ea968eaf039
refs/heads/master
2023-08-17T07:31:50.494617
2023-08-16T11:24:54
2023-08-16T15:05:11
381,712,622
1,143
224
Apache-2.0
2023-09-08T16:33:08
2021-06-30T13:32:17
C++
UTF-8
C++
false
false
8,352
h
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #ifndef _ST_HPC_PPL_NN_ENGINES_CUDA_PMX_UTILS_H_ #define _ST_HPC_PPL_NN_ENGINES_CUDA_PMX_UTILS_H_ #include "ppl/nn/models/pmx/utils.h" #include "ppl/nn/engines/cuda/params/conv_extra_param.h" #include "ppl/nn/engines/cuda/params/gemm_extra_param.h" #include "ppl/nn/engines/cuda/params/convtranspose_extra_param.h" #include "ppl/nn/engines/cuda/pmx/generated/cuda_op_params_generated.h" #include "ppl/nn/models/pmx/oputils/onnx/conv.h" using namespace ppl::nn; using namespace ppl::nn::cuda; namespace ppl { namespace nn { namespace pmx { namespace cuda { template <typename T> static RetCode SerializePrivateData(const pmx::SerializationContext& ctx, const T& extra_param, const std::string& ptx_code, flatbuffers::FlatBufferBuilder* builder) { auto& tiles = extra_param.algo_info.tiles; vector<int32_t> tiles_vec{tiles.m_cta, tiles.n_cta, tiles.k_cta, tiles.m_warp, tiles.n_warp, tiles.k_per_step, tiles.k_per_set, tiles.flt_size, tiles.flt_pad_size, tiles.cta_size_in_thd, tiles.smem_size, tiles.buf}; auto fb_algo_info = pmx::cuda::CreateConvAlgoInfoDirect(*builder, extra_param.algo_info.algo_type.c_str(), extra_param.algo_info.algo_name.c_str(), extra_param.algo_info.conv_type.c_str(), extra_param.algo_info.mma_shape.c_str(), &tiles_vec, extra_param.algo_info.kid, extra_param.algo_info.splitk, extra_param.algo_info.splitf, extra_param.is_initializer_weight, extra_param.bias_term); std::vector<flatbuffers::Offset<flatbuffers::String>> fb_types; std::vector<pmx::cuda::FuseAttrs> fb_attrs; for (uint32_t i = 0; i < extra_param.fuse_info.types.size(); ++i) { auto type = extra_param.fuse_info.types[i]; auto fb_type = builder->CreateString(type); fb_types.push_back(fb_type); pmx::cuda::FuseAttrs fb_attr; if (type == "Clip") { auto attr = extra_param.fuse_info.fuse_attrs[i]; auto clip_attr = (CudaClipParam*)attr; fb_attr = pmx::cuda::FuseAttrs(clip_attr->min_value, clip_attr->max_value, 0); } else if (type == "LeakyRelu") { auto attr = extra_param.fuse_info.fuse_attrs[i]; auto leaky_attr = (LeakyReluParam*)attr; fb_attr = pmx::cuda::FuseAttrs(0, 0, leaky_attr->alpha); } else { fb_attr = pmx::cuda::FuseAttrs(0, 0, 0); } fb_attrs.push_back(fb_attr); } // edge_id has reset in sequence edgeid_t fb_concat_edge_it = -1; if (extra_param.fuse_info.concat_edge_id != -1) { fb_concat_edge_it = ctx.eid2seq[extra_param.fuse_info.concat_edge_id]; } auto fb_fuse_info = pmx::cuda::CreateConvFusionInfoDirect(*builder, &fb_types, &extra_param.fuse_info.input_inds, &fb_attrs, extra_param.fuse_info.channel_size, extra_param.fuse_info.channel_offset, fb_concat_edge_it); auto fb_code = builder->CreateVector((const uint8_t*)ptx_code.data(), ptx_code.size()); auto fb_conv_param = pmx::cuda::CreateConvParam(*builder, fb_algo_info, fb_fuse_info, fb_code); auto fb_op_param = pmx::cuda::CreateOpParam(*builder, pmx::cuda::OpParamType_ConvParam, fb_conv_param.Union()); pmx::cuda::FinishOpParamBuffer(*builder, fb_op_param); return RC_SUCCESS; } template <typename T> static RetCode DeserializePrivateData(const void* fb_param, uint64_t size, std::string& ptx_code, T* extra_param) { auto fb_op_param = pmx::cuda::GetOpParam(fb_param); auto fb_conv_param = fb_op_param->value_as_ConvParam(); auto fb_algo_info = fb_conv_param->algo_info(); extra_param->algo_info.algo_type = fb_algo_info->algo_type()->c_str(); extra_param->algo_info.algo_name = fb_algo_info->algo_name()->c_str(); extra_param->algo_info.conv_type = fb_algo_info->conv_type()->c_str(); extra_param->algo_info.mma_shape = fb_algo_info->mma_shape()->c_str(); extra_param->algo_info.kid = fb_algo_info->kid(); extra_param->algo_info.splitk = fb_algo_info->splitk(); extra_param->algo_info.splitf = fb_algo_info->splitf(); extra_param->is_initializer_weight = fb_algo_info->is_initializer_weight(); extra_param->bias_term = fb_algo_info->has_bias(); auto& tiles = extra_param->algo_info.tiles; std::vector<int> tiles_vec; ppl::nn::pmx::utils::Fbvec2Stdvec(fb_algo_info->tiles(), &tiles_vec); tiles.m_cta = tiles_vec[0]; tiles.n_cta = tiles_vec[1]; tiles.k_cta = tiles_vec[2]; tiles.m_warp = tiles_vec[3]; tiles.n_warp = tiles_vec[4]; tiles.k_per_step = tiles_vec[5]; tiles.k_per_set = tiles_vec[6]; tiles.flt_size = tiles_vec[7]; tiles.flt_pad_size = tiles_vec[8]; tiles.cta_size_in_thd = tiles_vec[9]; tiles.smem_size = tiles_vec[10]; tiles.buf = tiles_vec[11]; auto fb_fuse_info = fb_conv_param->fuse_info(); auto fb_types = fb_fuse_info->types(); auto fb_input_inds = fb_fuse_info->input_inds(); auto fb_fuse_attrs = fb_fuse_info->fuse_attrs(); extra_param->fuse_info.types.clear(); extra_param->fuse_info.input_inds.clear(); extra_param->fuse_info.fuse_attrs.clear(); for (uint32_t i = 0; i < fb_types->size(); ++i) { std::string str = fb_types->Get(i)->str(); extra_param->fuse_info.types.push_back(str); auto ind = fb_input_inds->Get(i); extra_param->fuse_info.input_inds.push_back(ind); auto attr = fb_fuse_attrs->Get(i); if (str == "Clip") { CudaClipParam clip; clip.max_value = attr->clip_max(); clip.min_value = attr->clip_min(); extra_param->fuse_info.fuse_attrs.push_back(std::move(&clip)); } else if (str == "LeakyRelu") { LeakyReluParam leaky; leaky.alpha = attr->leaky_alpha(); extra_param->fuse_info.fuse_attrs.push_back(std::move(&leaky)); } else { extra_param->fuse_info.fuse_attrs.push_back(nullptr); } } extra_param->fuse_info.channel_offset = fb_fuse_info->channel_offset(); extra_param->fuse_info.channel_size = fb_fuse_info->channel_size(); extra_param->fuse_info.concat_edge_id = fb_fuse_info->concat_edge_id(); ptx_code.assign((const char*)fb_conv_param->gene_code()->data(), fb_conv_param->gene_code()->size()); return RC_SUCCESS; } }}}} // namespace ppl::nn::pmx::cuda #endif
[ "856454+ouonline@users.noreply.github.com" ]
856454+ouonline@users.noreply.github.com
a30b61ac1ae2cb531e29bcb1d7ec17949f2d3cab
b9d45717223d242544e3a5c83ba0a9377682743f
/Multiplexer.cpp
4ddb7700fb2d1a151d641bf13001c5a81d51fa94
[]
no_license
chenbk85/simpleton
68e7bd160c5b78d522552158bf6e042cbc88597d
f8b87a89dcaa75cbdd69d13db04e7d9d606ff108
refs/heads/master
2020-12-26T12:04:29.299938
2016-01-05T06:17:49
2016-01-05T06:17:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,011
cpp
// // Created by lyc-fedora on 15-4-27. // #include "Multiplexer.h" #include "Exceptions.h" using namespace simpleton; Multiplexer::Multiplexer() :_epollfd(-1),_eventList(8) //初始构造时产生8个空event结构体 { if ((_epollfd = ::epoll_create(5)) == -1) { int saveError = errno; throw exceptions::ApiExecError("epoll_create",saveError); } } Multiplexer::~Multiplexer() { if(_epollfd >= 0) ::close(_epollfd); } void Multiplexer::UpdateDispathcer(Dispatcher* dispatcher) { int sockfd = dispatcher->GetFd(); struct epoll_event event; event.data.fd = sockfd; event.events = dispatcher->GetEvents(); //判断是添加还是更新 if(_dispatcherMap.find(sockfd) == _dispatcherMap.end()) { if(::epoll_ctl(_epollfd, EPOLL_CTL_ADD, sockfd, &event) < 0) { int saveError = errno; throw exceptions::ApiExecError("epoll_ctl::ADD",saveError); } } else { if(::epoll_ctl(_epollfd, EPOLL_CTL_MOD, sockfd, &event) < 0) { int saveError = errno; throw exceptions::ApiExecError("epoll_ctl::MOD",saveError); } } //利用map特性直接使用下标运算符 _dispatcherMap[sockfd] = dispatcher; } void Multiplexer::DeleteDispatcher(Dispatcher* dispatcher) { int sockfd = dispatcher->GetFd(); struct epoll_event event; event.data.fd = sockfd; event.events = dispatcher->GetEvents(); //先查找,存在再进行下一步操作 auto iter = _dispatcherMap.find(sockfd); if(iter != _dispatcherMap.end()) { _dispatcherMap.erase(iter); if(::epoll_ctl(_epollfd,EPOLL_CTL_DEL,sockfd,&event) < 0) { int saveError = errno; throw exceptions::ApiExecError("epoll_ctl::DEL",saveError); } } } void Multiplexer::Wait(int timeout,vector<Dispatcher*>& result) { int eventnum = ::epoll_wait(_epollfd,_eventList.data(), static_cast<int>(_eventList.size()),timeout); //处理得到的各种发生的事件 if(eventnum > 0) { //首先获取就绪的事件表并填入分派器列表 for(int i = 0;i < eventnum;i++) { int fd = _eventList[i].data.fd; auto iter = _dispatcherMap.find(fd); //如果没找到,只有上帝知道为啥了 if (iter == _dispatcherMap.end()) throw exceptions::InternalLogicError("Multiplexer::Wait"); else { (iter->second)->SetReturnEvents(_eventList[i].events); result.push_back(iter->second); } } //动态改变内部eventList大小 if (static_cast<unsigned int>(eventnum) >= _eventList.size()) _eventList.resize(_eventList.size() * 2); } else if(eventnum == 0) { //timeout ??? } else { int saveError = errno; throw exceptions::ApiExecError("epoll_wait",saveError); } }
[ "lycmail58@163.com" ]
lycmail58@163.com
570b2707c9d5f6d0d7861851235733bb88b7cc63
b1e4a4c5841b8ae47ab4e23ebe2558fc0bb6f20e
/implementation/game/Player.cpp
041000295c5e3eef3d9ec28960505367412b5fc1
[]
no_license
flaithbheartaigh/symbian-4x-space-game
9c487ffd0efdedbe2fee56459c63db45806fc4c1
ba9f360309c4b5c2c2194c98fc9bd9e0b183dd41
refs/heads/master
2021-01-10T11:29:48.970470
2012-10-31T02:01:45
2012-10-31T02:01:45
50,126,275
0
0
null
null
null
null
UTF-8
C++
false
false
8,714
cpp
// Symbian 4X Space Game // // Copyright (C) 2011 Patrick Pelletier // // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by the // Free Software Foundation, either version 3 of the License, or any later // version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General // Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program. See <http://www.opensource.org/licenses/gpl-3.0.html> #include "Player.h" #include "AI.h" #include "Sector.h" #include "StarSystem.h" #include "UniverseVisitor.h" #include "StatsVisitor.h" #include "Planet.h" #include "Ship.h" #include "ShipConfig.h" #include <algorithm> using namespace Game; Player::Current::Subscriber::~Subscriber() { unsubscribe(); } Player::Current::Subscriber::Subscriber() { Player::Current::instance().subscribe(this); } void Player::Current::Subscriber::selectedSectorChanged(Sector * sector) { } void Player::Current::Subscriber::selectedSectorReselected(Sector * sector) { } void Player::Current::Subscriber::unsubscribe() { Player::Current::instance().unsubscribe(this); } Player::Current * Player::Current::_instance = NULL; Player::Current & Player::Current::instance() { if (_instance == NULL) { _instance = new Player::Current(); } return *_instance; } Player::Current::~Current() { std::set<Subscriber *> subscribers = mSubscribers; for (std::set<Subscriber *>::iterator it = subscribers.begin(); it != subscribers.end(); ++it) { (*it)->unsubscribe(); } _instance = NULL; } void Player::Current::playerDeactivated(Player * player) { if (player != NULL && player->selectedSector().sector() != NULL) { player->selectedSector().sector()->notifyDeselected(); } } void Player::Current::playerActivated(Player * player) { if (player != NULL && player->selectedSector().sector() != NULL) { player->selectedSector().sector()->notifySelected(); } std::set<Subscriber *> subscribers = mSubscribers; for (std::set<Subscriber *>::iterator it = subscribers.begin(); it != subscribers.end(); ++it) { (*it)->selectedSectorChanged(player != NULL ? player->selectedSector().sector() : NULL); } } Player::Current::Current() : Universe::Game::Subscriber() , mSubscribers() , mSelectionAllowed(true) { } void Player::Current::setSelectionAllowed(bool allowed) { mSelectionAllowed = allowed; } bool Player::Current::selectionAllowed() const { return mSelectionAllowed; } void Player::Current::subscribe(Subscriber * subscriber) { if (subscriber != NULL) { mSubscribers.insert(subscriber); } } void Player::Current::unsubscribe(Subscriber * subscriber) { if (subscriber != NULL) { mSubscribers.erase(subscriber); } } const int Player::Colors[4][3] = { { 255, 95, 95 }, { 95, 255, 95 }, { 95, 95, 255 }, { 255, 95, 255 } }; std::vector<int> Player::color(int index) { std::vector<int> color; color.resize(3); std::copy(Colors[index], Colors[index]+3, color.begin()); return color; } Player::~Player() { delete mAI; mAI = NULL; } Player::Player() : mName("Unknown") , mShipConfigs() , mComponents() , mMoney(0) , mSelectedSector() , mHomeSector() , mKnownSystems() , mElements() , mAI(NULL) { } void Player::update() { } const std::string & Player::name() const { return mName; } void Player::setName(const std::string & name) { mName = name; } int Player::money() const { return mMoney; } void Player::setMoney(int money) { mMoney = money; } const std::vector<ShipConfig> & Player::shipConfigs() const { return mShipConfigs; } void Player::setShipConfigs(const std::vector<ShipConfig> & shipConfigs) { mShipConfigs = shipConfigs; } ShipConfig Player::shipConfig(const std::string & configName) const { ShipConfig shipConfig; for (std::vector<ShipConfig>::const_iterator it = mShipConfigs.begin(); it != mShipConfigs.end(); ++it) { if ((*it).name() == configName) { shipConfig = *it; break; } } return shipConfig; } void Player::addShipConfig(const ShipConfig & shipConfig) { bool updated = false; for (std::vector<ShipConfig>::iterator it = mShipConfigs.begin(); it != mShipConfigs.end(); ++it) { if ((*it).name() == shipConfig.name()) { (*it) = shipConfig; updated = true; } } if (!updated) { mShipConfigs.push_back(shipConfig); } } const std::vector<Component> & Player::components() const { return mComponents; } void Player::setComponents(const std::vector<Component> & components) { mComponents = components; } const SectorReference & Player::selectedSector() const { return mSelectedSector; } void Player::setSelectedSector(const SectorReference & selectedSector) { if (Current::instance().selectionAllowed()) { SectorReference previous = mSelectedSector; mSelectedSector = selectedSector; if (previous.sector() != NULL) { previous.sector()->notifyDeselected(); } if (mSelectedSector.sector() != NULL) { mSelectedSector.sector()->notifySelected(); } std::set<Current::Subscriber *> subscribers = Current::instance().mSubscribers; for (std::set<Current::Subscriber *>::iterator it = subscribers.begin(); it != subscribers.end(); ++it) { (*it)->selectedSectorChanged(mSelectedSector.sector()); } } } void Player::reselectSector() { if (Current::instance().selectionAllowed()) { std::set<Current::Subscriber *> subscribers = Current::instance().mSubscribers; for (std::set<Current::Subscriber *>::iterator it = subscribers.begin(); it != subscribers.end(); ++it) { (*it)->selectedSectorReselected(mSelectedSector.sector()); } } } const SectorReference & Player::homeSector() const { return mHomeSector; } void Player::setHomeSector(const SectorReference & homeSector) { mHomeSector = homeSector; } const std::vector<StarSystemReference> & Player::knownSystems() const { return mKnownSystems; } void Player::setKnownSystems(const std::vector<StarSystemReference> & knownSystems) { for (std::vector<StarSystemReference>::const_iterator it = knownSystems.begin(); it != knownSystems.end(); ++it) { addKnownSystem(*it); } } void Player::addKnownSystem(const StarSystemReference & knownSystem) { if (std::find(mKnownSystems.begin(), mKnownSystems.end(), knownSystem) == mKnownSystems.end()) { mKnownSystems.push_back(knownSystem); if (knownSystem.starSystem() != NULL) { knownSystem.starSystem()->notifyBecameKnown(); } } } bool Player::knows(StarSystem * starSystem) const { return starSystem != NULL && std::find(mKnownSystems.begin(), mKnownSystems.end(), StarSystemReference(starSystem)) != mKnownSystems.end(); } void Player::accept(UniverseVisitor * visitor) { if (visitor != NULL) { visitor->visit(this); } } AI * Player::ai() const { return mAI; } void Player::setAI(AI * ai) { mAI = ai; } bool Player::isHuman() const { return dynamic_cast<NPC *>(mAI) == NULL; } int Player::revenue() const { static const float TaxRate = 0.10f; static const float MaintenanceRate = 0.01f; int rev = 0; Game::StatsVisitor stats(this); Game::Universe::instance().accept(&stats); for (unsigned int i = 0; i < stats.mPlanets.size(); ++i) { if (stats.mPlanets[i] != NULL) { rev += int(stats.mPlanets[i]->population() * TaxRate); } } for (unsigned int i = 0; i < stats.mShips.size(); ++i) { if (stats.mShips[i] != NULL) { rev -= int(stats.mShips[i]->config().cost() * MaintenanceRate); } } return rev; }
[ "mitthrawn@hotmail.com" ]
mitthrawn@hotmail.com
c8f5fca5300968314f2ce8a4fb17f89c73eb20c7
219c8e3fb09447f1a63e6bce695f3e61632df580
/src/command/moveunitcommand.cpp
595f215bebe426a01b176e7983430412822bf2a9
[]
no_license
AlexandreSanscartier/tripping-happiness
f2d7d1aadc0b81cb44ea7d70bf16d3e369881a36
9cc201fd0ecd74bbb381be9207569d948b1cb56d
refs/heads/master
2021-01-04T02:35:44.441048
2014-08-28T20:23:00
2014-08-28T20:23:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
30
cpp
#include "moveunitcommand.h"
[ "alex.sanscartier@gmail.com" ]
alex.sanscartier@gmail.com
2111efd13c7ffb6639b12dd3fb390f8ef51199c3
fee815564249d783307fa9a4c126a7df3a44ea5a
/E4_DspBuilder/docs/ReferenceDesignsReference_Design/Turbo/ctc_harris/cml/source/systemc/sysc/packages/boost/detail/call_traits.hpp
289fac4155e15a3fa22305fdbe81a2904978de89
[]
no_license
Benjamin142857/FPGA_Experiment_3A
6b4438d3cf01fafa9252a22c685afc5bdccf4682
4d546b29640e0a61ea46f16f2f61e4e91cf525ad
refs/heads/master
2020-09-13T00:04:24.561146
2019-11-26T12:50:26
2019-11-26T12:50:26
222,598,436
1
0
null
null
null
null
UTF-8
C++
false
false
3,974
hpp
// (C) Copyright Steve Cleary, Beman Dawes, Howard Hinnant & John Maddock 2000. // Permission to copy, use, modify, sell and // distribute this software is granted provided this copyright notice appears // in all copies. This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // See http://www.boost.org for most recent version including documentation. // call_traits: defines typedefs for function usage // (see libs/utility/call_traits.htm) /* Release notes: 23rd July 2000: Fixed array specialization. (JM) Added Borland specific fixes for reference types (issue raised by Steve Cleary). */ #ifndef BOOST_DETAIL_CALL_TRAITS_HPP #define BOOST_DETAIL_CALL_TRAITS_HPP #ifndef BOOST_CONFIG_HPP #include <sysc/packages/boost/config.hpp> #endif #ifndef BOOST_ARITHMETIC_TYPE_TRAITS_HPP #include <sysc/packages/boost/type_traits/arithmetic_traits.hpp> #endif #ifndef BOOST_COMPOSITE_TYPE_TRAITS_HPP #include <sysc/packages/boost/type_traits/composite_traits.hpp> #endif namespace boost{ namespace detail{ template <typename T, bool small_> struct ct_imp2 { typedef const T& param_type; }; template <typename T> struct ct_imp2<T, true> { typedef const T param_type; }; template <typename T, bool isp, bool b1> struct ct_imp { typedef const T& param_type; }; template <typename T, bool isp> struct ct_imp<T, isp, true> { typedef typename ct_imp2<T, sizeof(T) <= sizeof(void*)>::param_type param_type; }; template <typename T, bool b1> struct ct_imp<T, true, b1> { typedef T const param_type; }; } template <typename T> struct call_traits { public: typedef T value_type; typedef T& reference; typedef const T& const_reference; // // C++ Builder workaround: we should be able to define a compile time // constant and pass that as a single template parameter to ct_imp<T,bool>, // however compiler bugs prevent this - instead pass three bool's to // ct_imp<T,bool,bool,bool> and add an extra partial specialisation // of ct_imp to handle the logic. (JM) typedef typename detail::ct_imp< T, ::boost::is_pointer<T>::value, ::boost::is_arithmetic<T>::value >::param_type param_type; }; template <typename T> struct call_traits<T&> { typedef T& value_type; typedef T& reference; typedef const T& const_reference; typedef T& param_type; // hh removed const }; #if defined(__BORLANDC__) && (__BORLANDC__ <= 0x560) // these are illegal specialisations; cv-qualifies applied to // references have no effect according to [8.3.2p1], // C++ Builder requires them though as it treats cv-qualified // references as distinct types... template <typename T> struct call_traits<T&const> { typedef T& value_type; typedef T& reference; typedef const T& const_reference; typedef T& param_type; // hh removed const }; template <typename T> struct call_traits<T&volatile> { typedef T& value_type; typedef T& reference; typedef const T& const_reference; typedef T& param_type; // hh removed const }; template <typename T> struct call_traits<T&const volatile> { typedef T& value_type; typedef T& reference; typedef const T& const_reference; typedef T& param_type; // hh removed const }; #endif #ifndef __SUNPRO_CC template <typename T, std::size_t N> struct call_traits<T [N]> { private: typedef T array_type[N]; public: // degrades array to pointer: typedef const T* value_type; typedef array_type& reference; typedef const array_type& const_reference; typedef const T* const param_type; }; template <typename T, std::size_t N> struct call_traits<const T [N]> { private: typedef const T array_type[N]; public: // degrades array to pointer: typedef const T* value_type; typedef array_type& reference; typedef const array_type& const_reference; typedef const T* const param_type; }; #endif } #endif // BOOST_DETAIL_CALL_TRAITS_HPP
[ "benjamin142857@outlook.com" ]
benjamin142857@outlook.com
cdc474d6622568ec7332ae536c34b0b365da6ce8
9ea01d4df33eab409aec2d6533137fe0a43ee37f
/quadcopter_controllers/full_controllers/3d/pid_cascaded/src/cascaded_controller.cpp
65e6f516d274759a80bca0fffba2a4de21729bea
[]
no_license
sarath-menon/controller_lib
512c10f50c45113f74ebf1a5209c425d073be4a4
6a1046351902c92b44c9f291986a95a996bfdca7
refs/heads/master
2023-09-01T05:38:54.448763
2021-11-01T18:32:40
2021-11-01T18:32:40
410,218,122
0
0
null
null
null
null
UTF-8
C++
false
false
1,612
cpp
#include "pid_cascaded.h" namespace controllers_3d { cpp_msg::ThrustTorqueCommand & BasicPidCascaded::cascaded_controller(const cpp_msg::Pose &pose, const cpp_msg::Pose &pose_setpoint) { // Outer loop thrust_torque_cmd.thrust = z_position_controller(pose_setpoint.position.z, pose.position.z); roll_angle_command = y_position_controller(pose_setpoint.position.y, pose.position.y); // Inner loop thrust_torque_cmd.roll_torque = roll_angle_controller(roll_angle_command, pose.orientation_euler.roll); return thrust_torque_cmd; }; cpp_msg::ThrustTorqueCommand &BasicPidCascaded::cascaded_controller( const cpp_msg::Pose &pose, const cpp_msg::QuadPositionCmd &pos_setpoint) { // Outer loop thrust_torque_cmd.thrust = z_position_controller(pos_setpoint.position.z, pose.position.z); roll_angle_command = y_position_controller(pos_setpoint.position.y, pose.position.y); pitch_angle_command = x_position_controller(pos_setpoint.position.x, pose.position.x); // Inner loop thrust_torque_cmd.roll_torque = roll_angle_controller(roll_angle_command, pose.orientation_euler.roll); thrust_torque_cmd.pitch_torque = pitch_angle_controller(pitch_angle_command, pose.orientation_euler.pitch); // std::cout << "Cmd: " << thrust_torque_cmd.thrust << '\t' // << thrust_torque_cmd.roll_torque << '\t' // << thrust_torque_cmd.pitch_torque << '\t' // << thrust_torque_cmd.yaw_torque << std::endl; return thrust_torque_cmd; }; } // namespace controllers_3d
[ "smenon@ethz.ch" ]
smenon@ethz.ch
15685f430008635cf3599c9cac3ca5b341a92b0d
cfe8ea74ce5651e9954b3e9c6e4e495e031e0ad7
/utils/vgui/include/VGUI_Dar.h
6f8eb513bb900e19a959523795bc462cfdc23424
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "curl" ]
permissive
YaLTeR/OpenAG
dd699ec10d25672bf640812cd118f09ca92523b3
78fac3a9d0d8c033166f13d099d50ca1410e89e4
refs/heads/master
2023-05-10T17:15:01.445266
2023-05-02T04:20:02
2023-05-02T04:20:02
61,480,530
139
63
NOASSERTION
2022-12-31T00:07:53
2016-06-19T13:03:05
C++
WINDOWS-1252
C++
false
false
3,697
h
//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ // // Purpose: // // $NoKeywords: $ //============================================================================= #ifndef VGUI_DAR_H #define VGUI_DAR_H #include<stdlib.h> #include<string.h> #include<VGUI.h> namespace vgui { //Simple lightweight dynamic array implementation template<class ELEMTYPE> class VGUIAPI Dar { public: Dar() { _count=0; _capacity=0; _data=null; ensureCapacity(4); } Dar(int initialCapacity) { _count=0; _capacity=0; _data=null; ensureCapacity(initialCapacity); } public: void ensureCapacity(int wantedCapacity) { if(wantedCapacity<=_capacity){return;} //double capacity until it is >= wantedCapacity //this could be done with math, but iterative is just so much more fun int newCapacity=_capacity; if(newCapacity==0){newCapacity=1;} while(newCapacity<wantedCapacity){newCapacity*=2;} //allocate and zero newData ELEMTYPE* newData=new ELEMTYPE[newCapacity]; if(newData==null){exit(0);return;} memset(newData,0,sizeof(ELEMTYPE)*newCapacity); _capacity=newCapacity; //copy data into newData for(int i=0;i<_count;i++){newData[i]=_data[i];} delete[] _data; _data=newData; } void setCount(int count) { if((count<0)||(count>_capacity)) { return; } _count=count; } int getCount() { return _count; } void addElement(ELEMTYPE elem) { ensureCapacity(_count+1); _data[_count]=elem; _count++; } bool hasElement(ELEMTYPE elem) { for(int i=0;i<_count;i++) { if(_data[i]==elem) { return true; } } return false; } void putElement(ELEMTYPE elem) { if(hasElement(elem)) { return; } addElement(elem); } void insertElementAt(ELEMTYPE elem,int index) { if((index<0)||(index>_count)) { return; } if((index==_count)||(_count==0)) { addElement(elem); } else { addElement(elem); //just to make sure it is big enough for(int i=_count-1;i>index;i--) { _data[i]=_data[i-1]; } _data[index]=elem; } } void setElementAt(ELEMTYPE elem,int index) { if((index<0)||(index>=_count)) { return; } _data[index]=elem; } void removeElementAt(int index) { if((index<0)||(index>=_count)) { return; } //slide everything to the right of index, left one. for(int i=index;i<(_count-1);i++) { _data[i]=_data[i+1]; } _count--; } void removeElement(ELEMTYPE elem) { for(int i=0;i<_count;i++) { if(_data[i]==elem) { removeElementAt(i); break; } } } void removeAll() { _count=0; } ELEMTYPE operator[](int index) { if((index<0)||(index>=_count)) { return null; } return _data[index]; } protected: int _count; int _capacity; ELEMTYPE* _data; }; #ifdef _WIN32 //forward referencing all the template types used so they get exported template class VGUIAPI Dar<char>; template class VGUIAPI Dar<char*>; template class VGUIAPI Dar<int>; template class VGUIAPI Dar<class Button*>; template class VGUIAPI Dar<class SurfaceBase*>; template class VGUIAPI Dar<class InputSignal*>; template class VGUIAPI Dar<class FocusChangeSignal*>; template class VGUIAPI Dar<class FrameSignal*>; template class VGUIAPI Dar<class ActionSignal*>; template class VGUIAPI Dar<class IntChangeSignal*>; template class VGUIAPI Dar<class TickSignal*>; template class VGUIAPI Dar<class Dar<char>*>; template class VGUIAPI Dar<class Frame*>; template class VGUIAPI Dar<class DesktopIcon*>; template class VGUIAPI Dar<class ChangeSignal*>; template class VGUIAPI Dar<class Panel*>; template class VGUIAPI Dar<class Label*>; template class VGUIAPI Dar<class RepaintSignal*>; #endif } #endif
[ "alfred@alfredmacpro.valvesoftware.com" ]
alfred@alfredmacpro.valvesoftware.com
6c47f3800e629f7424609d07f1f0fe5b9a3d9a93
3f60c2e6358df73846d3e82794ff811cbaedc195
/c++/W01-01-Two fighters, one winner.cpp
9baa209001e8a23a8c700146682ba6f741599a71
[]
no_license
andreldelrosario/code-kata
57b3a538aa888e1ddcff2c05a2b0562de1a60b78
76a2314358742ac75e2ebcf01f8e66eeb9058525
refs/heads/master
2021-01-11T23:54:05.288114
2017-03-06T14:48:12
2017-03-06T14:48:12
78,643,480
0
0
null
null
null
null
UTF-8
C++
false
false
987
cpp
//Two fighters, one winner. bool isDead(Fighter* fighter) { return fighter->getHealth() <= 0; } void hitDefender(Fighter* defender, int attackDamage) { int newHealth = defender->getHealth() - attackDamage; defender->setHealth(newHealth); } std::string declareWinner(Fighter* fighter1, Fighter* fighter2, std::string firstAttacker) { // Your code goes here. Have fun! std::vector<Fighter*> combatants = {fighter1, fighter2}; int attackingCombatant = firstAttacker.compare(combatants[0]->getName()) == 0 ? 0 : 1; int defendingCombatant = -1; Fighter* attacker = NULL; do { attacker = combatants[attackingCombatant]; defendingCombatant = (attackingCombatant + 1) % 2; Fighter* defender = combatants[defendingCombatant]; hitDefender(defender, attacker->getDamagePerAttack()); attackingCombatant = defendingCombatant; } while (!isDead(combatants[defendingCombatant])); return attacker->getName(); }
[ "andreldelrosario@gmail.com" ]
andreldelrosario@gmail.com
f9c7dd84754ea294886eb95f0e5925498411f69b
527739ed800e3234136b3284838c81334b751b44
/include/RED4ext/Types/generated/anim/AnimEvent_Effect.hpp
44cee55081248475f990b7d939f2be5c7e4921cd
[ "MIT" ]
permissive
0xSombra/RED4ext.SDK
79ed912e5b628ef28efbf92d5bb257b195bfc821
218b411991ed0b7cb7acd5efdddd784f31c66f20
refs/heads/master
2023-07-02T11:03:45.732337
2021-04-15T16:38:19
2021-04-15T16:38:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
588
hpp
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/REDhash.hpp> #include <RED4ext/CName.hpp> #include <RED4ext/Types/generated/anim/AnimEvent.hpp> namespace RED4ext { namespace anim { struct AnimEvent_Effect : anim::AnimEvent { static constexpr const char* NAME = "animAnimEvent_Effect"; static constexpr const char* ALIAS = NAME; CName effectName; // 40 uint8_t unk48[0x50 - 0x48]; // 48 }; RED4EXT_ASSERT_SIZE(AnimEvent_Effect, 0x50); } // namespace anim } // namespace RED4ext
[ "expired6978@gmail.com" ]
expired6978@gmail.com
ae01839c713c1c0c19cce3042d52fcfef748388a
de56831c6f77f0e7a3c1717a5785dac9291dc0f9
/main.cpp
fb016f49c2faa485a07fe07cf9bf611a90c527b1
[]
no_license
davidzhangxm/Physics-Simulation
276d9c7d2081a402a81ce53f9b5ab8266e19c72d
ead82255bfa4ecc17da0694634c348634f26e50f
refs/heads/master
2020-05-09T14:33:03.208781
2019-06-12T03:48:46
2019-06-12T03:48:46
181,197,510
1
0
null
null
null
null
UTF-8
C++
false
false
10,578
cpp
#include <iostream> #include <limits> #include <glad/glad.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #define GLM_ENABLE_EXPERIMENTAL #include <glm/gtx/normal.hpp> #include "camera.h" #include "shader.h" #include "physys.h" #include "mesh.h" #include "plane.h" #include "Integrator.h" #include "debugger.h" #include "object_collision.h" #include "tetra_intersect.h" #define CHECK_GL_ERRORS assert(glGetError() == GL_NO_ERROR) void framebuffer_size_callback(GLFWwindow* window, int width, int height); void processInput(GLFWwindow *window); void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); void mouse_callback(GLFWwindow* window, double xpos, double ypos); namespace { // window setting unsigned int WIDTH = 800; unsigned int HEIGHT = 600; // camera glm::vec3 viewPoint = glm::vec3(0, 10.0, 25.5); Camera camera(viewPoint); float lastX = WIDTH / 2.0f; float lastY = HEIGHT / 2.0f; bool firstMouse = true; //timing float deltaTime = 0.0f; float lastFrame = 0.0f; float timestep = 1.0f / 300; int step_per_frame = 5; // fracture bool fracture = false; float roughness = 100.0f; //lighting glm::vec3 lightPos(-3.0f, 20.0f, 5.0f); //model glm::vec3 location_1 = glm::vec3(-3, 10, 1); glm::vec3 location_2 = glm::vec3(-3, 5, 1); float densities = 0.3; // kg/m3 float v = 0.2f; float E = 800.0f; float v_damping = 0.1f; float E_damping = 10.0f; bool use_gravity = true; //ground glm::vec3 ground_origin(-15.0f, 0.0f, 15.0f); glm::vec3 ground_side1(0.0f, 0.0f, -1.0f); glm::vec3 ground_side2(1.0f, 0.0f, 0.0f); float ground_distance = 30.0f; // wall1 glm::vec3 wall_origin(-15.0f, 0.0f, 15.0f); glm::vec3 wall_side1(0.0f, 1.0f, 0.0f); glm::vec3 wall_side2(0.0f, 0.0f, -1.0f); float wall_distance = 30.0f; // wall2 glm::vec3 wall2_origin(-15.0f, 0.0f, -15.0f); glm::vec3 wall2_side1(0.0f, 1.0f, 0.0f); glm::vec3 wall2_side2(1.0f, 0.0f, 0.0f); float wall2_distance = 30.0f; } int main() { // intiailize window glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Apple setting #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif GLFWwindow *window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGl", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // tell GLFW to capture our mouse // glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // load all openGL functions pointers if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // configure global opengl state glEnable(GL_DEPTH_TEST); glEnable(GL_PROGRAM_POINT_SIZE); // model // MassSpringSystem cube1("model/cube_origin/cube.node", // "model/cube_origin/cube.face", // "model/cube_origin/cube.ele", // densities, // location_1, // v, E, // v_damping, E_damping, // timestep, // use_gravity, // fracture, // roughness, // lightPos, // camera.Position); // cube1.initShader(); // // MassSpringSystem cube2("model/cube_origin/cube.node", // "model/cube_origin/cube.face", // "model/cube_origin/cube.ele", // densities, // location_2, // v, E, // v_damping, E_damping, // timestep, // use_gravity, // fracture, // roughness); // cube2.initShader(); MassSpringSystem mesh("model/cube/cube.1.node", "model/cube/cube.1.face", "model/cube/cube.1.ele", densities, location_1, v, E, v_damping, E_damping, timestep, use_gravity, fracture, roughness, lightPos, camera.Position); mesh.initShader(); // MassSpringSystem rectangle("model/rectangle/rectangle.1.node", // "model/rectangle/rectangle.1.face", // "model/rectangle/rectangle.1.ele", // densities, // location_2, // v, E, // v_damping, E_damping, // timestep, // use_gravity, // fracture, // roughness); // rectangle.initShader(); // ground Plane ground(ground_origin, ground_side1, ground_side2, ground_distance, lightPos, camera.Position); ground.initShaders(); // wall1 Plane wall(wall_origin, wall_side1, wall_side2, wall_distance, lightPos, camera.Position); wall.initShaders(); // wall2 Plane wall2(wall2_origin, wall2_side1, wall2_side2, wall2_distance, lightPos, camera.Position); wall2.initShaders(); ForwardEulerIntegrator ForwardEuler; std::vector<MassSpringSystem> object_list = {mesh}; //render loop while(!glfwWindowShouldClose(window)){ float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // input processInput(window); // render start 166, 202, 240 // glClearColor(0.65f, 0.79f, 0.94f, 0.0f); glClearColor(0.05, 0.05, 0.05, 0.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glm::mat4 view = glm::mat4(1.0f); view = camera.GetViewMatrix(); glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)WIDTH/(float)HEIGHT, 0.1f, 100.0f); glm::mat4 transform = projection * view; glm::mat4 model = glm::mat4(1.0f); ground.setTransform(transform); // ground.setVirePos(camera.Position); ground.renderPlane(); wall.setTransform(transform); // wall.setVirePos(camera.Position); wall.renderPlane(); wall2.setTransform(transform); // wall2.setVirePos(camera.Position); wall2.renderPlane(); // cube1.set_transformation(transform); // cube1.set_viewpos(camera.Position); // cube1.render_system(); // // cube2.set_transformation(transform); // cube2.render_system(); mesh.set_transformation(transform); // mesh.set_viewpos(camera.Position); mesh.render_system(); // rectangle.set_transformation(transform); // rectangle.render_system(); // draw geometry glfwSwapBuffers(window); glfwPollEvents(); for (int i = 0; i < step_per_frame; ++i) { // clear obkject force first CollideQuery::clear_collision_response(object_list); // object collision detection std::vector<std::tuple<int, int, std::vector<std::pair<unsigned int, unsigned int>>>> collide_result_list = CollideQuery::collide_quert_list(object_list); // object collision response if(!collide_result_list.empty()) CollideQuery::collision_response(collide_result_list, object_list); // collision with ground for (int j = 0; j < object_list.size(); ++j) { ground.processCollision(object_list[j]); } for (int j = 0; j < object_list.size(); ++j) { wall.processCollision(object_list[j]); } for (int j = 0; j < object_list.size(); ++j) { wall2.processCollision(object_list[j]); } // integration for (int k = 0; k < object_list.size(); ++k) { ForwardEuler.Integrate(&object_list[k], timestep); } // aabb update for(int i = 0; i < object_list.size(); ++i) object_list[i].update_aabb_tree(); } // buffer data update for (int l = 0; l < object_list.size(); ++l) { object_list[l].update(); } // cube1_de.update(object_list[0]); // cube2_de.update(object_list[1]); } // cube1.delete_shader(); // cube2.delete_shader(); mesh.delete_shader(); // rectangle.delete_shader(); ground.deleteBuffer(); wall.deleteBuffer(); wall2.deleteBuffer(); return 0; } void processInput(GLFWwindow* window) { if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); if(glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) camera.ProcessKeyboard(FORWARD, deltaTime); if(glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) camera.ProcessKeyboard(BACKWARD, deltaTime); if(glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) camera.ProcessKeyboard(LEFT, deltaTime); if(glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) camera.ProcessKeyboard(RIGHT, deltaTime); } void framebuffer_size_callback(GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); } void mouse_callback(GLFWwindow* window, double xpos, double ypos) { if(firstMouse) { lastX = xpos; lastY = ypos; firstMouse = false; } float xoffset = xpos - lastX; float yoffset = lastY - ypos; lastX = xpos; lastY = ypos; camera.ProcessMouseMovement(xoffset, yoffset); } void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { camera.ProcessMouseScroll(yoffset); }
[ "514405608@qq.com" ]
514405608@qq.com
ebca37773283bcc6b992bc59b7fec46f94cf3055
a27eeee986c716458515a2191d3b822c5332bd7f
/DFS/maxAreaOfIsland.cpp
8dd631d62f091d6fa5510a5624b6315a50260624
[]
no_license
wyukai/coding
e68a92d910332689c298a17c68859d98e9ee92b2
59cf6cec0d1461fcfc1496198f8b8b8c5c5f22d7
refs/heads/master
2021-08-16T13:15:20.780028
2021-08-10T08:27:58
2021-08-10T08:27:58
201,733,583
0
0
null
null
null
null
UTF-8
C++
false
false
3,151
cpp
// // Created by wk on 2021/7/9. // #include <iostream> #include <vector> #include <stack> using namespace std; vector<int> directions = {-1,0,1,0,-1}; /* * 在辅函数里,一个一定要注意的点是辅函数内递归搜索时,边界条件的判定。边界判定一般 有两种写法,一种是先判定是否越界,只有在合法的情况下才进行下一步搜索(即判断放在调用 递归函数前);另一种是不管三七二十一先进行下一步搜索,待下一步搜索开始时再判断是否合 法(即判断放在辅函数第一行) */ //递归写法 int dfs(vector<vector<int>>& grid, int i, int j){ // 边界情况 if(grid[i][j] == 0){ return 0; } //已经访问过的陆地置为0 grid[i][j] = 0; int x, y , area = 1; //在四个方向上进行搜索 for(int n = 0; n < 4; ++n){ x = i + directions[n]; y = j + directions[n + 1]; //注意考虑越界情况 if(x >= 0 && x < grid.size() && y >= 0 && y< grid[0].size()){ area += dfs(grid, x, y); } } return area; } int maxAreaOfIsland(vector<vector<int>> grid){ // 判断边界及异常情况 if(grid.empty() || grid[0].empty()){ return 0; } //遍历 int max_area = 0; for(int i = 0; i < grid.size(); ++i){ for(int j = 0; j < grid[0].size(); ++j){ //当遇到陆地时,开始深度优先遍历上下左右相连的陆地 if(grid[i][j] == 1) { max_area = max(max_area, dfs(grid, i, j)); } } } return max_area; } // 栈实现深度优先搜索 int maxAreaOfIsland_2(vector<vector<int>> grid){ int area=0, local_area = 0; int m = grid.size(); int n = grid[0].size(); int x, y; //循环搜索 for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { //探索岛屿 if(grid[i][j]){ local_area = 1; //访问过的岛屿置为0 grid[i][j] = 0; stack<pair<int, int>> island; island.push({i,j}); while (!island.empty()){ auto [r,c] = island.top(); island.pop(); for(int k = 0; k < 4; ++k){ x = r + directions[k]; y = c + directions[k + 1]; if(x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1){ grid[x][y] = 0; ++local_area; island.push({x,y}); } } } area = max(area, local_area); } } } return area; } int main(){ vector<vector<int>> isLand = {{1,0,1,1,0,1,0,1}, {1,0,1,1,0,1,1,1}, {0,0,0,0,0,0,0,1}}; int max_area = maxAreaOfIsland(isLand); cout << "max island is : "<<max_area << endl; int max_area_2 = maxAreaOfIsland_2(isLand); cout << "max island is : "<<max_area_2 << endl; }
[ "18502408205@163.com" ]
18502408205@163.com
e06bc68570a84c9363074d0ce0a6d26f2ee4dc77
133d0f38b3da2c51bf52bcdfa11d62978b94d031
/testAutocad/vendor/ifc-sdk/src/ifc2x3/IfcApprovalActorRelationship.cpp
5aeb226ca656183bdd8ec415348ac4ee385e540a
[]
no_license
Aligon42/ImportIFC
850404f1e1addf848e976b0351d9e217a72f868a
594001fc0942d356eb0d0472c959195151510493
refs/heads/master
2023-08-15T08:00:14.056542
2021-07-05T13:49:28
2021-07-05T13:49:28
361,410,709
0
1
null
null
null
null
UTF-8
C++
false
false
6,006
cpp
// IFC SDK : IFC2X3 C++ Early Classes // Copyright (C) 2009 CSTB // // 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. // The full license is in Licence.txt file included with this // distribution or is available at : // http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html // // 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. #include <ifc2x3/IfcApprovalActorRelationship.h> #include <ifc2x3/CopyOp.h> #include <ifc2x3/IfcActorRole.h> #include <ifc2x3/IfcActorSelect.h> #include <ifc2x3/IfcApproval.h> #include <ifc2x3/Visitor.h> #include <Step/BaseCopyOp.h> #include <Step/BaseEntity.h> #include <Step/BaseExpressDataSet.h> #include <Step/BaseObject.h> #include <Step/Referenced.h> #include <Step/SPFFunctions.h> #include <stdlib.h> #include <string> #include "precompiled.h" using namespace ifc2x3; IfcApprovalActorRelationship::IfcApprovalActorRelationship(Step::Id id, Step::SPFData *args) : Step::BaseEntity(id, args) { m_actor = NULL; m_approval = NULL; m_role = NULL; } IfcApprovalActorRelationship::~IfcApprovalActorRelationship() { } bool IfcApprovalActorRelationship::acceptVisitor(Step::BaseVisitor *visitor) { return static_cast< Visitor * > (visitor)->visitIfcApprovalActorRelationship(this); } const std::string &IfcApprovalActorRelationship::type() const { return IfcApprovalActorRelationship::s_type.getName(); } const Step::ClassType &IfcApprovalActorRelationship::getClassType() { return IfcApprovalActorRelationship::s_type; } const Step::ClassType &IfcApprovalActorRelationship::getType() const { return IfcApprovalActorRelationship::s_type; } bool IfcApprovalActorRelationship::isOfType(const Step::ClassType &t) const { return IfcApprovalActorRelationship::s_type == t ? true : Step::BaseObject::isOfType(t); } IfcActorSelect *IfcApprovalActorRelationship::getActor() { if (Step::BaseObject::inited()) { return m_actor.get(); } else { return NULL; } } const IfcActorSelect *IfcApprovalActorRelationship::getActor() const { IfcApprovalActorRelationship * deConstObject = const_cast< IfcApprovalActorRelationship * > (this); return deConstObject->getActor(); } void IfcApprovalActorRelationship::setActor(const Step::RefPtr< IfcActorSelect > &value) { m_actor = value; } void IfcApprovalActorRelationship::unsetActor() { m_actor = Step::getUnset(getActor()); } bool IfcApprovalActorRelationship::testActor() const { return !Step::isUnset(getActor()); } IfcApproval *IfcApprovalActorRelationship::getApproval() { if (Step::BaseObject::inited()) { return m_approval.get(); } else { return NULL; } } const IfcApproval *IfcApprovalActorRelationship::getApproval() const { IfcApprovalActorRelationship * deConstObject = const_cast< IfcApprovalActorRelationship * > (this); return deConstObject->getApproval(); } void IfcApprovalActorRelationship::setApproval(const Step::RefPtr< IfcApproval > &value) { if (m_approval.valid()) { m_approval->m_actors.erase(this); } if (value.valid()) { value->m_actors.insert(this); } m_approval = value; } void IfcApprovalActorRelationship::unsetApproval() { m_approval = Step::getUnset(getApproval()); } bool IfcApprovalActorRelationship::testApproval() const { return !Step::isUnset(getApproval()); } IfcActorRole *IfcApprovalActorRelationship::getRole() { if (Step::BaseObject::inited()) { return m_role.get(); } else { return NULL; } } const IfcActorRole *IfcApprovalActorRelationship::getRole() const { IfcApprovalActorRelationship * deConstObject = const_cast< IfcApprovalActorRelationship * > (this); return deConstObject->getRole(); } void IfcApprovalActorRelationship::setRole(const Step::RefPtr< IfcActorRole > &value) { m_role = value; } void IfcApprovalActorRelationship::unsetRole() { m_role = Step::getUnset(getRole()); } bool IfcApprovalActorRelationship::testRole() const { return !Step::isUnset(getRole()); } bool IfcApprovalActorRelationship::init() { std::string arg; arg = m_args->getNext(); if (arg == "$" || arg == "*") { m_actor = NULL; } else { m_actor = new IfcActorSelect; if (arg[0] == '#') { m_actor->set(m_expressDataSet->get((Step::Id)atol(arg.c_str() + 1))); } else if (arg[arg.length() - 1] == ')') { std::string type1; std::string::size_type i1; i1 = arg.find('('); if (i1 != std::string::npos) { type1 = arg.substr(0, i1); arg = arg.substr(i1 + 1, arg.length() - i1 - 2); } } } arg = m_args->getNext(); if (arg == "$" || arg == "*") { m_approval = NULL; } else { m_approval = static_cast< IfcApproval * > (m_expressDataSet->get(Step::getIdParam(arg))); } arg = m_args->getNext(); if (arg == "$" || arg == "*") { m_role = NULL; } else { m_role = static_cast< IfcActorRole * > (m_expressDataSet->get(Step::getIdParam(arg))); } return true; } void IfcApprovalActorRelationship::copy(const IfcApprovalActorRelationship &obj, const CopyOp &copyop) { Step::BaseEntity::copy(obj, copyop); m_actor = new IfcActorSelect; m_actor->copy(*(obj.m_actor.get()), copyop); setApproval((IfcApproval*)copyop(obj.m_approval.get())); setRole((IfcActorRole*)copyop(obj.m_role.get())); return; } IFC2X3_EXPORT Step::ClassType IfcApprovalActorRelationship::s_type("IfcApprovalActorRelationship");
[ "antoine.cacheux@procal.fr" ]
antoine.cacheux@procal.fr
47354a10ead4ec784e7e7af3c0a8d548c198e775
b1f396a687c8c83bc9e3123b056e60b1423db570
/src/seqStruct.hpp
51ea63360de01f262ee291c27bfabf6e6d2e2be2
[]
no_license
morikie/polar
8033daa7a7e1775a8e48241067edb56043c55d3d
46728b9ca4a1f7b0fd8a7ddddb26f37306feb2eb
refs/heads/master
2021-01-19T01:17:44.624383
2017-07-19T13:17:53
2017-07-19T13:17:53
37,848,036
2
0
null
null
null
null
UTF-8
C++
false
false
736
hpp
#ifndef __TRANSCRIPTMUTATION_HPP__ #define __TRANSCRIPTMUTATION_HPP__ #include <string> #include <boost/optional.hpp> #include "hgvsParser.hpp" /** * This class is used as a wrapper for the arguments "needed" by Utr3Finder */ struct SeqStruct { const std::string seq; boost::optional<const size_t> utr3Start; boost::optional<const size_t> txLength; //HGVS string parser boost::optional<const HgvsParser> mutation; //information about the sequence boost::optional<const std::string &> chrom; boost::optional<const size_t &> genomicPos; boost::optional<const std::string &> strand; //name of the sequence (e.g. transcript ID) boost::optional<const std::string &> seqId; }; #endif /* __TRANSCRIPTMUTATION_HPP__ */
[ "moritz.k@fu-berlin.de" ]
moritz.k@fu-berlin.de
ff96defcdf2cde624fd45108b03cffa7215201d2
f5cf8fff59bd1e5a490762c0087faf59e5ac6868
/Comm1.h
85c9777a75d030f4123904ed39e5a35b3cf34ca2
[]
no_license
cuihao0532/CSerial-class
0078455f417444f4cc195d71d444b921315dbb9a
26b139103d5582519b7f6c38d45de51fb3afd308
refs/heads/master
2016-09-14T04:12:06.493215
2016-05-10T10:06:46
2016-05-10T10:06:46
57,055,620
0
0
null
null
null
null
GB18030
C++
false
false
1,633
h
#pragma once #include "resource.h" #include "EventHandler.h" #include "Serial.h" using cuish::CSerial; #include <iostream> using std::cout; using std::endl; class CCom : public ISerialEventHandler { public: CCom(); virtual ~CCom(); bool Init(LPCTSTR lpSerialName, CSerial::_eOpenMode eMode); bool SetState(DWORD dwBaudRate/*波特率*/, BYTE byteParity/*校验*/, BYTE byteStopBits/*停止位*/); bool SetBufferSize(DWORD dwInput, DWORD dwOutput); bool Write(void* pBuf, DWORD dwNumBytsToWirte); bool Start(); void ReadFinish(void* pBuf, DWORD dwRead); void WriteFinish(void* pBuf, DWORD dwWritten ); protected: CSerial m_serial; }; CCom::CCom() : m_serial(this) { } CCom::~CCom() { } bool CCom::Init(LPCTSTR lpSerialName, CSerial::_eOpenMode eMode) { bool b = m_serial.Open(lpSerialName, eMode); return b; } void CCom::ReadFinish(void* pBuf, DWORD dwRead) { std::cout << (char*)( pBuf ) << std::endl; int a = 0; } void CCom::WriteFinish(void* pBuf, DWORD dwWritten ) { std::cout << (char*)( pBuf ) << ", Written Bytes=" << dwWritten << std::endl; int b = 0; } bool CCom::SetState(DWORD dwBaudRate/*波特率*/, BYTE byteParity/*校验*/, BYTE byteStopBits/*停止位*/) { return m_serial.SetState(dwBaudRate, byteParity, byteStopBits); } bool CCom::SetBufferSize(DWORD dwInput, DWORD dwOutput) { return m_serial.SetBufferSize(dwInput, dwOutput); } bool CCom::Start() { return m_serial.Start(); } bool CCom::Write(void* pBuf, DWORD dwNumBytsToWirte) { bool b = m_serial.Write(pBuf, dwNumBytsToWirte, NULL); return b; }
[ "cuihao0532@163.com" ]
cuihao0532@163.com
a811565402e9446ad7df51729a3a1070b9d91418
39d108f8b29a58cf8b756733c5fcaef013a87df5
/catkin_ws/devel/include/slugs_ros/SlugsInitExecutionStringRequest.h
299efbd274ff853abd331493355db4e0c2268a33
[]
no_license
kc834/swarm
0a5297eb44024e17de355f757228a0691d549551
c812b94cb5102c6dd211327a27edd0629ed9a63d
refs/heads/master
2021-08-31T04:48:52.359381
2017-12-20T12:10:55
2017-12-20T12:10:55
114,404,526
0
0
null
null
null
null
UTF-8
C++
false
false
5,957
h
// Generated by gencpp from file slugs_ros/SlugsInitExecutionStringRequest.msg // DO NOT EDIT! #ifndef SLUGS_ROS_MESSAGE_SLUGSINITEXECUTIONSTRINGREQUEST_H #define SLUGS_ROS_MESSAGE_SLUGSINITEXECUTIONSTRINGREQUEST_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace slugs_ros { template <class ContainerAllocator> struct SlugsInitExecutionStringRequest_ { typedef SlugsInitExecutionStringRequest_<ContainerAllocator> Type; SlugsInitExecutionStringRequest_() : init_inputs_outputs() { } SlugsInitExecutionStringRequest_(const ContainerAllocator& _alloc) : init_inputs_outputs(_alloc) { } typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _init_inputs_outputs_type; _init_inputs_outputs_type init_inputs_outputs; typedef boost::shared_ptr< ::slugs_ros::SlugsInitExecutionStringRequest_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::slugs_ros::SlugsInitExecutionStringRequest_<ContainerAllocator> const> ConstPtr; }; // struct SlugsInitExecutionStringRequest_ typedef ::slugs_ros::SlugsInitExecutionStringRequest_<std::allocator<void> > SlugsInitExecutionStringRequest; typedef boost::shared_ptr< ::slugs_ros::SlugsInitExecutionStringRequest > SlugsInitExecutionStringRequestPtr; typedef boost::shared_ptr< ::slugs_ros::SlugsInitExecutionStringRequest const> SlugsInitExecutionStringRequestConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::slugs_ros::SlugsInitExecutionStringRequest_<ContainerAllocator> & v) { ros::message_operations::Printer< ::slugs_ros::SlugsInitExecutionStringRequest_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace slugs_ros namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg'], 'actionlib_msgs': ['/opt/ros/indigo/share/actionlib_msgs/cmake/../msg'], 'slugs_ros': ['/home/kchaudhari/catkin_ws/src/LTL_stack/slugs_ros/msg', '/home/kchaudhari/catkin_ws/devel/share/slugs_ros/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::slugs_ros::SlugsInitExecutionStringRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::slugs_ros::SlugsInitExecutionStringRequest_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::slugs_ros::SlugsInitExecutionStringRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::slugs_ros::SlugsInitExecutionStringRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::slugs_ros::SlugsInitExecutionStringRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::slugs_ros::SlugsInitExecutionStringRequest_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::slugs_ros::SlugsInitExecutionStringRequest_<ContainerAllocator> > { static const char* value() { return "a90267b3a8111b10f13c8738b625a849"; } static const char* value(const ::slugs_ros::SlugsInitExecutionStringRequest_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xa90267b3a8111b10ULL; static const uint64_t static_value2 = 0xf13c8738b625a849ULL; }; template<class ContainerAllocator> struct DataType< ::slugs_ros::SlugsInitExecutionStringRequest_<ContainerAllocator> > { static const char* value() { return "slugs_ros/SlugsInitExecutionStringRequest"; } static const char* value(const ::slugs_ros::SlugsInitExecutionStringRequest_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::slugs_ros::SlugsInitExecutionStringRequest_<ContainerAllocator> > { static const char* value() { return "string init_inputs_outputs\n\ "; } static const char* value(const ::slugs_ros::SlugsInitExecutionStringRequest_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::slugs_ros::SlugsInitExecutionStringRequest_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.init_inputs_outputs); } ROS_DECLARE_ALLINONE_SERIALIZER; }; // struct SlugsInitExecutionStringRequest_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::slugs_ros::SlugsInitExecutionStringRequest_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::slugs_ros::SlugsInitExecutionStringRequest_<ContainerAllocator>& v) { s << indent << "init_inputs_outputs: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.init_inputs_outputs); } }; } // namespace message_operations } // namespace ros #endif // SLUGS_ROS_MESSAGE_SLUGSINITEXECUTIONSTRINGREQUEST_H
[ "kc834@cornell.edu" ]
kc834@cornell.edu
d588b9be7daa3134a7ce67c3f3c322bc0c82cc3e
0cfac3bf3ad8e349b1ec49427aba4f8b7acff545
/Chess.DataObjects/ChessRullEngine.h
ebecbceeff8d50744eb010e65dddf77af0a4cd15
[]
no_license
eli78435/Chess
ba74492ce4a7b1fc80e32f93d2132084bdca1a89
6e9752b979a7f27bbfcbca77538385307c95f0e0
refs/heads/master
2021-01-12T10:22:50.935420
2016-12-17T21:18:31
2016-12-17T21:18:31
76,437,603
0
0
null
null
null
null
UTF-8
C++
false
false
425
h
#pragma once #include <memory> #include "GameBoard.h" namespace Chess::DataObjects { class ChessRullEngine { std::weak_ptr<GameBoard> _gameBoard; void Move(GamePosition& start, GamePosition& end); public: ChessRullEngine(std::weak_ptr<GameBoard> gameBoard); ~ChessRullEngine(); bool TryMakeMove(GamePosition& start, GamePosition& end); bool CanMakeMove(GamePosition& start, GamePosition& end) const; }; }
[ "elid@codevalue.net" ]
elid@codevalue.net
1e169a6217073870b5e48054827dc63f4eeeb09a
ad926d4fdd771cacef1a914fd7deca5e440933a2
/src/qt/qtipcserver.cpp
2d49b9cc0f0b09a99d74e85987d1bdd0851d8738
[ "MIT" ]
permissive
mars2ll/knolix
2cbeb10f400cf53be5f53a953ab35f3cc44a3def
d72804a6a6b589703c7367322a2ab81b8b12cf1d
refs/heads/master
2023-02-26T17:23:40.032713
2021-02-03T21:39:00
2021-02-03T21:39:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,923
cpp
// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/version.hpp> #if defined(WIN32) && BOOST_VERSION == 104900 #define BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME #define BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME #endif #include "qtipcserver.h" #include "guiconstants.h" #include "ui_interface.h" #include "util.h" #include <boost/algorithm/string/predicate.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/interprocess/ipc/message_queue.hpp> #include <boost/version.hpp> #if defined(WIN32) && (!defined(BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME) || !defined(BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME) || BOOST_VERSION < 104900) #warning Compiling without BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME and BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME uncommented in boost/interprocess/detail/tmp_dir_helpers.hpp or using a boost version before 1.49 may have unintended results see svn.boost.org/trac/boost/ticket/5392 #endif using namespace boost; using namespace boost::interprocess; using namespace boost::posix_time; #if defined MAC_OSX || defined __FreeBSD__ // URI handling not implemented on OSX yet void ipcScanRelay(int argc, char *argv[]) { } void ipcInit(int argc, char *argv[]) { } #else static void ipcThread2(void* pArg); static bool ipcScanCmd(int argc, char *argv[], bool fRelay) { // Check for URI in argv bool fSent = false; for (int i = 1; i < argc; i++) { if (boost::algorithm::istarts_with(argv[i], "knolix:")) { const char *strURI = argv[i]; try { boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME); if (mq.try_send(strURI, strlen(strURI), 0)) fSent = true; else if (fRelay) break; } catch (boost::interprocess::interprocess_exception &ex) { // don't log the "file not found" exception, because that's normal for // the first start of the first instance if (ex.get_error_code() != boost::interprocess::not_found_error || !fRelay) { printf("main() - boost interprocess exception #%d: %s\n", ex.get_error_code(), ex.what()); break; } } } } return fSent; } void ipcScanRelay(int argc, char *argv[]) { if (ipcScanCmd(argc, argv, true)) exit(0); } static void ipcThread(void* pArg) { // Make this thread recognisable as the GUI-IPC thread RenameThread("knolix-gui-ipc"); try { ipcThread2(pArg); } catch (std::exception& e) { PrintExceptionContinue(&e, "ipcThread()"); } catch (...) { PrintExceptionContinue(NULL, "ipcThread()"); } printf("ipcThread exited\n"); } static void ipcThread2(void* pArg) { printf("ipcThread started\n"); message_queue* mq = (message_queue*)pArg; char buffer[MAX_URI_LENGTH + 1] = ""; size_t nSize = 0; unsigned int nPriority = 0; while (true) { ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(100); if (mq->timed_receive(&buffer, sizeof(buffer), nSize, nPriority, d)) { uiInterface.ThreadSafeHandleURI(std::string(buffer, nSize)); MilliSleep(1000); } if (fShutdown) break; } // Remove message queue message_queue::remove(BITCOINURI_QUEUE_NAME); // Cleanup allocated memory delete mq; } void ipcInit(int argc, char *argv[]) { message_queue* mq = NULL; char buffer[MAX_URI_LENGTH + 1] = ""; size_t nSize = 0; unsigned int nPriority = 0; try { mq = new message_queue(open_or_create, BITCOINURI_QUEUE_NAME, 2, MAX_URI_LENGTH); // Make sure we don't lose any bitcoin: URIs for (int i = 0; i < 2; i++) { ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(1); if (mq->timed_receive(&buffer, sizeof(buffer), nSize, nPriority, d)) { uiInterface.ThreadSafeHandleURI(std::string(buffer, nSize)); } else break; } // Make sure only one bitcoin instance is listening message_queue::remove(BITCOINURI_QUEUE_NAME); delete mq; mq = new message_queue(open_or_create, BITCOINURI_QUEUE_NAME, 2, MAX_URI_LENGTH); } catch (interprocess_exception &ex) { printf("ipcInit() - boost interprocess exception #%d: %s\n", ex.get_error_code(), ex.what()); return; } if (!NewThread(ipcThread, mq)) { delete mq; return; } ipcScanCmd(argc, argv, false); } #endif
[ "root@vultr.guest" ]
root@vultr.guest
ffda3bcce262a7a05644b6b68cd67f4389861c91
bc655b33bc631f108dccd62f870d5b4de51c74d9
/Client/Client.hpp
47bf399d221ebe1dc700aeb99e293a7c9ef3c187
[]
no_license
nandee95/ZombieGame
c21dfe5c923ed969d35fed300ab3c277220eb305
a01d22150d1625f6fe4571cabbda09054b8d0478
refs/heads/master
2020-05-29T21:07:49.943818
2019-05-30T08:25:33
2019-05-30T08:25:33
189,371,184
0
0
null
null
null
null
UTF-8
C++
false
false
2,160
hpp
#pragma once #include "../System/State.hpp" #include "../System/CfgFile.hpp" #include "../Client/Chat.hpp" #include "../Client/Wind.hpp" #include "../Server/Protocol.hpp" #include "../System/ResourceManager.hpp" #include "../Client/Level.hpp" #include "../System/Window.hpp" #include "../Physics/Physics.hpp" #include "../Overlays/Debug.hpp" #include "../Entities/Tree.hpp" #include "../Entities/ParticleEmitter.hpp" #include "../Entities/Grass.hpp" #include "../Inventory/Inventory.hpp" #include "../Client/Player.hpp" #include <unordered_map> #include <thread> #include <mutex> using namespace client; struct Vec2iHash { size_t operator () (const sf::Vector2i& vec) const { return vec.x * 10000 + vec.y; } }; class Client : public State { protected: ResourceManager resMg; sf::TcpSocket server; std::unique_ptr<Chat> chat; bool exitFlag = false; std::thread physicsThread; std::shared_ptr<client::LocalPlayer> player; sf::Clock timer; sf::Time lastFrame; Physics physics; sf::View view; bool showDebug = false; std::unique_ptr<DebugOverlay> debugScreen; sf::RenderTexture target; std::multimap<float, std::shared_ptr<client::Entity>> entities; Wind wind; std::thread reporterThread,listenerThread; std::map<int, std::shared_ptr<client::RemotePlayer>> remotePlayers; std::vector<std::shared_ptr<Inventory>> inventories; bool inventory = false; ChunkResources chunkMg; std::unordered_map<const sf::Vector2i, client::Chunk,Vec2iHash> chunks; sf::Vector2i lastChunk=sf::Vector2i(-5125,-15672); std::mutex mu; public: Window& window; Client(Window& window,CfgFile& cfg); ~Client(); void Listener(); virtual void event(sf::Event& e); virtual void update(); virtual void draw(sf::RenderTarget& _target); void Reporter(); bool isChunkLoaded(sf::Vector2i chunk); void sendPacket(sf::Packet& packet); void registerEntity(std::shared_ptr<client::Entity> entity); void destroyEntity(std::shared_ptr<client::Entity> entity); const bool AABBintersectionOptimized(const sf::FloatRect& rect1, const sf::FloatRect& rect2); };
[ "noreply@github.com" ]
noreply@github.com
43348c46fdf46d111b2d040bac18150b4c362beb
a2835f69393d56c3eef1454e0e8ef6d542701088
/ch03ex/A1031.cpp
0219c8a33bdfb67c689c82b81af6b5e3d2846476
[]
no_license
PiFtch/PAT
1656614922c2f1128c591e348f2eb5d41951afb2
683eab8dc96f9615544ec00ce214628896b5b248
refs/heads/master
2020-04-07T22:17:18.098697
2018-11-23T01:06:49
2018-11-23T01:06:49
158,763,197
0
0
null
null
null
null
UTF-8
C++
false
false
450
cpp
#include <cstdio> #include <cstring> int main() { char str[85]; scanf("%s", str); int len = strlen(str); int n1 = (len + 2) / 3, n2 = len - 2 * n1 + 2; for (int i = 0; i < n1-1; i++) { printf("%c", str[i]); for (int j = 0; j < n2 - 2; j++) printf(" "); printf("%c\n", str[len - i - 1]); } for (int i = n1 - 1; i < n1 + n2 -1; i++) { printf("%c", str[i]); } }
[ "piftch@126.com" ]
piftch@126.com
cde3d31a1a11bfa77e55462eb4f9e11199cd68b4
ad273708d98b1f73b3855cc4317bca2e56456d15
/aws-cpp-sdk-kms/source/model/ConnectionStateType.cpp
14768e334e84737eb61d3aaa1967e7e65cf9393e
[ "MIT", "Apache-2.0", "JSON" ]
permissive
novaquark/aws-sdk-cpp
b390f2e29f86f629f9efcf41c4990169b91f4f47
a0969508545bec9ae2864c9e1e2bb9aff109f90c
refs/heads/master
2022-08-28T18:28:12.742810
2020-05-27T15:46:18
2020-05-27T15:46:18
267,351,721
1
0
Apache-2.0
2020-05-27T15:08:16
2020-05-27T15:08:15
null
UTF-8
C++
false
false
3,370
cpp
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/kms/model/ConnectionStateType.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace KMS { namespace Model { namespace ConnectionStateTypeMapper { static const int CONNECTED_HASH = HashingUtils::HashString("CONNECTED"); static const int CONNECTING_HASH = HashingUtils::HashString("CONNECTING"); static const int FAILED_HASH = HashingUtils::HashString("FAILED"); static const int DISCONNECTED_HASH = HashingUtils::HashString("DISCONNECTED"); static const int DISCONNECTING_HASH = HashingUtils::HashString("DISCONNECTING"); ConnectionStateType GetConnectionStateTypeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == CONNECTED_HASH) { return ConnectionStateType::CONNECTED; } else if (hashCode == CONNECTING_HASH) { return ConnectionStateType::CONNECTING; } else if (hashCode == FAILED_HASH) { return ConnectionStateType::FAILED; } else if (hashCode == DISCONNECTED_HASH) { return ConnectionStateType::DISCONNECTED; } else if (hashCode == DISCONNECTING_HASH) { return ConnectionStateType::DISCONNECTING; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<ConnectionStateType>(hashCode); } return ConnectionStateType::NOT_SET; } Aws::String GetNameForConnectionStateType(ConnectionStateType enumValue) { switch(enumValue) { case ConnectionStateType::CONNECTED: return "CONNECTED"; case ConnectionStateType::CONNECTING: return "CONNECTING"; case ConnectionStateType::FAILED: return "FAILED"; case ConnectionStateType::DISCONNECTED: return "DISCONNECTED"; case ConnectionStateType::DISCONNECTING: return "DISCONNECTING"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace ConnectionStateTypeMapper } // namespace Model } // namespace KMS } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
a8475365f100808b3250d6485028b7c4eb01877f
45bf672454afe49b3a370e2a10f6f263837f61fd
/7segments0to9/7segments0to9.ino
21e804714e8b8e0dc4908e7d7af74d910a5243e6
[]
no_license
BCRCO/arduino-projects-collection-a
14665c98cb932f85f221e46f67a66dcc0627ad17
1cb197a6b5045a0e379ef1fced308da5e4d99611
refs/heads/main
2023-04-19T11:55:40.011335
2021-05-07T21:47:20
2021-05-07T21:47:20
365,358,996
0
0
null
null
null
null
UTF-8
C++
false
false
467
ino
#include "SevSeg.h" //BCR SevSeg sevseg; void setup(){ byte ND = 1; byte DP[] = {}; byte segmentPins[] = {13, 12, 11, 10, 9, 8, 7, 6}; bool R = true; byte HC = COMMON_ANODE; sevseg.begin(HC, ND, DP, segmentPins, R); sevseg.setBrightness(90); //Max } void loop(){ for(int i = 0; i < 10; i++){ sevseg.setNumber(i, i%2); delay(1500); //Time sevseg.refreshDisplay(); } }
[ "noreply@github.com" ]
noreply@github.com
95aad1953086598661e102debc9fab08ac36a483
fda4841612e5734e4c72ab6e7fd92ff2420f8a59
/CC/octlong20/test.cpp
dc49e825a857fafae6962fde0a16a6298b603877
[]
no_license
Cybertron3/competitive
ef980be2a0c584f2cd785b202713a593ae26da44
9e6ef05865485c42b319182eaab325ca5150d5a1
refs/heads/master
2021-08-02T07:07:00.942252
2021-07-30T23:50:33
2021-07-30T23:50:33
181,389,615
1
0
null
null
null
null
UTF-8
C++
false
false
3,454
cpp
#include<bits/stdc++.h> using namespace std; using ll = long long ; using pii = pair<int , int>; using pll = pair<ll,ll>; //pairs #define ss second #define ff first // vectors #define sz(x) (int)(x).size() #define all(x) begin(x), end(x) #define rall(x) (x).rbegin(), (x).rend() #define sor(x) sort(all(x)) #define rsz resize #define ins insert #define ft front() #define bk back() #define pf push_front #define pb push_back #define eb emplace_back #define lb lower_bound #define ub upper_bound // loops #define FOR(i,a,b) for (int i = (a); i < (b); ++i) #define F0R(i,a) FOR(i,0,a) #define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i) #define R0F(i,a) ROF(i,0,a) #define trav(a,x) for (auto& a: x) const int N = 1e5 + 10 , mod = 1000000007; //helper funcs ll cdiv(ll a, ll b) { return a/b+((a^b)>0&&a%b); } // divide a by b rounded up ll fdiv(ll a, ll b) { return a/b-((a^b)<0&&a%b); } // divide a by b rounded down bool power(int n,int count){ int ans = 1; while(count--){ ans*=2; } if(ans == n){ return true; }else{ return false; } } std::vector<int> sethia(int n){ std::vector<int> v; ll temp = n; ll count = 0; while(temp>1){ // 2 1 0 temp/=2; count++; } // count--; ll k = 0; if(power(n,count)){ // cout << "-1 " << endl; v.pb(-1); return v; }else{ if(n>=3){ // cout << "2 3 1 "; v.pb(2); v.pb(3); v.pb(1); ll i; k = 4; for(i=4;i<=n;i++){ if(k == i){ k = k*2; // cout << (i+1) << " " << i << " "; v.pb(i+1); v.pb(i); i+=1; }else{ // cout << i << " "; v.pb(i); } } }else if(n ==2){ // cout << "-1 "; v.pb(-1); } else if(n == 1){ // cout << "1" ; v.pb(1); } } // cout << endl; return v; } std::vector<int> solve(ll n){ std::vector<int> v; if(n == 1){ // cout << "1\n"; v.pb(1); return v; } ll p = n; while(p > 1){ if(p%2 == 0 ){ p /= 2; } else{ break; } } if(p == 1){ // cout << "-1\n"; v.pb(-1); return v; } v.pb(2); v.pb(3); v.pb(1); p = 4; ll num = 4; while(p <= n){ v.pb(p+1); v.pb(p); FOR(i,p+2,min(n+1 , 2*p)){ v.pb(i); } p *= 2; } return v; // trav(t , v)cout << t << " "; // cout << "\n"; } int main(){ ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); /* #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif */ int t = 1; // cin >> t; while(t <= N){ std::vector<int> ans1 = solve(t); std::vector<int> ans2 = sethia(t); if(sz(ans1) != sz(ans2)){ cout << t << "\n"; return 0; } FOR(i,0,sz(ans1)){ if(ans1[i] != ans2[i]){ cout << t << "\n"; return 0; } } cout << t << " OK\n" ; } return 0; }
[ "18ucs110@lnmiit.ac.in" ]
18ucs110@lnmiit.ac.in
eb79a4756ec8b9d8e57953c0922fdb56813ad92f
23d0eef2d251d7b615e727be5f7c364724be9b46
/Equa.h
7f176f2d7426434abebb990e8a057a677e7543ea
[]
no_license
1ovNemo/Equa
6a795dc7f35cd7af0ff2b747ec84f4f9337d53d3
8d8479253ebdcb0a3a9cfc48d0f418f1a647a098
refs/heads/master
2020-06-11T03:55:03.910572
2016-12-13T12:02:39
2016-12-13T12:02:39
76,010,194
0
0
null
null
null
null
UTF-8
C++
false
false
677
h
#ifndef EQUA_H #define EQUA_H #include <cmath> #include <ostream> class Equa { public: Equa(); Equa(double, double, double); void solve(); double getResult(); void setData(double, double, double); friend void informationAlerts(Equa); friend std::ostream& operator<<(std::ostream& out, const Equa& com); void setX(double X); void setZ(double Z); void setY(double Y); double getX() const; double getY() const; double getZ() const; double getT() const; private: double X; double Y; double Z; double T; }; #endif // EQUA_H
[ "vitali.kysilov.9@gmail.com" ]
vitali.kysilov.9@gmail.com
abcbaa2fbd80d2f72fa0ad46c2fc31b5708c5044
ac41d2ccb549dc09ed34e5c0f4da403509abb5c3
/test/expressions/MatrixVectorTerms.hpp
6e8eef10c492314e3079fcd36d9742d0cb4d1caa
[ "MIT" ]
permissive
spraetor/amdis2
c65b530dabd087d922d616bfaf9d53f4c8d5e3c4
53c45c81a65752a8fafbb54f9ae6724a86639dcd
refs/heads/master
2020-12-24T15:51:03.069002
2016-03-06T14:42:53
2016-03-06T14:42:53
39,136,073
2
0
null
null
null
null
UTF-8
C++
false
false
7,642
hpp
#pragma once // AMDiS includes #include "expressions/FunctorTerm.hpp" #include "expressions/TermConcepts.hpp" #include "matrix_vector/MatrixVectorOperations.hpp" /// Macro that generates a unary (vector) functor. /** * \p NAME Name of the class. * \p DEGREE Expression in 'd0' that gives the polynomial degree, with * 'd0' the degree of the argument passed to the functor. * \p FCT Name of a unary c++-function that represents the functor. */ #define AMDIS_MAKE_VECTOR_FUNCTOR( NAME, DEGREE, FCT ) \ struct NAME \ { \ constexpr int getDegree(int d0) const \ { \ return DEGREE ; \ } \ template <class T> \ auto operator()(T const& t) const RETURNS \ ( \ FCT( t ) \ ) \ }; namespace AMDiS { namespace functors { AMDIS_MAKE_VECTOR_FUNCTOR( TwoNorm, 2*d0+1, two_norm ) AMDIS_MAKE_VECTOR_FUNCTOR( OneNorm, d0, one_norm ) AMDIS_MAKE_VECTOR_FUNCTOR( UnaryDot, 2*d0, unary_dot ) AMDIS_MAKE_VECTOR_FUNCTOR( Sum, d0, sum ) AMDIS_MAKE_VECTOR_FUNCTOR( Mean, d0, mean ) AMDIS_MAKE_VECTOR_FUNCTOR( Prod, d0*d0*d0, prod ) AMDIS_MAKE_VECTOR_FUNCTOR( Max, d0, AMDiS::max ) AMDIS_MAKE_VECTOR_FUNCTOR( AbsMax, d0, AMDiS::abs_max ) AMDIS_MAKE_VECTOR_FUNCTOR( Min, d0, AMDiS::min ) AMDIS_MAKE_VECTOR_FUNCTOR( AbsMin, d0, AMDiS::abs_min ) /// Convert a vector to a diagonal matrix and extract the diagonal of /// a matrix and store it in a vector. // struct Diagonal // { // constexpr int getDegree(int d0) const // { // return d0; // } // // private: // // Extract the diagonal of a matrix // template <class M, class V = detail::MatrixToVector<M>> // static typename V::type eval(M const& m, tag::matrix) // { // using value_type = Value_t<M>; // typename V::type vector(num_rows(m), value_type{0}); // for (size_t i = 0; i < num_rows(m); ++i) // vector(i) = m(i,i); // return vector; // } // // // Generate a diagonal matrix // template <class V, class M = detail::VectorToMatrix<V>> // static typename M::type eval(V const& v, tag::vector) // { // using value_type = Value_t<V>; // typename M::type matrix(size(v), size(v), value_type{0}); // for (size_t i = 0; i < size(v); ++i) // matrix(i,i) = v(i); // return matrix; // } // // public: // template <class T> // auto operator()(T&& t) const RETURNS // ( // Diagonal::eval(std::forward<T>(t), // typename traits::category<Decay_t<T>>::tag()) // ) // }; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - struct Dot { constexpr int getDegree(int d0, int d1) const { return d0+d1; } template <class T1, class T2> auto operator()(T1&& t1, T2&& t2) const RETURNS ( dot(std::forward<T1>(t1), std::forward<T2>(t2)) ) }; // struct Cross // { // constexpr int getDegree(int d0, int d1) const // { // return d0+d1; // } // // template <class Vec1, class Vec2, // class = Requires_t<and_<traits::is_vector<Vec1>, traits::is_vector<Vec2>>>> // Assign_t<Vec1> operator()(Vec1 const& v1, Vec2 const& v2) const // { // using size_type = Size_t<traits::category<Vec1>>; // Assign_t<Vec1> result(size(v1)); // // TEST_EXIT_DBG( size(v1) == 3 && size(v1) == size(v2), "cross: inkompatible sizes!\n"); // // for (size_type i = 0; i < size(v1); ++i) // { // size_type k = (i+1) % 3, l = (i+2) % 3; // result(i) = v1(k) * v2(l) - v1(l) * v2(k); // } // return result; // } // }; // struct Outer // { // constexpr int getDegree(int d0, int d1) const // { // return d0+d1; // } // // template <class Vec1, class Vec2, // class = Requires_t<and_<traits::is_vector<Vec1>, traits::is_vector<Vec2>>>> // VectorToMatrix_t<Vec1> operator()(Vec1 const& v1, Vec2 const& v2) const // { // using size_type1 = Size_t<traits::category<Vec1>>; // using size_type2 = Size_t<traits::category<Vec2>>; // VectorToMatrix_t<Vec1> result(size(v1), size(v2)); // // for (size_type1 i = 0; i < size(v1); ++i) // { // for (size_type2 j = 0; j < size(v2); ++j) // { // result(i,j) = v1(i) * v2(j); // } // } // return result; // } // }; struct Distance { constexpr int getDegree(int d0, int d1) const { return d0+d1+1; } template <class T1, class T2> auto operator()(T1&& t1, T2&& t2) const RETURNS ( distance(std::forward<T1>(t1), std::forward<T2>(t2)) ) }; } // --------------------------------------------------------------------------- template <class T> FunctorTerm<functors::OneNorm, T> inline one_norm(VectorTerm<T> const& t) { return {t.sub()}; } template <class T> FunctorTerm<functors::TwoNorm, T> inline two_norm(VectorTerm<T> const& t) { return {t.sub()}; } template <class T> FunctorTerm<functors::TwoNorm, T> inline frobenius_norm(MatrixTerm<T> const& t) { return {t.sub()}; } template <class T> FunctorTerm<functors::TwoNorm, T> inline norm(VectorTerm<T> const& t) { return {t.sub()}; } template <class T> FunctorTerm<functors::TwoNorm, T> inline norm(MatrixTerm<T> const& t) { return {t.sub()}; } template <class T> FunctorTerm<functors::UnaryDot, T> inline unary_dot(VectorTerm<T> const& t) { return {t.sub()}; } // template <class T> // FunctorTerm<functors::Diagonal, T> // inline diag(VectorTerm<T> const& t) // { // return {t.sub()}; // } // template <class T> // FunctorTerm<functors::Diagonal, T> // inline diag(MatrixTerm<T> const& t) // { // return {t.sub()}; // } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <class T1, class T2> requires::Term<FunctorTerm<functors::Dot, ToTerm_t<T1>, ToTerm_t<T2>>, T1, T2> inline dot(T1&& t1, T2&& t2) { return {toTerm(std::forward<T1>(t1)), toTerm(std::forward<T2>(t2))}; } // template <class T1, class T2> // requires::Term<FunctorTerm<functors::Cross, ToTerm_t<T1>, ToTerm_t<T2>>, T1, T2> // inline cross(T1&& t1, T2&& t2) // { // return {toTerm(std::forward<T1>(t1)), toTerm(std::forward<T2>(t2))}; // } // template <class T1, class T2> // requires::Term<FunctorTerm<functors::Outer, ToTerm_t<T1>, ToTerm_t<T2>>, T1, T2> // inline outer(T1&& t1, T2&& t2) // { // return {toTerm(std::forward<T1>(t1)), toTerm(std::forward<T2>(t2))}; // } template <class T1, class T2> requires::Term<FunctorTerm<functors::Distance, ToTerm_t<T1>, ToTerm_t<T2>>, T1, T2> inline distance(T1&& t1, T2&& t2) { return {toTerm(std::forward<T1>(t1)), toTerm(std::forward<T2>(t2))}; } } // end namespace AMDiS
[ "simon.praetorius@tu-dresden.de" ]
simon.praetorius@tu-dresden.de
ecb152fee4f35c17e3c2bb8a473b7beab9bd4527
23a405404b3238e9d7bb24f852f69d3f558183d9
/吉田学園情報ビジネス専門学校 竹内亘/06_ハッカソン春/開発環境/写真泥棒/camera.cpp
aae06493f45f4ba18649b62e6b200c485a556c0d
[]
no_license
takeuchiwataru/TakeuchiWataru_QMAX
fa25283aa90bcedb75dd650613d8d828a3f8f81a
cd5d6f75ca258f58df934d40a8ea238976e7c69d
refs/heads/master
2022-02-07T16:33:12.052935
2019-06-12T04:32:08
2019-06-12T04:32:08
191,302,573
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
14,729
cpp
//============================================================================= // // カメラ処理 [camera.cpp] // Author : Hodaka Niwa // //============================================================================= #include "camera.h" #include "player.h" #include "input.h" //***************************************************************************** // マクロ定義 //***************************************************************************** #define CAMERA_ANGEL_VIEW (45.0f) // カメラの画角 #define CAMERA_MOVE (15.0f) // カメラの移動量 #define AROUND_SPEED (0.02f) // 回り込み速度初期値 #define AROUND_TIME (50) // 回り込み待ち時間初期値 //***************************************************************************** // グローバル変数 //***************************************************************************** Camera g_camera; // カメラの情報 //============================================================================= // カメラの初期化処理 //============================================================================= void InitCamera(void) { g_camera.posR = D3DXVECTOR3(0.0f, 0.0f, 0.0f); // 現在の注視点を初期化 g_camera.posVDest = D3DXVECTOR3(0.0f, 0.0f, 0.0f); // 目的の視点を初期化 g_camera.posRDest = D3DXVECTOR3(0.0f, 0.0f, 0.0f); // 目的の注視点を初期化 g_camera.posVAdd = D3DXVECTOR3(0.0f, 0.0f, 0.0f); // 加える分の視点を初期化 g_camera.posRAdd = D3DXVECTOR3(0.0f, 100.0f, 0.0f); // 加える分の注視点を初期化 g_camera.vecU = D3DXVECTOR3(0.0f, 1.0f, 0.0f); // ベクトルを初期化 g_camera.rot = D3DXVECTOR3(0.0f, 0.0f, 0.0f); // 現在の向きを初期化 g_camera.rotDest = D3DXVECTOR3(0.0f, 0.0f, 0.0f); // 目的の向きを初期化 g_camera.state = CAMERASTATE_NORMAL; // 通常の状態に g_camera.fWaraparoundSpeed = AROUND_SPEED; // 回り込み速度を初期化 g_camera.nWaraparoundTime = AROUND_TIME; // 回り込み待ち時間を初期化 g_camera.nCounterTime = 0; // 待ち時間カウンターを初期化 g_camera.posVAdd = D3DXVECTOR3(0.0f, 0.0f, 0.0f); // 目的の視点座標を初期化 g_camera.posRAdd = D3DXVECTOR3(0.0f, 0.0f, 0.0f); // 目的の注視点座標を初期化 g_camera.fLength = D3DXVECTOR3(0.0f, 0.0f, 0.0f); // 距離を初期化 // ビューポートの設定 g_camera.ViewPort.X = 0; // x座標左端 g_camera.ViewPort.Y = 0; // y座標上端 g_camera.ViewPort.Width = SCREEN_WIDTH; // x座標右端 g_camera.ViewPort.Height = SCREEN_HEIGHT; // x座標下端 g_camera.ViewPort.MinZ = 0.0f; // 手前 g_camera.ViewPort.MaxZ = 1.0f; // 奥側 if (GetMode() == MODE_RANKING) {// ランキング画面だったら g_camera.fLength.x = 200; g_camera.fLength.y = 30; g_camera.fLength.z = 200; } else if (GetMode() == MODE_TITLE) {// タイトル画面だったら g_camera.fLength.x = 200; g_camera.fLength.y = 50; g_camera.fLength.z = 200; g_camera.posR = D3DXVECTOR3(0.0f, 300.0f, 0.0f); // 現在の注視点を初期化 } else if(GetMode() == MODE_GAME) {// それ以外の画面だったら g_camera.fLength.x = 600; g_camera.fLength.y = 300; g_camera.fLength.z = 600; } else if (GetMode() == MODE_TUTORIAL) {// それ以外の画面だったら g_camera.fLength.x = 200; g_camera.fLength.y = 0; g_camera.fLength.z = 200; g_camera.posR = D3DXVECTOR3(0.0f, 240.0f,800.0f); // 現在の注視点を初期化 } g_camera.posV.x = g_camera.posR.x + sinf(g_camera.rot.y) * g_camera.fLength.x; g_camera.posV.y = g_camera.posR.y + cosf(g_camera.rot.y) * g_camera.fLength.y; g_camera.posV.z = g_camera.posR.z + cosf(g_camera.rot.y) * g_camera.fLength.z; } //============================================================================= // カメラの終了処理 //============================================================================= void UninitCamera(void) { } //============================================================================= // カメラの更新処理 //============================================================================= void UpdateCamera(void) { // デバック用カメラ操作の処理 #if 0 //----------------- // 視点移動 //----------------- if (GetKeyboardPress(DIK_LEFT) == true) {// Aキーが押された if (GetKeyboardPress(DIK_UP) == true) {// 同時にWキーが押された g_camera.posV.x -= sinf(g_camera.rot.y + (D3DX_PI * 0.75f)) * CAMERA_MOVE; g_camera.posV.z -= cosf(g_camera.rot.y + (D3DX_PI * 0.75f)) * CAMERA_MOVE; } else if (GetKeyboardPress(DIK_DOWN) == true) {// 同時にSキーが押された g_camera.posV.x -= sinf(g_camera.rot.y + (D3DX_PI * 0.25f)) * CAMERA_MOVE; g_camera.posV.z -= cosf(g_camera.rot.y + (D3DX_PI * 0.25f)) * CAMERA_MOVE; } else {// 同時に何も押されていない g_camera.posV.x -= sinf(g_camera.rot.y + (D3DX_PI * 0.5f)) * CAMERA_MOVE; g_camera.posV.z -= cosf(g_camera.rot.y + (D3DX_PI * 0.5f)) * CAMERA_MOVE; } g_camera.posR.x = g_camera.posV.x + sinf(g_camera.rot.y) * g_camera.fLength.x; g_camera.posR.z = g_camera.posV.z + cosf(g_camera.rot.y) * g_camera.fLength.z; } else if (GetKeyboardPress(DIK_RIGHT) == true) {// Dキーが押された if (GetKeyboardPress(DIK_UP) == true) {// 同時にWキーが押された g_camera.posV.x -= sinf(g_camera.rot.y - (D3DX_PI * 0.75f)) * CAMERA_MOVE; g_camera.posV.z -= cosf(g_camera.rot.y - (D3DX_PI * 0.75f)) * CAMERA_MOVE; } else if (GetKeyboardPress(DIK_DOWN) == true) {// 同時にSキーが押された g_camera.posV.x -= sinf(g_camera.rot.y - (D3DX_PI * 0.25f)) * CAMERA_MOVE; g_camera.posV.z -= cosf(g_camera.rot.y - (D3DX_PI * 0.25f)) * CAMERA_MOVE; } else {// 同時に何も押されていない g_camera.posV.x -= sinf(g_camera.rot.y - (D3DX_PI * 0.5f)) * CAMERA_MOVE; g_camera.posV.z -= cosf(g_camera.rot.y - (D3DX_PI * 0.5f)) * CAMERA_MOVE; } g_camera.posR.x = g_camera.posV.x + sinf(g_camera.rot.y) * g_camera.fLength.x; g_camera.posR.z = g_camera.posV.z + cosf(g_camera.rot.y) * g_camera.fLength.z; } else if (GetKeyboardPress(DIK_UP) == true) {// Wキーが押された g_camera.posV.x += sinf(g_camera.rot.y) * CAMERA_MOVE; g_camera.posV.z += cosf(g_camera.rot.y) * CAMERA_MOVE; g_camera.posR.x = g_camera.posV.x + sinf(g_camera.rot.y) * g_camera.fLength.x; g_camera.posR.z = g_camera.posV.z + cosf(g_camera.rot.y) * g_camera.fLength.z; } else if (GetKeyboardPress(DIK_DOWN) == true) {// Sキーが押された g_camera.posV.x -= sinf(g_camera.rot.y) * CAMERA_MOVE; g_camera.posV.z -= cosf(g_camera.rot.y) * CAMERA_MOVE; g_camera.posR.x = g_camera.posV.x + sinf(g_camera.rot.y) * g_camera.fLength.x; g_camera.posR.z = g_camera.posV.z + cosf(g_camera.rot.y) * g_camera.fLength.z; } //----------------- // 視点旋回 //----------------- if (GetKeyboardPress(DIK_Z) == true) {// Zキーが押された g_camera.rot.y -= D3DX_PI / 120; if (g_camera.rot.y <= -D3DX_PI) { g_camera.rot.y = D3DX_PI; } g_camera.posV.x = g_camera.posR.x - sinf(g_camera.rot.y) * g_camera.fLength.x; g_camera.posV.z = g_camera.posR.z - cosf(g_camera.rot.y) * g_camera.fLength.z; } if (GetKeyboardPress(DIK_C) == true) {// Cキーが押された g_camera.rot.y += D3DX_PI / 120; if (g_camera.rot.y >= D3DX_PI) { g_camera.rot.y = -D3DX_PI; } g_camera.posV.x = g_camera.posR.x - sinf(g_camera.rot.y) * g_camera.fLength.x; g_camera.posV.z = g_camera.posR.z - cosf(g_camera.rot.y) * g_camera.fLength.z; } //----------------- // 注視点旋回 //----------------- if (GetKeyboardPress(DIK_Q) == true) {// Qキーが押された g_camera.rot.y -= D3DX_PI / 120; if (g_camera.rot.y < -D3DX_PI) { g_camera.rot.y = D3DX_PI; } g_camera.posR.x = g_camera.posV.x + sinf(g_camera.rot.y) * g_camera.fLength.x; g_camera.posR.z = g_camera.posV.z + cosf(g_camera.rot.y) * g_camera.fLength.z; } if (GetKeyboardPress(DIK_E) == true) {// Eキーが押された g_camera.rot.y += D3DX_PI / 120; if (g_camera.rot.y >= D3DX_PI) { g_camera.rot.y = -D3DX_PI; } g_camera.posR.x = g_camera.posV.x + sinf(g_camera.rot.y) * g_camera.fLength.x; g_camera.posR.z = g_camera.posV.z + cosf(g_camera.rot.y) * g_camera.fLength.z; } //----------------- // カメラリセット //----------------- if (GetKeyboardPress(DIK_G) == true) {// SPACEキーが押された g_camera.posV = D3DXVECTOR3(0.0f, 130.0f, -250.0f); g_camera.posR = D3DXVECTOR3(0.0f, 00.0f, 0.0f); g_camera.rot = D3DXVECTOR3(0.0f, 0.0f, 0.0f); g_camera.rot.y = atan2f(g_camera.posV.x - g_camera.posR.x, g_camera.posV.z - g_camera.posR.z); } //----------------- // 注視点上昇下降 //----------------- if (GetKeyboardPress(DIK_T) == true) {// Tキーが押された g_camera.posR.y += 3.5f; } if (GetKeyboardPress(DIK_B) == true) {// Bキーが押された g_camera.posR.y -= 3.5f; } //----------------- // 視点上昇下降 //----------------- if (GetKeyboardPress(DIK_Y) == true) {// Yキーが押された g_camera.posV.y += 3.5f; } if (GetKeyboardPress(DIK_N) == true) {// Nキーが押された g_camera.posV.y -= 3.5f; } //------------------------ // ズームイン ズームアウト //------------------------ if (GetKeyboardPress(DIK_U) == true) {// Uキーが押された if (g_camera.fLength.z >= 60) { g_camera.fLength.z -= 2.0f; } } if (GetKeyboardPress(DIK_M) == true) {// Mキーが押された if (g_camera.fLength.z <= 350) { g_camera.fLength.z += 2.0f; } } #endif if (GetMode() == MODE_TITLE) {// タイトル画面だったら g_camera.rot.y += D3DX_PI / 1200; if (g_camera.rot.y >= D3DX_PI) { g_camera.rot.y = -D3DX_PI; } g_camera.posV.x = g_camera.posR.x + sinf(g_camera.rot.y) * g_camera.fLength.x; g_camera.posV.z = g_camera.posR.z + cosf(g_camera.rot.y) * g_camera.fLength.z; } else if (GetMode() == MODE_RANKING) {// ランキング画面だったら g_camera.rot.y -= D3DX_PI / 1200; if (g_camera.rot.y <= -D3DX_PI) { g_camera.rot.y = D3DX_PI; } g_camera.posV.x = g_camera.posR.x + sinf(g_camera.rot.y) * g_camera.fLength.x; g_camera.posV.z = g_camera.posR.z + cosf(g_camera.rot.y) * g_camera.fLength.z; } else if (GetMode() == MODE_GAME) {// ゲーム画面だったら Player *pPlayer = GetPlayer(); // プレイヤーの取得 // 視点設定 g_camera.posVDest.x = (pPlayer->pos.x + (5.0f * pPlayer->move.x)) - sinf(g_camera.rot.y) * g_camera.fLength.x; // 目的の視点を設定 g_camera.posVDest.y = (pPlayer->pos.y + g_camera.posVAdd.y) + cosf(0.0f) * g_camera.fLength.y / 1.7f; // 目的の視点を設定 g_camera.posVDest.z = (pPlayer->pos.z + (5.0f * pPlayer->move.z)) - cosf(g_camera.rot.y) * g_camera.fLength.z; // 目的の視点を設定 // 注視点設定 g_camera.posRDest.x = (pPlayer->pos.x + (5.0f * pPlayer->move.x)) + sinf(pPlayer->rot.y + D3DX_PI) * ((pPlayer->move.x * pPlayer->move.x) + ((pPlayer->move.x * pPlayer->move.x))); // 目的の注視点を設定 g_camera.posRDest.y = (pPlayer->pos.y + g_camera.posRAdd.y + 40.0f); // 目的の注視点を設定 g_camera.posRDest.z = (pPlayer->pos.z + (5.0f * pPlayer->move.z)) + cosf(pPlayer->rot.y + D3DX_PI) * ((pPlayer->move.z * pPlayer->move.z) + ((pPlayer->move.z * pPlayer->move.z))); // 目的の注視点を設定 g_camera.posV.x += (g_camera.posVDest.x - g_camera.posV.x) * 0.5f; // 現在の視点を設定 g_camera.posV.y += (g_camera.posVDest.y - g_camera.posV.y) * 0.5f; // 現在の視点を設定 g_camera.posV.z += (g_camera.posVDest.z - g_camera.posV.z) * 0.5f; // 現在の視点を設定 g_camera.posR.x += (g_camera.posRDest.x - g_camera.posR.x) * 0.30f; // 現在の注視点を設定 g_camera.posR.y += (g_camera.posRDest.y - g_camera.posR.y) * 0.30f; // 現在の注視点を設定 g_camera.posR.z += (g_camera.posRDest.z - g_camera.posR.z) * 0.30f; // 現在の注視点を設定 if (GetKeyboardPress(DIK_RIGHT) == true || GetJoyPadPress(DIJS_BUTTON_16, 0) == TRUE) {// 左アナログスティックが右に倒された g_camera.rot.y += D3DX_PI / 120; if (g_camera.rot.y >= D3DX_PI) { g_camera.rot.y = -D3DX_PI; } } else if (GetKeyboardPress(DIK_LEFT) == true || GetJoyPadPress(DIJS_BUTTON_17, 0) == TRUE) {// 左アナログスティックが左に倒された g_camera.rot.y -= D3DX_PI / 120; if (g_camera.rot.y <= -D3DX_PI) { g_camera.rot.y = D3DX_PI; } } else if (GetKeyboardPress(DIK_UP) == true || GetJoyPadPress(DIJS_BUTTON_14, 0) == TRUE) {// 左アナログスティックが上に倒された if (g_camera.fLength.y >= 70.0f) {// 視点が既定の値まで下がっていない g_camera.fLength.y -= 3.0f; } } else if (GetKeyboardPress(DIK_DOWN) == true || GetJoyPadPress(DIJS_BUTTON_15, 0) == TRUE) {// 左アナログスティックが下に倒された if (g_camera.fLength.y <= 320.0f) {// 視点が既定の値まで上がっていない g_camera.fLength.y += 3.0f; } } } } //============================================================================= // カメラの設定処理 //============================================================================= void SetCamera(void) { LPDIRECT3DDEVICE9 pDevice = GetDevice(); // デバイスの取得 // ビューポートの設定 pDevice->SetViewport(&g_camera.ViewPort); // プロジェクションマトリックスの初期化 D3DXMatrixIdentity(&g_camera.mtxProjection); // プロジェクションマトリックスを作成 D3DXMatrixPerspectiveFovLH(&g_camera.mtxProjection, D3DXToRadian(CAMERA_ANGEL_VIEW), (float)SCREEN_WIDTH / (float)SCREEN_HEIGHT, 10.0f, 50000.0f); // プロジェクションマトリックスの設定 pDevice->SetTransform(D3DTS_PROJECTION, &g_camera.mtxProjection); // ビューマトリックスの初期化 D3DXMatrixIdentity(&g_camera.mtxView); // ビューマトリックスを作成 D3DXMatrixLookAtLH(&g_camera.mtxView, &g_camera.posV, &g_camera.posR, &g_camera.vecU); // ビューマトリックスの設定 pDevice->SetTransform(D3DTS_VIEW, &g_camera.mtxView); } //============================================================================= // カメラの取得 //============================================================================= Camera *GetCamera(void) { return &g_camera; }
[ "jb2017024@stu.yoshida-g.ac.jp" ]
jb2017024@stu.yoshida-g.ac.jp
db09f2c52593cf24b2678469c92c73bdd0baaca4
9030ce2789a58888904d0c50c21591632eddffd7
/SDK/ARKSurvivalEvolved_PrimalItemStructure_CropPlot_Large_parameters.hpp
b0fd2bfdf934c1efe7e06b09ac48c5a2b2946cc4
[ "MIT" ]
permissive
2bite/ARK-SDK
8ce93f504b2e3bd4f8e7ced184980b13f127b7bf
ce1f4906ccf82ed38518558c0163c4f92f5f7b14
refs/heads/master
2022-09-19T06:28:20.076298
2022-09-03T17:21:00
2022-09-03T17:21:00
232,411,353
14
5
null
null
null
null
UTF-8
C++
false
false
806
hpp
#pragma once // ARKSurvivalEvolved (332.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_PrimalItemStructure_CropPlot_Large_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function PrimalItemStructure_CropPlot_Large.PrimalItemStructure_CropPlot_Large_C.ExecuteUbergraph_PrimalItemStructure_CropPlot_Large struct UPrimalItemStructure_CropPlot_Large_C_ExecuteUbergraph_PrimalItemStructure_CropPlot_Large_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
3e50eb204670a82a43ffed6cc7d91643028f48f4
dd6147bf9433298a64bbceb7fdccaa4cc477fba6
/8382/kobenko/lab1-7/DarkArmy.h
fd02c148561c03200056ce5093dfc0b326444910
[]
no_license
moevm/oop
64a89677879341a3e8e91ba6d719ab598dcabb49
faffa7e14003b13c658ccf8853d6189b51ee30e6
refs/heads/master
2023-03-16T15:48:35.226647
2020-06-08T16:16:31
2020-06-08T16:16:31
85,785,460
42
304
null
2023-03-06T23:46:08
2017-03-22T04:37:01
C++
UTF-8
C++
false
false
990
h
// // Created by vlad on 01.06.2020. // #ifndef UNTITLED_DARKARMY_H #define UNTITLED_DARKARMY_H #include <iostream> #include "Infantry.h" #include "Cavalry.h" #include "Archers.h" class DarkArcher:public Archers { public: int x; int y; char type; int health; public: DarkArcher(); int MoveUnits(int, int); int AttackUnits(char** , char ); void getDamage(int); private: int attack; int armor; }; class DarkInfantry:public Infantry { public: int x; int y; char type; int health; public: DarkInfantry(); int MoveUnits(int, int) ; int AttackUnits(char** , char); void getDamage(int); private: int attack; int armor; }; class DarkCavalry:public Cavalry { public: int x; int y; char type; int health; public: DarkCavalry(); int MoveUnits(int, int) ; int AttackUnits(char** , char ); void getDamage(int); private: int attack; int armor; }; #endif //UNTITLED_DARKARMY_H
[ "vladkobenko348@gmail.com" ]
vladkobenko348@gmail.com
e5dc4e9b647feee94085f0e78082723b00ab72ae
d5d649d358b72cc2c634b88945521fb1aefd4dd8
/Rocklights/src/InterpGen.h
0c6ed7d3a414517e2a5d30f42fb008be3904b2bd
[]
no_license
damonseeley/electroland_repos
70dd6cad4361616d7d2bf8a10139ba949bed0a57
63b06daf1a5bc2d66e3fc80bf44a867796e7028b
refs/heads/master
2021-01-10T12:43:13.110448
2014-10-13T18:59:40
2014-10-13T18:59:40
50,899,790
0
0
null
null
null
null
UTF-8
C++
false
false
302
h
#ifndef __INTERPGEN_H__ #define __INTERPGEN_H__ class InterpGen { float deltaPerUSec; float perc; public: bool isRunning; bool wasStarted; InterpGen(); void start(int timeUSecs); void reset(); // sets was started to false float update(int deltaT); } ; #endif
[ "emendelowitz@38cd337d-7a19-44a1-8cca-49443be78b0d" ]
emendelowitz@38cd337d-7a19-44a1-8cca-49443be78b0d
656bf2cc45395a6e71c099eb9d45f517221cc99c
69ce284757e3c57798a6cee551c441d30ccc97b7
/practice_c++/18.4.Addition_Of_RationalNumber.cpp
aad2009f30b3e235c9b47bf572dbbbd7cf83a64e
[]
no_license
HarshitVerma1/Competetive-programming-with-C-plus-plus
76a6dc0ea6bb3897558fdd8ba34ae0ddec476ef5
8de3d6e2d71fd6ad7c968f88a9b0cdb856d24cb5
refs/heads/master
2023-03-28T01:24:15.418693
2021-03-27T07:19:59
2021-03-27T07:19:59
278,889,420
1
0
null
null
null
null
UTF-8
C++
false
false
817
cpp
#include <iostream> using namespace std; class RationalNumber { private: int p, q; public: RationalNumber(int p = 0, int q = 0) { this->p = p; this->q = q; } RationalNumber Add(RationalNumber R2) { RationalNumber temp; temp.p = p * (R2.q) + q * (R2.p); temp.q = q * (R2.q); display(temp); return temp; } void display(RationalNumber R1) { cout << "Addition is : " << R1.p << "/" << R1.q << endl; } }; int main() { int m, n, o, p; cout << "Enter the p and q part of 1st Rational number repectively : " << endl; cin >> m >> n; cout << "Enter the p and q part of 2nd Rational number repectively : " << endl; cin >> o >> p; RationalNumber r1(m, n), r2(o, p), result; result = r1.Add(r2); }
[ "terminator@pop-os.localdomain" ]
terminator@pop-os.localdomain
9c13e9ca313f13cbcce39328533c209ff7471910
b152993f856e9598e67d046e6243350dcd622abe
/services/network/shared_dictionary/shared_dictionary_storage_in_memory.cc
bcf44fa322762d83429536e2654baae25e9ae093
[ "BSD-3-Clause" ]
permissive
monad-one/chromium
10e4a585fbd2b66b55d5afcba72c50a872708238
691b5c9cfa2a4fc38643509932e62438dc3a0d54
refs/heads/main
2023-05-14T07:36:48.032727
2023-05-10T13:47:48
2023-05-10T13:47:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,122
cc
// Copyright 2023 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/network/shared_dictionary/shared_dictionary_storage_in_memory.h" #include "base/logging.h" #include "base/strings/pattern.h" #include "base/strings/string_util.h" #include "net/base/io_buffer.h" #include "services/network/shared_dictionary/shared_dictionary_in_memory.h" #include "services/network/shared_dictionary/shared_dictionary_writer_in_memory.h" #include "url/scheme_host_port.h" namespace network { SharedDictionaryStorageInMemory::SharedDictionaryStorageInMemory( base::ScopedClosureRunner on_deleted_closure_runner) : on_deleted_closure_runner_(std::move(on_deleted_closure_runner)) {} SharedDictionaryStorageInMemory::~SharedDictionaryStorageInMemory() = default; std::unique_ptr<SharedDictionary> SharedDictionaryStorageInMemory::GetDictionary(const GURL& url) { auto it = dictionary_info_map_.find(url::SchemeHostPort(url)); if (it == dictionary_info_map_.end()) { return nullptr; } const DictionaryInfo* info = nullptr; size_t mached_path_size = 0; // TODO(crbug.com/1413922): If there are multiple matching dictionaries, this // method currently returns the dictionary with the longest path pattern. But // we should have a detailed description about `best-matching` in the spec. for (const auto& item : it->second) { // TODO(crbug.com/1413922): base::MatchPattern() is treating '?' in the // pattern as an wildcard. We need to introduce a new flag in // base::MatchPattern() to treat '?' as a normal character. // TODO(crbug.com/1413922): Need to check the expiration of the dictionary. // TODO(crbug.com/1413922): Need support path expansion for relative paths. if ((item.first.size() > mached_path_size) && base::MatchPattern(url.path(), item.first)) { mached_path_size = item.first.size(); info = &item.second; } } if (!info) { return nullptr; } return std::make_unique<SharedDictionaryInMemory>(info->data(), info->size(), info->hash()); } scoped_refptr<SharedDictionaryWriter> SharedDictionaryStorageInMemory::CreateWriter(const GURL& url, base::Time response_time, base::TimeDelta expiration, const std::string& match) { return base::MakeRefCounted<SharedDictionaryWriterInMemory>(base::BindOnce( &SharedDictionaryStorageInMemory::OnDictionaryWritten, weak_factory_.GetWeakPtr(), url, response_time, expiration, match)); } void SharedDictionaryStorageInMemory::OnDictionaryWritten( const GURL& url, base::Time response_time, base::TimeDelta expiration, const std::string& match, SharedDictionaryWriterInMemory::Result result, scoped_refptr<net::IOBuffer> data, size_t size, const net::SHA256HashValue& hash) { if (result != SharedDictionaryWriterInMemory::Result::kSuccess) { return; } dictionary_info_map_[url::SchemeHostPort(url)].insert(std::make_pair( match, DictionaryInfo(url, response_time, expiration, match, data, size, hash))); } SharedDictionaryStorageInMemory::DictionaryInfo::DictionaryInfo( const GURL& url, base::Time response_time, base::TimeDelta expiration, const std::string& match, scoped_refptr<net::IOBuffer> data, size_t size, const net::SHA256HashValue& hash) : url_(url), response_time_(response_time), expiration_(expiration), match_(match), data_(std::move(data)), size_(size), hash_(hash) {} SharedDictionaryStorageInMemory::DictionaryInfo::DictionaryInfo( DictionaryInfo&& other) = default; SharedDictionaryStorageInMemory::DictionaryInfo& SharedDictionaryStorageInMemory::DictionaryInfo::operator=( SharedDictionaryStorageInMemory::DictionaryInfo&& other) = default; SharedDictionaryStorageInMemory::DictionaryInfo::~DictionaryInfo() = default; } // namespace network
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
1cdab4be8e5a2fbd4d9cf66e321d3e9084e5755d
eb7f316efd1567d00dcd3de8e59e58b42c4a8932
/opencv-3.3.0/build/modules/videoio/opencv_test_videoio_pch_dephelp.cxx
57f9b0a8dfe8efc38cf4e3566e53369949e47d0b
[ "BSD-3-Clause" ]
permissive
cstarkjp/CV3_RPiZero_Stretch
914ba7fa9a2fe5fdc5c24955b0fbc267e4044bd7
bbd4424e94cba78541b5aa44f69ce1c2aa888773
refs/heads/master
2021-07-24T22:40:20.988930
2017-11-06T06:18:27
2017-11-06T06:18:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
137
cxx
#include "/home/pi/Packages/opencv-3.3.0/modules/videoio/test/test_precomp.hpp" int testfunction(); int testfunction() { return 0; }
[ "cstarkjp@gmail.com" ]
cstarkjp@gmail.com
635d4e9246e0cc4027f59d2fe43b0cbcd0f9f307
52bd63e7c5f1730485e80008181dde512ad1a313
/pstade/egg/pipable.hpp
d9cd0c9daa5b61a9e76b29c113721ff55a07f9d4
[ "BSL-1.0" ]
permissive
fpelliccioni/pstade
09df122a8cada6bd809512507b1eff9543d22cb1
ffb52f2bf187c8f001588e6c5c007a4a3aa9a5e8
refs/heads/master
2016-09-11T02:06:23.972758
2013-09-26T15:13:05
2013-09-26T15:13:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,391
hpp
#ifndef PSTADE_EGG_PIPABLE_HPP #define PSTADE_EGG_PIPABLE_HPP #include "./detail/prefix.hpp" // PStade.Egg // // Copyright Shunsuke Sogame 2007. // 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 <pstade/pod_constant.hpp> #include "./by_perfect.hpp" #include "./by_value.hpp" #include "./detail/little_pipable_result.hpp" #include "./generator.hpp" #include "./use_brace2.hpp" namespace pstade { namespace egg { template<class Base, class Strategy = by_perfect> struct result_of_pipable { typedef function<detail::little_pipable_result<Base, Strategy>, Strategy> type; }; #define PSTADE_EGG_PIPABLE_L { { #define PSTADE_EGG_PIPABLE_R , {} } } #define PSTADE_EGG_PIPABLE(F) PSTADE_EGG_PIPABLE_L F PSTADE_EGG_PIPABLE_R typedef generator< result_of_pipable< deduce<boost::mpl::_1, as_value> >::type, boost::use_default, use_brace2, by_value >::type T_pipable; PSTADE_POD_CONSTANT((T_pipable), pipable) = PSTADE_EGG_GENERATOR; // If msvc fails to find operator|, use this as super type. using detail::lookup_pipable_operator; } } // namespace pstade::egg #endif
[ "fpelliccioni@gmail.com" ]
fpelliccioni@gmail.com
bafd2285ea886f8776dd026113f57ef08bab15fb
e223d16fd7230428f0b1470e6bd896e22515270c
/Trabajo Practico 3/include/Animal.h
a98435a85a0acf51e4dc0465a07cf522278c6e40
[]
no_license
virtualoutsider/POO
f5852b08e6a303772b9f390f5ed51784daaa29ac
7fd78e28fb974ec2a6edf2676687b2c53b46a238
refs/heads/master
2023-08-29T18:16:07.881042
2021-10-27T17:33:48
2021-10-27T17:33:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
602
h
#ifndef ANIMAL_H #define ANIMAL_H #include <string> using namespace std; class Animal { public: Animal(int _numero,string _nombre,int _edad); virtual ~Animal(); virtual void mostrar()=0; virtual float getPeso(); virtual int getHuevos(); virtual float getVel(); string getNom(){return nombre;} int getNum() { return numero; } int getEdad(){return edad;} string gettypeid(); protected: int numero; string nombre; int edad; private: }; #endif // ANIMAL_H
[ "pauligrp@gmail.com" ]
pauligrp@gmail.com
bb175ee730d0bb9fafeaa4f791364440dd0b4923
b7d183e63d640e42d201557ca81d11dcc36b199d
/Client/acm_gui (BackUp)/loginwindow.cpp
884c654b437ae0cf7399be1dc21507c6442080e2
[]
no_license
ksmail13/SimpleAlgorithmJudge
529823a6510e6a2f09a92de85093d62db4de25bb
53b83435af7019bcfe6886d208d36a48e1b4912d
refs/heads/master
2020-05-17T00:10:36.321504
2015-06-08T03:50:21
2015-06-08T03:50:21
30,504,556
0
0
null
null
null
null
UTF-8
C++
false
false
2,455
cpp
#include "loginwindow.h" //#include "ui_loginwindow.h" #include <QMessageBox> #include <stdio.h> #include <string> using namespace std; LoginWindow::LoginWindow(QWidget *parent) : QMainWindow(parent)//, ui(new Ui::MainWindow) { // ui->setupUi(this); //LoginWidget mywidget; setFixedSize(600, 400); setWindowTitle("Login"); widget_login = new LoginWidget; setCentralWidget(widget_login); show(); connect(widget_login->button_help, SIGNAL(clicked()), this, SLOT(helpBox())); connect(widget_login->button_login, SIGNAL(clicked()), this, SLOT(sendLoginInfo())); } //void MainWindow:: void LoginWindow::sendLoginInfo() { QMessageBox msgBox; id = widget_login->getID(); pw = widget_login->getPW(); ip = widget_login->getIP(); QString str; if(id == NULL) { str = "Please Enter Your ID"; } else if(pw == NULL) { str = "Please Enter Your PW"; } else if(ip == NULL) { str = "Please Enter Correct IP"; } else { socket_manager = new SocketManager(); if(socket_manager->setIP(ip) == false) { str = "Set IP Error"; } else { str = QString("id : %1\npw : %2\nip : %3").arg(id, pw, ip); Json::Value root; Json::Value ID; root["ID"] = id.toStdString().c_str(); Json::Value PW; root["PW"] = pw.toStdString().c_str(); socket_manager->send(root); newWidget(); } } msgBox.setText(str); msgBox.exec(); } void LoginWindow::helpBox() { QMessageBox msgBox; msgBox.setText("This is help Box about IP address"); msgBox.exec(); } void LoginWindow::newWidget() { this->takeCentralWidget(); setWindowTitle("Welcome " + id + "!"); widget_main = new MainWidget; connect(widget_main->button_logout, SIGNAL(clicked()), this, SLOT(logOut())); setCentralWidget(widget_main); //thread create for receive } void LoginWindow::logOut() { this->takeCentralWidget(); //close socket socket_manager->close(); setWindowTitle("Login"); widget_login = new LoginWidget; connect(widget_login->button_help, SIGNAL(clicked()), this, SLOT(helpBox())); connect(widget_login->button_login, SIGNAL(clicked()), this, SLOT(sendLoginInfo())); setCentralWidget(widget_login); } LoginWindow::~LoginWindow() { //delete ui; }
[ "wlstjd7375@gmail.com" ]
wlstjd7375@gmail.com
d23c9aaa6c7d4ac8e7d807c75c6ab361e783ed47
d5e43c17289866b9dc6c3ecca2527bdae172edf4
/Baekjoon/2986_Pascal.cpp
8071fdf6643e9582cb7ee427685b70d7625099bd
[]
no_license
skqoaudgh/Algorithm_studying
81dfc4a60c88b434863707bb841a18deb69adcab
61e49dc159ea4b591bd01b80f8a6a0fc96dd96c6
refs/heads/master
2021-07-11T23:36:58.333780
2020-06-15T06:38:58
2020-06-15T06:38:58
158,647,211
1
0
null
null
null
null
UTF-8
C++
false
false
182
cpp
#include <cstdio> int main() { int N,k=1,sum=0; scanf("%d",&N); for(int i=2; i*i<=N; i++) { if(N % i == 0) { k = N/i; break; } } printf("%d",N-k); return 0; }
[ "skqoaudgh2@hanmail.net" ]
skqoaudgh2@hanmail.net
cd6367388785cd20bd52c957f0f6688103c92163
2e1446d16fcec683cf2eb35600c6f9e2028b22af
/pdp8i/pynq_z2/sim/sim_main.cpp
82bf59f9b41f927c770191d96e0e4df95b4344a3
[]
no_license
drovak/verilogpdp
05204a294d0193185b2dae0c9daab6a13e6b1806
ae6e478d4ad7b854d98ed8677e8eb431f646dbb4
refs/heads/main
2023-09-01T10:23:09.766477
2023-08-28T04:30:13
2023-08-28T04:30:13
341,054,166
7
1
null
2023-08-28T04:30:14
2021-02-22T02:13:08
Verilog
UTF-8
C++
false
false
2,532
cpp
#include <memory> #include <verilated.h> #include "verilated_vcd_c.h" #include "Vtop.h" vluint64_t main_time = 0; double sc_time_stamp() { return main_time; // Note does conversion to real, to match SystemC } int main(int argc, char** argv, char** env) { if (false && argc && argv && env) {} // Set debug level, 0 is off, 9 is highest presently used // May be overridden by commandArgs Verilated::debug(0); // Randomization reset policy // May be overridden by commandArgs Verilated::randReset(2); // Verilator must compute traced signals Verilated::traceEverOn(true); // Pass arguments so Verilated code can see them, e.g. $value$plusargs // This needs to be called before you create any model Verilated::commandArgs(argc, argv); // Construct the Verilated model, from Vtop.h generated from Verilating "top.v" // Using unique_ptr is similar to "Vtop* top = new Vtop" then deleting at end const std::unique_ptr<Vtop> top{new Vtop}; #if VM_TRACE VerilatedVcdC* tfp = nullptr; const char* flag = Verilated::commandArgsPlusMatch("trace"); if (flag && 0 == strcmp(flag, "+trace")) { tfp = new VerilatedVcdC; top->trace(tfp, 99); tfp->open("logs/trace.vcd"); } #endif top->clk = 0; top->rst = 1; top->ion = 1; top->pause = 0; top->run = 1; top->inst_and = 1; top->inst_tad = 0; top->inst_isz = 0; top->inst_dca = 0; top->inst_jms = 0; top->inst_jmp = 0; top->inst_iot = 0; top->inst_opr = 0; top->state_fetch = 1; top->state_defer = 0; top->state_execute = 0; top->state_word_count = 0; top->state_cur_addr = 0; top->state_break = 0; top->dataf = 5; top->instf = 2; top->pc = 01234; top->ma = 04321; top->mb = 05555; top->lac = 016243; top->sc = 013; top->mq = 02222; VL_PRINTF("running...\n"); for (int i = 0; i < 10000000; i++) { if (main_time > 20) top->rst = 0; for (int clk = 0; clk < 2; clk++) { main_time += 5; #if VM_TRACE if (tfp) tfp->dump(10*i + 5*clk); #endif top->clk = !top->clk; if (top->sw_row == 6) top->col = 03777; else if (top->sw_row == 5) top->col = 05777; else if (top->sw_row == 3) top->col = 06777; else top->col = 07777; top->eval(); } } #if VM_TRACE if (tfp) tfp->close(); #endif // Final model cleanup top->final(); exit(0); }
[ "kylevowen@gmail.com" ]
kylevowen@gmail.com
a6814e7c1869dfc79812b46751656a05bab3ca47
7c0536baf5ca26447e91fb771a38baff0a2ef82b
/node.cpp
b43d518da0dc6241c13e5795d3612c7d0570f11c
[]
no_license
mlin9/SFML-Perceptron
efc2921ee7c9f1f490226b940d6245941bfaf48f
4b4101e6f32d7a494c6f2c584922f2c8f12036b6
refs/heads/master
2021-09-14T03:29:23.845616
2018-05-07T17:26:57
2018-05-07T17:26:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
746
cpp
#include "node.h" // Node-Based Feed-Forward Perceptron Demonstration // Information flow is unidirectional, no multithreading required. Node::Node() { learn_weight = 2.0; output = 0.0; entry = 0.0; init(); } void Node::learn(double error) { weight += learn_weight * error * entry; } void Node::input(double input) { output += input; entry = input; } void Node::transmit(Node &output_node) { output = output * weight; output_node.input(output); output = 0.0; } double Node::sum() { double temp = output; output = 0.0; return temp; } void Node::init() { //Generate random weight between -1 and 1 std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<> dis(-1.0, 0.0); weight = dis(gen); }
[ "michaellindocs@gmail.com" ]
michaellindocs@gmail.com
d6bd0eaa404ad43d34e7f89460229f6865b1e3e2
de24ce80cd112eee86845a99997afba4b5c7e8af
/11.9/Package头文件/Package头文件.cpp
7d277b1456102b56e80efd5109dde2d0f2d6c44a
[]
no_license
JDFjdf/ji_dongfang
2e25ea65f650dc15e59452f38311bb6d3e635500
6f5e9251c55b1c117e33c50018011523099b4d86
refs/heads/master
2020-04-02T14:36:29.943037
2019-04-21T15:08:41
2019-04-21T15:08:41
154,531,418
0
0
null
null
null
null
UTF-8
C++
false
false
1,496
cpp
#ifndef PACKAGE_H #define PACKAGE_H #include <string> using namespace std; class Package { public: Package( const string &, const string &, const string &, const string &, int, const string &, const string &, const string &, const string &, int, double, double ); void setSenderName( const string & ); string getSenderName() const; void setSenderAddress( const string & ); string getSenderAddress() const; void setSenderCity( const string & ); string getSenderCity() const; void setSenderState( const string & ); string getSenderState() const; void setSenderZIP( int ); int getSenderZIP() const; void setRecipientName( const string & ); string getRecipientName() const; void setRecipientAddress( const string & ); string getRecipientAddress() const; void setRecipientCity( const string & ); string getRecipientCity() const; void setRecipientState( const string & ); string getRecipientState() const; void setRecipientZIP( int ); int getRecipientZIP() const; void setWeight( double ); double getWeight() const; void setCostPerOunce( double ); double getCostPerOunce() const; double calculateCost() const; private: string senderName; string senderAddress; string senderCity; string senderState; int senderZIP; string recipientName; string recipientAddress; string recipientCity; string recipientState; int recipientZIP; double weight; double costPerOunce; }; #endif
[ "1041943228@qq.com" ]
1041943228@qq.com
17d1953a6d277a596ff5d168db568b66b07b3fb5
9b7a92f4288d2b5e6885fe2ea5188b74edd651e1
/Pac-Man Recreation/Phaze/PhazeEngine/3rdPartyLibs/Box2D/src/b2CollideEdge.cpp
c51bdd95768da3c4da3ecb501430fb201a79a427
[]
no_license
surefireace/Pac-Man-Recreation
bced7ec750905ca63442b01ffaaf72c6f4ab09e3
5cad3cf260836f6deaeca8d09e69cad6ebc3f8f8
refs/heads/master
2020-08-05T11:25:54.614101
2019-10-20T22:54:53
2019-10-20T22:54:53
212,482,117
0
0
null
null
null
null
UTF-8
C++
false
false
15,533
cpp
/* * Copyright (c) 2007-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include "b2Collision.h" #include "b2CircleShape.h" #include "b2EdgeShape.h" #include "b2PolygonShape.h" // Compute contact points for edge versus circle. // This accounts for edge connectivity. void b2CollideEdgeAndCircle(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, const b2CircleShape* circleB, const b2Transform& xfB) { manifold->pointCount = 0; // Compute circle in frame of edge b2Vec2 Q = b2MulT(xfA, b2Mul(xfB, circleB->m_p)); b2Vec2 A = edgeA->m_vertex1, B = edgeA->m_vertex2; b2Vec2 e = B - A; // Barycentric coordinates float32 u = b2Dot(e, B - Q); float32 v = b2Dot(e, Q - A); float32 radius = edgeA->m_radius + circleB->m_radius; b2ContactFeature cf; cf.indexB = 0; cf.typeB = b2ContactFeature::e_vertex; // Region A if (v <= 0.0f) { b2Vec2 P = A; b2Vec2 d = Q - P; float32 dd = b2Dot(d, d); if (dd > radius * radius) { return; } // Is there an edge connected to A? if (edgeA->m_hasVertex0) { b2Vec2 A1 = edgeA->m_vertex0; b2Vec2 B1 = A; b2Vec2 e1 = B1 - A1; float32 u1 = b2Dot(e1, B1 - Q); // Is the circle in Region AB of the previous edge? if (u1 > 0.0f) { return; } } cf.indexA = 0; cf.typeA = b2ContactFeature::e_vertex; manifold->pointCount = 1; manifold->type = b2Manifold::e_circles; manifold->localNormal.SetZero(); manifold->localPoint = P; manifold->points[0].id.key = 0; manifold->points[0].id.cf = cf; manifold->points[0].localPoint = circleB->m_p; return; } // Region B if (u <= 0.0f) { b2Vec2 P = B; b2Vec2 d = Q - P; float32 dd = b2Dot(d, d); if (dd > radius * radius) { return; } // Is there an edge connected to B? if (edgeA->m_hasVertex3) { b2Vec2 B2 = edgeA->m_vertex3; b2Vec2 A2 = B; b2Vec2 e2 = B2 - A2; float32 v2 = b2Dot(e2, Q - A2); // Is the circle in Region AB of the next edge? if (v2 > 0.0f) { return; } } cf.indexA = 1; cf.typeA = b2ContactFeature::e_vertex; manifold->pointCount = 1; manifold->type = b2Manifold::e_circles; manifold->localNormal.SetZero(); manifold->localPoint = P; manifold->points[0].id.key = 0; manifold->points[0].id.cf = cf; manifold->points[0].localPoint = circleB->m_p; return; } // Region AB float32 den = b2Dot(e, e); b2Assert(den > 0.0f); b2Vec2 P = (1.0f / den) * (u * A + v * B); b2Vec2 d = Q - P; float32 dd = b2Dot(d, d); if (dd > radius * radius) { return; } b2Vec2 n(-e.y, e.x); if (b2Dot(n, Q - A) < 0.0f) { n.Set(-n.x, -n.y); } n.Normalize(); cf.indexA = 0; cf.typeA = b2ContactFeature::e_face; manifold->pointCount = 1; manifold->type = b2Manifold::e_faceA; manifold->localNormal = n; manifold->localPoint = A; manifold->points[0].id.key = 0; manifold->points[0].id.cf = cf; manifold->points[0].localPoint = circleB->m_p; } // This structure is used to keep track of the best separating axis. struct b2EPAxis { enum Type { e_unknown, e_edgeA, e_edgeB }; Type type; int32 index; float32 separation; }; // This holds polygon B expressed in frame A. struct b2TempPolygon { b2Vec2 vertices[b2_maxPolygonVertices]; b2Vec2 normals[b2_maxPolygonVertices]; int32 count; }; // Reference face used for clipping struct b2ReferenceFace { int32 i1, i2; b2Vec2 v1, v2; b2Vec2 normal; b2Vec2 sideNormal1; float32 sideOffset1; b2Vec2 sideNormal2; float32 sideOffset2; }; // This class collides and edge and a polygon, taking into account edge adjacency. struct b2EPCollider { void Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, const b2PolygonShape* polygonB, const b2Transform& xfB); b2EPAxis ComputeEdgeSeparation(); b2EPAxis ComputePolygonSeparation(); enum VertexType { e_isolated, e_concave, e_convex }; b2TempPolygon m_polygonB; b2Transform m_xf; b2Vec2 m_centroidB; b2Vec2 m_v0, m_v1, m_v2, m_v3; b2Vec2 m_normal0, m_normal1, m_normal2; b2Vec2 m_normal; VertexType m_type1, m_type2; b2Vec2 m_lowerLimit, m_upperLimit; float32 m_radius; bool m_front; }; // Algorithm: // 1. Classify v1 and v2 // 2. Classify polygon centroid as front or back // 3. Flip normal if necessary // 4. Initialize normal range to [-pi, pi] about face normal // 5. Adjust normal range according to adjacent edges // 6. Visit each separating axes, only accept axes within the range // 7. Return if _any_ axis indicates separation // 8. Clip void b2EPCollider::Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, const b2PolygonShape* polygonB, const b2Transform& xfB) { m_xf = b2MulT(xfA, xfB); m_centroidB = b2Mul(m_xf, polygonB->m_centroid); m_v0 = edgeA->m_vertex0; m_v1 = edgeA->m_vertex1; m_v2 = edgeA->m_vertex2; m_v3 = edgeA->m_vertex3; bool hasVertex0 = edgeA->m_hasVertex0; bool hasVertex3 = edgeA->m_hasVertex3; b2Vec2 edge1 = m_v2 - m_v1; edge1.Normalize(); m_normal1.Set(edge1.y, -edge1.x); float32 offset1 = b2Dot(m_normal1, m_centroidB - m_v1); float32 offset0 = 0.0f, offset2 = 0.0f; bool convex1 = false, convex2 = false; // Is there a preceding edge? if (hasVertex0) { b2Vec2 edge0 = m_v1 - m_v0; edge0.Normalize(); m_normal0.Set(edge0.y, -edge0.x); convex1 = b2Cross(edge0, edge1) >= 0.0f; offset0 = b2Dot(m_normal0, m_centroidB - m_v0); } // Is there a following edge? if (hasVertex3) { b2Vec2 edge2 = m_v3 - m_v2; edge2.Normalize(); m_normal2.Set(edge2.y, -edge2.x); convex2 = b2Cross(edge1, edge2) > 0.0f; offset2 = b2Dot(m_normal2, m_centroidB - m_v2); } // Determine front or back collision. Determine collision normal limits. if (hasVertex0 && hasVertex3) { if (convex1 && convex2) { m_front = offset0 >= 0.0f || offset1 >= 0.0f || offset2 >= 0.0f; if (m_front) { m_normal = m_normal1; m_lowerLimit = m_normal0; m_upperLimit = m_normal2; } else { m_normal = -m_normal1; m_lowerLimit = -m_normal1; m_upperLimit = -m_normal1; } } else if (convex1) { m_front = offset0 >= 0.0f || (offset1 >= 0.0f && offset2 >= 0.0f); if (m_front) { m_normal = m_normal1; m_lowerLimit = m_normal0; m_upperLimit = m_normal1; } else { m_normal = -m_normal1; m_lowerLimit = -m_normal2; m_upperLimit = -m_normal1; } } else if (convex2) { m_front = offset2 >= 0.0f || (offset0 >= 0.0f && offset1 >= 0.0f); if (m_front) { m_normal = m_normal1; m_lowerLimit = m_normal1; m_upperLimit = m_normal2; } else { m_normal = -m_normal1; m_lowerLimit = -m_normal1; m_upperLimit = -m_normal0; } } else { m_front = offset0 >= 0.0f && offset1 >= 0.0f && offset2 >= 0.0f; if (m_front) { m_normal = m_normal1; m_lowerLimit = m_normal1; m_upperLimit = m_normal1; } else { m_normal = -m_normal1; m_lowerLimit = -m_normal2; m_upperLimit = -m_normal0; } } } else if (hasVertex0) { if (convex1) { m_front = offset0 >= 0.0f || offset1 >= 0.0f; if (m_front) { m_normal = m_normal1; m_lowerLimit = m_normal0; m_upperLimit = -m_normal1; } else { m_normal = -m_normal1; m_lowerLimit = m_normal1; m_upperLimit = -m_normal1; } } else { m_front = offset0 >= 0.0f && offset1 >= 0.0f; if (m_front) { m_normal = m_normal1; m_lowerLimit = m_normal1; m_upperLimit = -m_normal1; } else { m_normal = -m_normal1; m_lowerLimit = m_normal1; m_upperLimit = -m_normal0; } } } else if (hasVertex3) { if (convex2) { m_front = offset1 >= 0.0f || offset2 >= 0.0f; if (m_front) { m_normal = m_normal1; m_lowerLimit = -m_normal1; m_upperLimit = m_normal2; } else { m_normal = -m_normal1; m_lowerLimit = -m_normal1; m_upperLimit = m_normal1; } } else { m_front = offset1 >= 0.0f && offset2 >= 0.0f; if (m_front) { m_normal = m_normal1; m_lowerLimit = -m_normal1; m_upperLimit = m_normal1; } else { m_normal = -m_normal1; m_lowerLimit = -m_normal2; m_upperLimit = m_normal1; } } } else { m_front = offset1 >= 0.0f; if (m_front) { m_normal = m_normal1; m_lowerLimit = -m_normal1; m_upperLimit = -m_normal1; } else { m_normal = -m_normal1; m_lowerLimit = m_normal1; m_upperLimit = m_normal1; } } // Get polygonB in frameA m_polygonB.count = polygonB->m_count; for (int32 i = 0; i < polygonB->m_count; ++i) { m_polygonB.vertices[i] = b2Mul(m_xf, polygonB->m_vertices[i]); m_polygonB.normals[i] = b2Mul(m_xf.q, polygonB->m_normals[i]); } m_radius = polygonB->m_radius + edgeA->m_radius; manifold->pointCount = 0; b2EPAxis edgeAxis = ComputeEdgeSeparation(); // If no valid normal can be found than this edge should not collide. if (edgeAxis.type == b2EPAxis::e_unknown) { return; } if (edgeAxis.separation > m_radius) { return; } b2EPAxis polygonAxis = ComputePolygonSeparation(); if (polygonAxis.type != b2EPAxis::e_unknown && polygonAxis.separation > m_radius) { return; } // Use hysteresis for jitter reduction. const float32 k_relativeTol = 0.98f; const float32 k_absoluteTol = 0.001f; b2EPAxis primaryAxis; if (polygonAxis.type == b2EPAxis::e_unknown) { primaryAxis = edgeAxis; } else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol) { primaryAxis = polygonAxis; } else { primaryAxis = edgeAxis; } b2ClipVertex ie[2]; b2ReferenceFace rf; if (primaryAxis.type == b2EPAxis::e_edgeA) { manifold->type = b2Manifold::e_faceA; // Search for the polygon normal that is most anti-parallel to the edge normal. int32 bestIndex = 0; float32 bestValue = b2Dot(m_normal, m_polygonB.normals[0]); for (int32 i = 1; i < m_polygonB.count; ++i) { float32 value = b2Dot(m_normal, m_polygonB.normals[i]); if (value < bestValue) { bestValue = value; bestIndex = i; } } int32 i1 = bestIndex; int32 i2 = i1 + 1 < m_polygonB.count ? i1 + 1 : 0; ie[0].v = m_polygonB.vertices[i1]; ie[0].id.cf.indexA = 0; ie[0].id.cf.indexB = static_cast<uint8>(i1); ie[0].id.cf.typeA = b2ContactFeature::e_face; ie[0].id.cf.typeB = b2ContactFeature::e_vertex; ie[1].v = m_polygonB.vertices[i2]; ie[1].id.cf.indexA = 0; ie[1].id.cf.indexB = static_cast<uint8>(i2); ie[1].id.cf.typeA = b2ContactFeature::e_face; ie[1].id.cf.typeB = b2ContactFeature::e_vertex; if (m_front) { rf.i1 = 0; rf.i2 = 1; rf.v1 = m_v1; rf.v2 = m_v2; rf.normal = m_normal1; } else { rf.i1 = 1; rf.i2 = 0; rf.v1 = m_v2; rf.v2 = m_v1; rf.normal = -m_normal1; } } else { manifold->type = b2Manifold::e_faceB; ie[0].v = m_v1; ie[0].id.cf.indexA = 0; ie[0].id.cf.indexB = static_cast<uint8>(primaryAxis.index); ie[0].id.cf.typeA = b2ContactFeature::e_vertex; ie[0].id.cf.typeB = b2ContactFeature::e_face; ie[1].v = m_v2; ie[1].id.cf.indexA = 0; ie[1].id.cf.indexB = static_cast<uint8>(primaryAxis.index); ie[1].id.cf.typeA = b2ContactFeature::e_vertex; ie[1].id.cf.typeB = b2ContactFeature::e_face; rf.i1 = primaryAxis.index; rf.i2 = rf.i1 + 1 < m_polygonB.count ? rf.i1 + 1 : 0; rf.v1 = m_polygonB.vertices[rf.i1]; rf.v2 = m_polygonB.vertices[rf.i2]; rf.normal = m_polygonB.normals[rf.i1]; } rf.sideNormal1.Set(rf.normal.y, -rf.normal.x); rf.sideNormal2 = -rf.sideNormal1; rf.sideOffset1 = b2Dot(rf.sideNormal1, rf.v1); rf.sideOffset2 = b2Dot(rf.sideNormal2, rf.v2); // Clip incident edge against extruded edge1 side edges. b2ClipVertex clipPoints1[2]; b2ClipVertex clipPoints2[2]; int32 np; // Clip to box side 1 np = b2ClipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1); if (np < b2_maxManifoldPoints) { return; } // Clip to negative box side 1 np = b2ClipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2); if (np < b2_maxManifoldPoints) { return; } // Now clipPoints2 contains the clipped points. if (primaryAxis.type == b2EPAxis::e_edgeA) { manifold->localNormal = rf.normal; manifold->localPoint = rf.v1; } else { manifold->localNormal = polygonB->m_normals[rf.i1]; manifold->localPoint = polygonB->m_vertices[rf.i1]; } int32 pointCount = 0; for (int32 i = 0; i < b2_maxManifoldPoints; ++i) { float32 separation; separation = b2Dot(rf.normal, clipPoints2[i].v - rf.v1); if (separation <= m_radius) { b2ManifoldPoint* cp = manifold->points + pointCount; if (primaryAxis.type == b2EPAxis::e_edgeA) { cp->localPoint = b2MulT(m_xf, clipPoints2[i].v); cp->id = clipPoints2[i].id; } else { cp->localPoint = clipPoints2[i].v; cp->id.cf.typeA = clipPoints2[i].id.cf.typeB; cp->id.cf.typeB = clipPoints2[i].id.cf.typeA; cp->id.cf.indexA = clipPoints2[i].id.cf.indexB; cp->id.cf.indexB = clipPoints2[i].id.cf.indexA; } ++pointCount; } } manifold->pointCount = pointCount; } b2EPAxis b2EPCollider::ComputeEdgeSeparation() { b2EPAxis axis; axis.type = b2EPAxis::e_edgeA; axis.index = m_front ? 0 : 1; axis.separation = FLT_MAX; for (int32 i = 0; i < m_polygonB.count; ++i) { float32 s = b2Dot(m_normal, m_polygonB.vertices[i] - m_v1); if (s < axis.separation) { axis.separation = s; } } return axis; } b2EPAxis b2EPCollider::ComputePolygonSeparation() { b2EPAxis axis; axis.type = b2EPAxis::e_unknown; axis.index = -1; axis.separation = -FLT_MAX; b2Vec2 perp(-m_normal.y, m_normal.x); for (int32 i = 0; i < m_polygonB.count; ++i) { b2Vec2 n = -m_polygonB.normals[i]; float32 s1 = b2Dot(n, m_polygonB.vertices[i] - m_v1); float32 s2 = b2Dot(n, m_polygonB.vertices[i] - m_v2); float32 s = b2Min(s1, s2); if (s > m_radius) { // No collision axis.type = b2EPAxis::e_edgeB; axis.index = i; axis.separation = s; return axis; } // Adjacency if (b2Dot(n, perp) >= 0.0f) { if (b2Dot(n - m_upperLimit, m_normal) < -b2_angularSlop) { continue; } } else { if (b2Dot(n - m_lowerLimit, m_normal) < -b2_angularSlop) { continue; } } if (s > axis.separation) { axis.type = b2EPAxis::e_edgeB; axis.index = i; axis.separation = s; } } return axis; } void b2CollideEdgeAndPolygon( b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, const b2PolygonShape* polygonB, const b2Transform& xfB) { b2EPCollider collider; collider.Collide(manifold, edgeA, xfA, polygonB, xfB); }
[ "surefireace@hotmail.com" ]
surefireace@hotmail.com
79f8a660491088952709ed23d3b4e22496fbe97a
5adb78e2c8ffb17c95f5187db8aceaee59955709
/src/rpcblockchain.cpp
4bca61d8a9f95eafb48818b0d0dc7f8ea9b80b26
[ "MIT" ]
permissive
wmchain/wmc1
6b3da524e65eda17467cc6cf89275ab92cd8b6b6
b993266ddb5c027e5e301a39669556b02581f854
refs/heads/master
2020-03-30T14:42:18.252648
2018-10-02T22:27:12
2018-10-02T22:27:12
151,331,655
0
0
null
null
null
null
UTF-8
C++
false
false
45,501
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The Wmc Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "amount.h" #include "chain.h" #include "chainparams.h" #include "checkpoints.h" #include "coins.h" #include "consensus/validation.h" #include "main.h" #include "policy/policy.h" #include "primitives/transaction.h" #include "rpcserver.h" #include "streams.h" #include "sync.h" #include "txmempool.h" #include "util.h" #include "utilstrencodings.h" #include <stdint.h> #include <univalue.h> using namespace std; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry); void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex); double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (chainActive.Tip() == NULL) return 1.0; else blockindex = chainActive.Tip(); } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } UniValue blockheaderToJSON(const CBlockIndex* blockindex) { UniValue result(UniValue::VOBJ); result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", blockindex->nVersion)); result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex())); result.push_back(Pair("time", (int64_t)blockindex->nTime)); result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast())); result.push_back(Pair("nonce", (uint64_t)blockindex->nNonce)); result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex())); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); CBlockIndex *pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); return result; } UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false) { UniValue result(UniValue::VOBJ); result.push_back(Pair("hash", block.GetHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); UniValue txs(UniValue::VARR); BOOST_FOREACH(const CTransaction&tx, block.vtx) { if(txDetails) { UniValue objTx(UniValue::VOBJ); TxToJSON(tx, uint256(), objTx); txs.push_back(objTx); } else txs.push_back(tx.GetHash().GetHex()); } result.push_back(Pair("tx", txs)); result.push_back(Pair("time", block.GetBlockTime())); result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast())); result.push_back(Pair("nonce", (uint64_t)block.nNonce)); result.push_back(Pair("bits", strprintf("%08x", block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex())); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); CBlockIndex *pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); return result; } UniValue getblockcount(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockcount\n" "\nReturns the number of blocks in the longest block chain.\n" "\nResult:\n" "n (numeric) The current block count\n" "\nExamples:\n" + HelpExampleCli("getblockcount", "") + HelpExampleRpc("getblockcount", "") ); LOCK(cs_main); return chainActive.Height(); } UniValue getbestblockhash(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getbestblockhash\n" "\nReturns the hash of the best (tip) block in the longest block chain.\n" "\nResult\n" "\"hex\" (string) the block hash hex encoded\n" "\nExamples\n" + HelpExampleCli("getbestblockhash", "") + HelpExampleRpc("getbestblockhash", "") ); LOCK(cs_main); return chainActive.Tip()->GetBlockHash().GetHex(); } UniValue getdifficulty(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getdifficulty\n" "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n" "\nResult:\n" "n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n" "\nExamples:\n" + HelpExampleCli("getdifficulty", "") + HelpExampleRpc("getdifficulty", "") ); LOCK(cs_main); return GetDifficulty(); } UniValue mempoolToJSON(bool fVerbose = false) { if (fVerbose) { LOCK(mempool.cs); UniValue o(UniValue::VOBJ); BOOST_FOREACH(const CTxMemPoolEntry& e, mempool.mapTx) { const uint256& hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); info.push_back(Pair("size", (int)e.GetTxSize())); info.push_back(Pair("fee", ValueFromAmount(e.GetFee()))); info.push_back(Pair("modifiedfee", ValueFromAmount(e.GetModifiedFee()))); info.push_back(Pair("time", e.GetTime())); info.push_back(Pair("height", (int)e.GetHeight())); info.push_back(Pair("startingpriority", e.GetPriority(e.GetHeight()))); info.push_back(Pair("currentpriority", e.GetPriority(chainActive.Height()))); info.push_back(Pair("descendantcount", e.GetCountWithDescendants())); info.push_back(Pair("descendantsize", e.GetSizeWithDescendants())); info.push_back(Pair("descendantfees", e.GetModFeesWithDescendants())); const CTransaction& tx = e.GetTx(); set<string> setDepends; BOOST_FOREACH(const CTxIn& txin, tx.vin) { if (mempool.exists(txin.prevout.hash)) setDepends.insert(txin.prevout.hash.ToString()); } UniValue depends(UniValue::VARR); BOOST_FOREACH(const string& dep, setDepends) { depends.push_back(dep); } info.push_back(Pair("depends", depends)); o.push_back(Pair(hash.ToString(), info)); } return o; } else { vector<uint256> vtxid; mempool.queryHashes(vtxid); UniValue a(UniValue::VARR); BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } } UniValue getrawmempool(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getrawmempool ( verbose )\n" "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n" "\nArguments:\n" "1. verbose (boolean, optional, default=false) true for a json object, false for array of transaction ids\n" "\nResult: (for verbose = false):\n" "[ (json array of string)\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" "]\n" "\nResult: (for verbose = true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" " \"size\" : n, (numeric) transaction size in bytes\n" " \"fee\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + "\n" " \"modifiedfee\" : n, (numeric) transaction fee with fee deltas used for mining priority\n" " \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n" " \"height\" : n, (numeric) block height when transaction entered pool\n" " \"startingpriority\" : n, (numeric) priority when transaction entered pool\n" " \"currentpriority\" : n, (numeric) transaction priority now\n" " \"descendantcount\" : n, (numeric) number of in-mempool descendant transactions (including this one)\n" " \"descendantsize\" : n, (numeric) size of in-mempool descendants (including this one)\n" " \"descendantfees\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one)\n" " \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n" " \"transactionid\", (string) parent transaction id\n" " ... ]\n" " }, ...\n" "}\n" "\nExamples\n" + HelpExampleCli("getrawmempool", "true") + HelpExampleRpc("getrawmempool", "true") ); LOCK(cs_main); bool fVerbose = false; if (params.size() > 0) fVerbose = params[0].get_bool(); return mempoolToJSON(fVerbose); } UniValue getblockhashes(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "getblockhashes timestamp\n" "\nReturns array of hashes of blocks within the timestamp range provided.\n" "\nArguments:\n" "1. high (numeric, required) The newer block timestamp\n" "2. low (numeric, required) The older block timestamp\n" "\nResult:\n" "[\n" " \"hash\" (string) The block hash\n" "]\n" "\nExamples:\n" + HelpExampleCli("getblockhashes", "1231614698 1231024505") + HelpExampleRpc("getblockhashes", "1231614698, 1231024505") ); unsigned int high = params[0].get_int(); unsigned int low = params[1].get_int(); std::vector<uint256> blockHashes; if (!GetTimestampIndex(high, low, blockHashes)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for block hashes"); } UniValue result(UniValue::VARR); for (std::vector<uint256>::const_iterator it=blockHashes.begin(); it!=blockHashes.end(); it++) { result.push_back(it->GetHex()); } return result; } UniValue getblockhash(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblockhash index\n" "\nReturns hash of block in best-block-chain at index provided.\n" "\nArguments:\n" "1. index (numeric, required) The block index\n" "\nResult:\n" "\"hash\" (string) The block hash\n" "\nExamples:\n" + HelpExampleCli("getblockhash", "1000") + HelpExampleRpc("getblockhash", "1000") ); LOCK(cs_main); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > chainActive.Height()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range"); CBlockIndex* pblockindex = chainActive[nHeight]; return pblockindex->GetBlockHash().GetHex(); } UniValue getblockheader(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblockheader \"hash\" ( verbose )\n" "\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n" "If verbose is true, returns an Object with information about blockheader <hash>.\n" "\nArguments:\n" "1. \"hash\" (string, required) The block hash\n" "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n" "\nResult (for verbose = true):\n" "{\n" " \"hash\" : \"hash\", (string) the block hash (same as provided)\n" " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" " \"height\" : n, (numeric) The block height or index\n" " \"version\" : n, (numeric) The block version\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"nextblockhash\" : \"hash\", (string) The hash of the next block\n" " \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n" "}\n" "\nResult (for verbose=false):\n" "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n" "\nExamples:\n" + HelpExampleCli("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"") + HelpExampleRpc("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"") ); LOCK(cs_main); std::string strHash = params[0].get_str(); uint256 hash(uint256S(strHash)); bool fVerbose = true; if (params.size() > 1) fVerbose = params[1].get_bool(); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << pblockindex->GetBlockHeader(); std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockheaderToJSON(pblockindex); } UniValue getblockheaders(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "getblockheaders \"hash\" ( count verbose )\n" "\nReturns an array of items with information about <count> blockheaders starting from <hash>.\n" "\nIf verbose is false, each item is a string that is serialized, hex-encoded data for a single blockheader.\n" "If verbose is true, each item is an Object with information about a single blockheader.\n" "\nArguments:\n" "1. \"hash\" (string, required) The block hash\n" "2. count (numeric, optional, default/max=" + strprintf("%s", MAX_HEADERS_RESULTS) +")\n" "3. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n" "\nResult (for verbose = true):\n" "[ {\n" " \"hash\" : \"hash\", (string) The block hash\n" " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" " \"height\" : n, (numeric) The block height or index\n" " \"version\" : n, (numeric) The block version\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"nextblockhash\" : \"hash\", (string) The hash of the next block\n" " \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n" "}, {\n" " ...\n" " },\n" "...\n" "]\n" "\nResult (for verbose=false):\n" "[\n" " \"data\", (string) A string that is serialized, hex-encoded data for block header.\n" " ...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getblockheaders", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 2000") + HelpExampleRpc("getblockheaders", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 2000") ); LOCK(cs_main); std::string strHash = params[0].get_str(); uint256 hash(uint256S(strHash)); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); int nCount = MAX_HEADERS_RESULTS; if (params.size() > 1) nCount = params[1].get_int(); if (nCount <= 0 || nCount > (int)MAX_HEADERS_RESULTS) throw JSONRPCError(RPC_INVALID_PARAMETER, "Count is out of range"); bool fVerbose = true; if (params.size() > 2) fVerbose = params[2].get_bool(); CBlockIndex* pblockindex = mapBlockIndex[hash]; UniValue arrHeaders(UniValue::VARR); if (!fVerbose) { for (; pblockindex; pblockindex = chainActive.Next(pblockindex)) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << pblockindex->GetBlockHeader(); std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); arrHeaders.push_back(strHex); if (--nCount <= 0) break; } return arrHeaders; } for (; pblockindex; pblockindex = chainActive.Next(pblockindex)) { arrHeaders.push_back(blockheaderToJSON(pblockindex)); if (--nCount <= 0) break; } return arrHeaders; } UniValue getblock(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock \"hash\" ( verbose )\n" "\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash'.\n" "If verbose is true, returns an Object with information about block <hash>.\n" "\nArguments:\n" "1. \"hash\" (string, required) The block hash\n" "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n" "\nResult (for verbose = true):\n" "{\n" " \"hash\" : \"hash\", (string) the block hash (same as provided)\n" " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" " \"size\" : n, (numeric) The block size\n" " \"height\" : n, (numeric) The block height or index\n" " \"version\" : n, (numeric) The block version\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"tx\" : [ (array of string) The transaction ids\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" " ],\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"chainwork\" : \"xxxx\", (string) Expected number of hashes required to produce the chain up to this block (in hex)\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"nextblockhash\" : \"hash\" (string) The hash of the next block\n" "}\n" "\nResult (for verbose=false):\n" "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n" "\nExamples:\n" + HelpExampleCli("getblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"") + HelpExampleRpc("getblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"") ); LOCK(cs_main); std::string strHash = params[0].get_str(); uint256 hash(uint256S(strHash)); bool fVerbose = true; if (params.size() > 1) fVerbose = params[1].get_bool(); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0) throw JSONRPCError(RPC_INTERNAL_ERROR, "Block not available (pruned data)"); if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << block; std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockToJSON(block, pblockindex); } UniValue gettxoutsetinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "gettxoutsetinfo\n" "\nReturns statistics about the unspent transaction output set.\n" "Note this call may take some time.\n" "\nResult:\n" "{\n" " \"height\":n, (numeric) The current block height (index)\n" " \"bestblock\": \"hex\", (string) the best block hash hex\n" " \"transactions\": n, (numeric) The number of transactions\n" " \"txouts\": n, (numeric) The number of output transactions\n" " \"bytes_serialized\": n, (numeric) The serialized size\n" " \"hash_serialized\": \"hash\", (string) The serialized hash\n" " \"total_amount\": x.xxx (numeric) The total amount\n" "}\n" "\nExamples:\n" + HelpExampleCli("gettxoutsetinfo", "") + HelpExampleRpc("gettxoutsetinfo", "") ); UniValue ret(UniValue::VOBJ); CCoinsStats stats; FlushStateToDisk(); if (pcoinsTip->GetStats(stats)) { ret.push_back(Pair("height", (int64_t)stats.nHeight)); ret.push_back(Pair("bestblock", stats.hashBlock.GetHex())); ret.push_back(Pair("transactions", (int64_t)stats.nTransactions)); ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs)); ret.push_back(Pair("bytes_serialized", (int64_t)stats.nSerializedSize)); ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex())); ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount))); } return ret; } UniValue gettxout(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) throw runtime_error( "gettxout \"txid\" n ( includemempool )\n" "\nReturns details about an unspent transaction output.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "2. n (numeric, required) vout value\n" "3. includemempool (boolean, optional) Whether to included the mem pool\n" "\nResult:\n" "{\n" " \"bestblock\" : \"hash\", (string) the block hash\n" " \"confirmations\" : n, (numeric) The number of confirmations\n" " \"value\" : x.xxx, (numeric) The transaction value in " + CURRENCY_UNIT + "\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"code\", (string) \n" " \"hex\" : \"hex\", (string) \n" " \"reqSigs\" : n, (numeric) Number of required signatures\n" " \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n" " \"addresses\" : [ (array of string) array of wmc addresses\n" " \"dashaddress\" (string) wmc address\n" " ,...\n" " ]\n" " },\n" " \"version\" : n, (numeric) The version\n" " \"coinbase\" : true|false (boolean) Coinbase or not\n" "}\n" "\nExamples:\n" "\nGet unspent transactions\n" + HelpExampleCli("listunspent", "") + "\nView the details\n" + HelpExampleCli("gettxout", "\"txid\" 1") + "\nAs a json rpc call\n" + HelpExampleRpc("gettxout", "\"txid\", 1") ); LOCK(cs_main); UniValue ret(UniValue::VOBJ); std::string strHash = params[0].get_str(); uint256 hash(uint256S(strHash)); int n = params[1].get_int(); bool fMempool = true; if (params.size() > 2) fMempool = params[2].get_bool(); CCoins coins; if (fMempool) { LOCK(mempool.cs); CCoinsViewMemPool view(pcoinsTip, mempool); if (!view.GetCoins(hash, coins)) return NullUniValue; mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool } else { if (!pcoinsTip->GetCoins(hash, coins)) return NullUniValue; } if (n<0 || (unsigned int)n>=coins.vout.size() || coins.vout[n].IsNull()) return NullUniValue; BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock()); CBlockIndex *pindex = it->second; ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex())); if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT) ret.push_back(Pair("confirmations", 0)); else ret.push_back(Pair("confirmations", pindex->nHeight - coins.nHeight + 1)); ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue))); UniValue o(UniValue::VOBJ); ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o, true); ret.push_back(Pair("scriptPubKey", o)); ret.push_back(Pair("version", coins.nVersion)); ret.push_back(Pair("coinbase", coins.fCoinBase)); return ret; } UniValue verifychain(const UniValue& params, bool fHelp) { int nCheckLevel = GetArg("-checklevel", DEFAULT_CHECKLEVEL); int nCheckDepth = GetArg("-checkblocks", DEFAULT_CHECKBLOCKS); if (fHelp || params.size() > 2) throw runtime_error( "verifychain ( checklevel numblocks )\n" "\nVerifies blockchain database.\n" "\nArguments:\n" "1. checklevel (numeric, optional, 0-4, default=" + strprintf("%d", nCheckLevel) + ") How thorough the block verification is.\n" "2. numblocks (numeric, optional, default=" + strprintf("%d", nCheckDepth) + ", 0=all) The number of blocks to check.\n" "\nResult:\n" "true|false (boolean) Verified or not\n" "\nExamples:\n" + HelpExampleCli("verifychain", "") + HelpExampleRpc("verifychain", "") ); LOCK(cs_main); if (params.size() > 0) nCheckLevel = params[0].get_int(); if (params.size() > 1) nCheckDepth = params[1].get_int(); return CVerifyDB().VerifyDB(Params(), pcoinsTip, nCheckLevel, nCheckDepth); } /** Implementation of IsSuperMajority with better feedback */ static UniValue SoftForkMajorityDesc(int minVersion, CBlockIndex* pindex, int nRequired, const Consensus::Params& consensusParams) { int nFound = 0; CBlockIndex* pstart = pindex; for (int i = 0; i < consensusParams.nMajorityWindow && pstart != NULL; i++) { if (pstart->nVersion >= minVersion) ++nFound; pstart = pstart->pprev; } UniValue rv(UniValue::VOBJ); rv.push_back(Pair("status", nFound >= nRequired)); rv.push_back(Pair("found", nFound)); rv.push_back(Pair("required", nRequired)); rv.push_back(Pair("window", consensusParams.nMajorityWindow)); return rv; } static UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex* pindex, const Consensus::Params& consensusParams) { UniValue rv(UniValue::VOBJ); rv.push_back(Pair("id", name)); rv.push_back(Pair("version", version)); rv.push_back(Pair("enforce", SoftForkMajorityDesc(version, pindex, consensusParams.nMajorityEnforceBlockUpgrade, consensusParams))); rv.push_back(Pair("reject", SoftForkMajorityDesc(version, pindex, consensusParams.nMajorityRejectBlockOutdated, consensusParams))); return rv; } static UniValue BIP9SoftForkDesc(const std::string& name, const Consensus::Params& consensusParams, Consensus::DeploymentPos id) { UniValue rv(UniValue::VOBJ); rv.push_back(Pair("id", name)); switch (VersionBitsTipState(consensusParams, id)) { case THRESHOLD_DEFINED: rv.push_back(Pair("status", "defined")); break; case THRESHOLD_STARTED: rv.push_back(Pair("status", "started")); break; case THRESHOLD_LOCKED_IN: rv.push_back(Pair("status", "locked_in")); break; case THRESHOLD_ACTIVE: rv.push_back(Pair("status", "active")); break; case THRESHOLD_FAILED: rv.push_back(Pair("status", "failed")); break; } return rv; } UniValue getblockchaininfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockchaininfo\n" "Returns an object containing various state info regarding block chain processing.\n" "\nResult:\n" "{\n" " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n" " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n" " \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n" " \"bestblockhash\": \"...\", (string) the hash of the currently best block\n" " \"difficulty\": xxxxxx, (numeric) the current difficulty\n" " \"mediantime\": xxxxxx, (numeric) median time for the current best block\n" " \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n" " \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n" " \"pruned\": xx, (boolean) if the blocks are subject to pruning\n" " \"pruneheight\": xxxxxx, (numeric) heighest block available\n" " \"softforks\": [ (array) status of softforks in progress\n" " {\n" " \"id\": \"xxxx\", (string) name of softfork\n" " \"version\": xx, (numeric) block version\n" " \"enforce\": { (object) progress toward enforcing the softfork rules for new-version blocks\n" " \"status\": xx, (boolean) true if threshold reached\n" " \"found\": xx, (numeric) number of blocks with the new version found\n" " \"required\": xx, (numeric) number of blocks required to trigger\n" " \"window\": xx, (numeric) maximum size of examined window of recent blocks\n" " },\n" " \"reject\": { ... } (object) progress toward rejecting pre-softfork blocks (same fields as \"enforce\")\n" " }, ...\n" " ],\n" " \"bip9_softforks\": [ (array) status of BIP9 softforks in progress\n" " {\n" " \"id\": \"xxxx\", (string) name of the softfork\n" " \"status\": \"xxxx\", (string) one of \"defined\", \"started\", \"lockedin\", \"active\", \"failed\"\n" " }\n" " ]\n" "}\n" "\nExamples:\n" + HelpExampleCli("getblockchaininfo", "") + HelpExampleRpc("getblockchaininfo", "") ); LOCK(cs_main); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("chain", Params().NetworkIDString())); obj.push_back(Pair("blocks", (int)chainActive.Height())); obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1)); obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex())); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("mediantime", (int64_t)chainActive.Tip()->GetMedianTimePast())); obj.push_back(Pair("verificationprogress", Checkpoints::GuessVerificationProgress(Params().Checkpoints(), chainActive.Tip()))); obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex())); obj.push_back(Pair("pruned", fPruneMode)); const Consensus::Params& consensusParams = Params().GetConsensus(); CBlockIndex* tip = chainActive.Tip(); UniValue softforks(UniValue::VARR); UniValue bip9_softforks(UniValue::VARR); softforks.push_back(SoftForkDesc("bip34", 2, tip, consensusParams)); softforks.push_back(SoftForkDesc("bip66", 3, tip, consensusParams)); softforks.push_back(SoftForkDesc("bip65", 4, tip, consensusParams)); bip9_softforks.push_back(BIP9SoftForkDesc("csv", consensusParams, Consensus::DEPLOYMENT_CSV)); obj.push_back(Pair("softforks", softforks)); obj.push_back(Pair("bip9_softforks", bip9_softforks)); if (fPruneMode) { CBlockIndex *block = chainActive.Tip(); while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA)) block = block->pprev; obj.push_back(Pair("pruneheight", block->nHeight)); } return obj; } /** Comparison function for sorting the getchaintips heads. */ struct CompareBlocksByHeight { bool operator()(const CBlockIndex* a, const CBlockIndex* b) const { /* Make sure that unequal blocks with the same height do not compare equal. Use the pointers themselves to make a distinction. */ if (a->nHeight != b->nHeight) return (a->nHeight > b->nHeight); return a < b; } }; UniValue getchaintips(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getchaintips ( count branchlen )\n" "Return information about all known tips in the block tree," " including the main chain as well as orphaned branches.\n" "\nArguments:\n" "1. count (numeric, optional) only show this much of latest tips\n" "2. branchlen (numeric, optional) only show tips that have equal or greater length of branch\n" "\nResult:\n" "[\n" " {\n" " \"height\": xxxx, (numeric) height of the chain tip\n" " \"hash\": \"xxxx\", (string) block hash of the tip\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n" " \"branchlen\": 0 (numeric) zero for main chain\n" " \"status\": \"active\" (string) \"active\" for the main chain\n" " },\n" " {\n" " \"height\": xxxx,\n" " \"hash\": \"xxxx\",\n" " \"difficulty\" : x.xxx,\n" " \"chainwork\" : \"0000...1f3\"\n" " \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n" " \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n" " }\n" "]\n" "Possible values for status:\n" "1. \"invalid\" This branch contains at least one invalid block\n" "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n" "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n" "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n" "5. \"active\" This is the tip of the active main chain, which is certainly valid\n" "\nExamples:\n" + HelpExampleCli("getchaintips", "") + HelpExampleRpc("getchaintips", "") ); LOCK(cs_main); /* Build up a list of chain tips. We start with the list of all known blocks, and successively remove blocks that appear as pprev of another block. */ std::set<const CBlockIndex*, CompareBlocksByHeight> setTips; BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex) setTips.insert(item.second); BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex) { const CBlockIndex* pprev = item.second->pprev; if (pprev) setTips.erase(pprev); } // Always report the currently active tip. setTips.insert(chainActive.Tip()); int nBranchMin = -1; int nCountMax = INT_MAX; if(params.size() >= 1) nCountMax = params[0].get_int(); if(params.size() == 2) nBranchMin = params[1].get_int(); /* Construct the output array. */ UniValue res(UniValue::VARR); BOOST_FOREACH(const CBlockIndex* block, setTips) { const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight; if(branchLen < nBranchMin) continue; if(nCountMax-- < 1) break; UniValue obj(UniValue::VOBJ); obj.push_back(Pair("height", block->nHeight)); obj.push_back(Pair("hash", block->phashBlock->GetHex())); obj.push_back(Pair("difficulty", GetDifficulty(block))); obj.push_back(Pair("chainwork", block->nChainWork.GetHex())); obj.push_back(Pair("branchlen", branchLen)); string status; if (chainActive.Contains(block)) { // This block is part of the currently active chain. status = "active"; } else if (block->nStatus & BLOCK_FAILED_MASK) { // This block or one of its ancestors is invalid. status = "invalid"; } else if (block->nChainTx == 0) { // This block cannot be connected because full block data for it or one of its parents is missing. status = "headers-only"; } else if (block->IsValid(BLOCK_VALID_SCRIPTS)) { // This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized. status = "valid-fork"; } else if (block->IsValid(BLOCK_VALID_TREE)) { // The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain. status = "valid-headers"; } else { // No clue. status = "unknown"; } obj.push_back(Pair("status", status)); res.push_back(obj); } return res; } UniValue mempoolInfoToJSON() { UniValue ret(UniValue::VOBJ); ret.push_back(Pair("size", (int64_t) mempool.size())); ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize())); ret.push_back(Pair("usage", (int64_t) mempool.DynamicMemoryUsage())); size_t maxmempool = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000; ret.push_back(Pair("maxmempool", (int64_t) maxmempool)); ret.push_back(Pair("mempoolminfee", ValueFromAmount(mempool.GetMinFee(maxmempool).GetFeePerK()))); return ret; } UniValue getmempoolinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmempoolinfo\n" "\nReturns details on the active state of the TX memory pool.\n" "\nResult:\n" "{\n" " \"size\": xxxxx, (numeric) Current tx count\n" " \"bytes\": xxxxx, (numeric) Sum of all tx sizes\n" " \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n" " \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n" " \"mempoolminfee\": xxxxx (numeric) Minimum fee for tx to be accepted\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmempoolinfo", "") + HelpExampleRpc("getmempoolinfo", "") ); return mempoolInfoToJSON(); } UniValue invalidateblock(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "invalidateblock \"hash\"\n" "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n" "\nArguments:\n" "1. hash (string, required) the hash of the block to mark as invalid\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("invalidateblock", "\"blockhash\"") + HelpExampleRpc("invalidateblock", "\"blockhash\"") ); std::string strHash = params[0].get_str(); uint256 hash(uint256S(strHash)); CValidationState state; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; InvalidateBlock(state, Params().GetConsensus(), pblockindex); } if (state.IsValid()) { ActivateBestChain(state, Params()); } if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; } UniValue reconsiderblock(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "reconsiderblock \"hash\"\n" "\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n" "This can be used to undo the effects of invalidateblock.\n" "\nArguments:\n" "1. hash (string, required) the hash of the block to reconsider\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("reconsiderblock", "\"blockhash\"") + HelpExampleRpc("reconsiderblock", "\"blockhash\"") ); std::string strHash = params[0].get_str(); uint256 hash(uint256S(strHash)); CValidationState state; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; ReconsiderBlock(state, pblockindex); } if (state.IsValid()) { ActivateBestChain(state, Params()); } if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; }
[ "37483096+RRCdev@users.noreply.github.com" ]
37483096+RRCdev@users.noreply.github.com
0c7100c5c68c7fddd3a593fe1e99bd3deeca0da8
6db9478ab57690420b2aa98b450d346f7a9f3b7d
/z_unclassified/5597.cpp
0f3642eefccb0e9a9b730e45facc5da26908faaa
[]
no_license
siosio34/AlgorithmStudy
d23266e0d4576a3aab123aee7b571021ec619009
b5626a0e4eb14f9553fe48aacacb1696a927c740
refs/heads/master
2020-03-19T09:15:13.167353
2019-05-22T13:50:41
2019-05-22T13:50:41
136,272,154
0
0
null
null
null
null
UTF-8
C++
false
false
239
cpp
#include <iostream> using namespace std; bool check[31]; int main() { int tmp; for(int i = 1 ; i <= 28 ; i++) { cin >> tmp; check[tmp] = true; } for(int i = 1 ; i <= 30 ; i++) { if(!check[i]) { cout << i << endl; } } }
[ "siosio34@nate.com" ]
siosio34@nate.com
a137f99220ddeef255268e1a4ab7069d0543c13d
415f05343a56dbab4c0963c7e4060e5c561dec75
/lib/SSD1306/SSD1306.hpp
c02738ca7ded05eb510c015cf93d3498921e141c
[]
no_license
fzilic/gd32v-basics
8bb5e650d29de2a3238f0ca640230a1d06a70983
ee0b5fc16bc469c6e4ade6c48ad76209974bfc94
refs/heads/master
2023-01-27T18:59:25.268212
2020-11-29T13:42:17
2020-11-29T13:42:17
315,856,106
1
0
null
null
null
null
UTF-8
C++
false
false
1,401
hpp
#ifndef __SSD1306_H #define __SSD1306_H #define WIRE_MAX 32 // if needed at all #include "I2C.hpp" #include "GPIO.hpp" namespace SSD1306 { enum SSD1306Command : uint8_t { MEMORY_MODE = 0x20, DEACTIVATE_SCROLL = 0x2E, SET_START_LINE = 0x40, SETCONTRAST = 0x81, CHARGE_PUMP = 0x8D, SEGREMAP = 0xA0, DISPLAYALLON_RESUME = 0xA4, NORMALDISPLAY = 0xA6, SET_MULTIPLEX = 0xA8, DISPLAY_OFF = 0xAE, DISPLAYON = 0xAF, COMSCANDEC = 0xC8, SET_DISPLAY_OFFSET = 0xD3, SET_DISPLAYCLOCK_DIV = 0xD5, SETPRECHARGE = 0xD9, SETCOMPINS = 0xDA, SETVCOMDETECT = 0xDB }; class SSD1306 { private: I2C::I2C _i2c; GPIO::GPIO _reset; uint8_t _width; uint8_t _height; uint32_t _address; uint32_t _clockDuring; //400000UL uint32_t _clockAfter; //100000UL uint8_t *_buffer; void command(const uint8_t command); void commands(const uint8_t *commands, uint8_t count); public: bool init(); void clearDisplay(); void display(); // void setTextSize(uint8_t size); // void setTextColor(uint16_t color); // void setCursor(int16_t x, int16_t y); // void cp437(); // void write(); }; }; // namespace SSD1306 #endif
[ "franjo.zilic@omnifit.hr" ]
franjo.zilic@omnifit.hr
897413e543bce758c63cb73a1cd5ccb1a3806dc4
90741b131af6b09386d187901797f779e59ef893
/FreeFormPairsTest/RoughPay.cpp
8303f23ff51e4726bf355a5d8287e6d5edfd7624
[]
no_license
TGKStudios/Game-Directory-Personal-Project
ab2580b0646ef02d411d43fd09099a954c12d871
279b35bd4cac4f28a4a97fce7c22051b72537a57
refs/heads/master
2022-12-08T02:37:09.576872
2020-08-28T17:01:34
2020-08-28T17:01:34
280,720,995
0
0
null
null
null
null
UTF-8
C++
false
false
1,328
cpp
// FreeFormPairsTest.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <algorithm> #include <vector> #include <string> class payCalc { public: float weeklyAdd(float pay, int hoursWorked) { return (pay * hoursWorked) ; } float biWeeklyAdd(float pay, int hoursWorked) { return (pay * hoursWorked) * 2; } float monthlyAdd(float pay, int hoursWorked) { return (pay * hoursWorked) * 4; } float anuallyAdd(float pay, int hoursWorked) { return (pay * hoursWorked) *52 ; } }; template<typename T, typename U> void processInput(payCalc p) { T payTemp; U hoursTemp; std::cout << "Enter your hourly pay\n"; std::cin >> payTemp; std::cout << "Enter the average number of hours you work per hour (20,40,etc.)\n"; std::cin >> hoursTemp; std::cout << "Your weekly pay is: " << p.weeklyAdd(payTemp, hoursTemp) << "\n"; std::cout << "Your biweekly pay is: " << p.biWeeklyAdd(payTemp, hoursTemp) << "\n"; std::cout << "Your monthly pay is: " << p.monthlyAdd(payTemp, hoursTemp) << "\n"; std::cout << "Your annual pay is: " << p.anuallyAdd(payTemp, hoursTemp) << "\n"; return; } int main() { payCalc p; processInput<float, int>(p); }
[ "62812478+TGKStudios@users.noreply.github.com" ]
62812478+TGKStudios@users.noreply.github.com
97580cae2373eae49768de4ae3bd055e986797eb
88c664489bb9480b5fb446c45cfd988ef044be7b
/corelib/include/rtabmap/core/OptimizerG2O.h
e85909605e7778b22f601798af25873a26028031
[]
no_license
ygling2008/rtabmap
51157cc1822edc2a5bd45b442de1c4d53518f3cc
0802f9158c6fb94e6012d66439078bf2bd62f9c6
refs/heads/master
2020-07-01T22:13:13.329791
2016-11-18T21:59:14
2016-11-18T21:59:14
74,334,422
0
1
null
2016-11-21T06:45:54
2016-11-21T06:45:54
null
UTF-8
C++
false
false
3,286
h
/* Copyright (c) 2010-2016, Mathieu Labbe - IntRoLab - Universite de Sherbrooke 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 the Universite de Sherbrooke nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef OPTIMIZERG2O_H_ #define OPTIMIZERG2O_H_ #include "rtabmap/core/RtabmapExp.h" // DLL export/import defines #include <rtabmap/core/Optimizer.h> namespace rtabmap { class RTABMAP_EXP OptimizerG2O : public Optimizer { public: static bool available(); static bool isCSparseAvailable(); static bool isCholmodAvailable(); static bool saveGraph( const std::string & fileName, const std::map<int, Transform> & poses, const std::multimap<int, Link> & edgeConstraints, bool useRobustConstraints = false); public: OptimizerG2O(const ParametersMap & parameters = ParametersMap()) : Optimizer(parameters), solver_(Parameters::defaultg2oSolver()), optimizer_(Parameters::defaultg2oOptimizer()), pixelVariance_(Parameters::defaultg2oPixelVariance()) { parseParameters(parameters); } virtual ~OptimizerG2O() {} virtual Type type() const {return kTypeG2O;} virtual void parseParameters(const ParametersMap & parameters); virtual std::map<int, Transform> optimize( int rootId, const std::map<int, Transform> & poses, const std::multimap<int, Link> & edgeConstraints, std::list<std::map<int, Transform> > * intermediateGraphes = 0, double * finalError = 0, int * iterationsDone = 0); virtual std::map<int, Transform> optimizeBA( int rootId, const std::map<int, Transform> & poses, const std::multimap<int, Link> & links, const std::map<int, CameraModel> & models, std::map<int, cv::Point3f> & points3DMap, const std::map<int, std::map<int, cv::Point2f> > & wordReferences); // <ID words, IDs frames + keypoint> private: int solver_; int optimizer_; double pixelVariance_; }; } /* namespace rtabmap */ #endif /* OPTIMIZERG2O_H_ */
[ "matlabbe@gmail.com" ]
matlabbe@gmail.com
71de800b1452547d0e54bf1e0ab91d8703629872
515eae03aa8892ce48e91b593f1d7057b4bf2cc2
/CPPINTERMEDIATE/207_AUTO_DECLTYPE/auto1.cpp
795960beff10f3b9422674b3c506c3819959da7b
[]
no_license
et16kr/codenuri-clone
b7b759d85337009c40ee4b2d3e42e7c38a025c6d
d1178eec9db369d2cb94ceb44fd3a4982228f2eb
refs/heads/master
2023-04-20T12:44:58.696043
2021-05-01T04:13:33
2021-05-01T04:13:33
363,316,531
0
1
null
null
null
null
UTF-8
C++
false
false
338
cpp
/* * HOME : ecourse.co.kr * EMAIL : smkang @ codenuri.co.kr * COURSENAME : C++ Intermediate * Copyright (C) 2018 CODENURI Inc. All rights reserved. */ #include <iostream> using namespace std; int main() { int n = 10; int& r = n; auto a = r; // a ? int ? int& a = 30; cout << n << endl; // 30 ? 10 }
[ "et16kr@gmail.com" ]
et16kr@gmail.com
6202c73899f38141d6d04ffe2dc44474b761d56d
d8fe65c431e73e96b4b273dbaa2b6a28f50ee650
/Common/util/src/path.cpp
09320d0635f37a444786d14563b49f5ff190ca19
[ "MIT" ]
permissive
deeptexas-ai/MasterAI-1.0-1vs1-Limit
eebba13819977e5f7387687e42b85f19f9ac8ad0
f06b798d18f2d53c9206df41406d02647004ce84
refs/heads/main
2023-08-16T15:32:37.505341
2021-10-19T04:10:45
2021-10-19T04:10:45
415,269,205
12
1
null
null
null
null
UTF-8
C++
false
false
5,743
cpp
/** * \file path.cpp * \brief 路径类函数的实现 */ #include "pch.h" #include "path.h" #ifdef WIN32 # include <shlwapi.h> # pragma comment(lib, "shlwapi") #else # include <dirent.h> #endif namespace dtutil { /** * \brief 是否目录 * \param path 路径 * \return 是返回true,否则返回false */ bool Path::IsDirectory(std::string path) { #ifdef WIN32 return PathIsDirectoryA(path.c_str()) ? true : false; #else DIR* dir = opendir(path.c_str()); if (NULL != dir) { closedir(dir); dir = NULL; return true; } return false; #endif } /** * \brief 生成目录 * \param path 路径 * \return 成功返回true,否则返回false */ bool Path::MakeDir(std::string path) { if (0 == path.length()) { return true; } std::string sub; FixPath(path); std::string::size_type pos = path.find('/'); while (pos != std::string::npos) { std::string cur = path.substr(0, pos); if (cur.length() > 0 && !IsDirectory(cur)) { bool result = false; #ifdef WIN32 result = CreateDirectoryA(cur.c_str(), NULL) ? true : false; #else result = (mkdir(cur.c_str(), S_IRWXU|S_IRWXG|S_IRWXO) == 0); #endif if (!result) { return false; } } pos = path.find('/', pos+1); } return true; } /** * \brief 修正路径 * \param path 路径 * 将 win32 下的路径符号"\"改为"/", * 并在路径后加上"/" */ void Path::FixPath(std::string &path) { if (path.empty()) { return; } for(std::string::iterator it = path.begin(); it != path.end(); ++it) { if (*it == '\\') { *it = '/'; } } if (path.at(path.length()-1) != '/') { path.append("/"); } } /** * \brief 获取文件路径 * \param file 完整文件名 * \return 去掉文件名的路径 */ std::string Path::GetPath(std::string file) { std::string path = ""; if (file.empty()) { return path; } // 无斜杠,返回空 std::string::size_type pos = file.rfind('\\'); if (pos == std::string::npos) { pos = file.rfind('/'); if (pos == std::string::npos) { return path; } } path = file.substr(0, pos); return path; } /** * \brief 获取文件名 * \param file 完整文件名 * \return 去掉路径的文件名 */ std::string Path::GetFileName(std::string file) { std::string filename = file; if (file.empty()) { return filename; } // 无斜杠,返回空 std::string::size_type pos = file.rfind('\\'); if (pos == std::string::npos) { pos = file.rfind('/'); if (pos == std::string::npos) { return filename; } } filename = file.substr(pos+1, file.length()-pos-1); return filename; } /** * \brief 解析文件名 * \param filename 完整文件名 * \param path 返回的文件路径 * \param file 返回的文件名 * \param ext 返回的文件名后缀 * \return 成功返回true,否则返回false */ bool Path::ParseFileName(std::string filename, std::string &path, std::string &file, std::string &ext) { if (filename.empty()) { return false; } path.clear(); file.clear(); ext.clear(); // 点的位置 std::string::size_type point_pos = filename.rfind('.'); // 斜杠的位置 std::string::size_type pos = filename.rfind('\\'); if (pos == std::string::npos) { pos = filename.rfind('/'); } // 无点无斜杠 if (pos == std::string::npos && point_pos == std::string::npos) { return false; } // 无点,当作路径 if (point_pos == std::string::npos) { path = filename; } else { // 以斜杠结尾 if (pos == filename.length() - 1) { path = filename.substr(0, pos); } // 非斜杠结尾 else { if (pos != std::string::npos) { path = filename.substr(0, pos); } file = filename.substr(pos+1, point_pos-pos-1); ext = filename.substr(point_pos+1, filename.length()-point_pos-1); } } return true; } /** * \brief 是否存在文件 * \param file 文件名 * \return 存在返回true,否则返回false */ bool Path::ExistFile(std::string file) { if (-1 == access(file.c_str(), 0)) { return false; } return true; } /** * \brief 文件改名 * \param oldfile 旧文件名 * \param newfile 新文件名 * \return 成功返回true,否则返回false */ bool Path::RenameFile(std::string oldfile, std::string newfile) { // 删除文件 if (0 != rename(oldfile.c_str(), newfile.c_str())) { return false; } return true; } }
[ "Awzs+20211008" ]
Awzs+20211008
cb26fa95ca4055b521d639b23d5a3923cfd62702
ffb47dd609b05c2c1e280c817b496149df0dbf57
/37-delegates/shapedelegate.h
be4e3efc89deec5958e3cab4669a11a55796a9e8
[]
no_license
Katysul/cppqt-course-examples
481df22ca60c694e68a464bc1f1d5fde21f350cf
6a1435e86353012e31f3e3a6316477857353c7c2
refs/heads/master
2023-04-18T17:38:00.421009
2021-04-28T11:19:16
2021-04-28T11:19:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
967
h
#ifndef SHAPEDELEGATE_H #define SHAPEDELEGATE_H #include <QObject> #include <QStyledItemDelegate> class ShapeDelegate : public QStyledItemDelegate { public: ShapeDelegate(QObject *parent = NULL); // QAbstractItemDelegate interface public: virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; virtual QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; // QAbstractItemDelegate interface public: virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; virtual void setEditorData(QWidget *editor, const QModelIndex &index) const; virtual void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; virtual void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const; }; #endif // SHAPEDELEGATE_H
[ "ynonperek@gmail.com" ]
ynonperek@gmail.com
cade9fd412d38316138c571f0ae5acab1004d4f2
2a7fab71876c922bce73081a69e728eeb9a83359
/m3/src/ui/build-debug-ui-unknown-release/debug-ui_autogen/include/ui_debug_ui_mainwindow.h
91f38dcba87c9df2f0039c166097b4b342209a86
[]
no_license
SiChiTong/scrubbber_slam_CMES
3a127453bc2e868dee978f1e4d448c5cce0f86e1
cfc07222cb53c83c09602b5f4da4022c37c97574
refs/heads/master
2023-06-22T10:29:37.018491
2021-07-26T15:09:12
2021-07-26T15:09:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,142
h
/******************************************************************************** ** Form generated from reading UI file 'debug_ui_mainwindow.ui' ** ** Created by: Qt User Interface Compiler version 5.9.5 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_DEBUG_UI_MAINWINDOW_H #define UI_DEBUG_UI_MAINWINDOW_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QCheckBox> #include <QtWidgets/QComboBox> #include <QtWidgets/QDoubleSpinBox> #include <QtWidgets/QFrame> #include <QtWidgets/QGridLayout> #include <QtWidgets/QGroupBox> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QMainWindow> #include <QtWidgets/QMenuBar> #include <QtWidgets/QPushButton> #include <QtWidgets/QSlider> #include <QtWidgets/QSpinBox> #include <QtWidgets/QTextBrowser> #include <QtWidgets/QToolBar> #include <QtWidgets/QToolButton> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> #include "QVTKWidget.h" QT_BEGIN_NAMESPACE class Ui_MainWindow { public: QWidget *centralWidget; QWidget *widget; QGridLayout *gridLayout; QVBoxLayout *verticalLayout; QLabel *label; QHBoxLayout *horizontalLayout; QLineEdit *db_path_; QToolButton *db_path_btn_; QHBoxLayout *horizontalLayout_2; QLineEdit *keyframe_path_; QToolButton *kf_path_btn_; QPushButton *load_map_btn_; QVTKWidget *pcl_window_; QGroupBox *groupBox; QLabel *label_4; QSpinBox *loop_kf_1_; QSpinBox *loop_kf_2_; QLabel *label_13; QPushButton *add_loop_btn_; QLineEdit *num_loops_; QLabel *label_18; QGroupBox *groupBox_4; QTextBrowser *opti_report_; QPushButton *call_optimize_btn_; QPushButton *reset_optimize_btn_; QGroupBox *groupBox_2; QLabel *label_5; QSpinBox *current_kf_id_box_; QPushButton *focus_cur_kf_btn_; QLabel *label_6; QWidget *verticalLayoutWidget_3; QVBoxLayout *verticalLayout_3; QLabel *label_7; QLabel *label_8; QLabel *label_9; QLabel *label_10; QLabel *label_11; QLabel *label_12; QWidget *verticalLayoutWidget_2; QVBoxLayout *verticalLayout_2; QDoubleSpinBox *cur_kf_x_display_; QDoubleSpinBox *cur_kf_y_display_; QDoubleSpinBox *cur_kf_z_display_; QDoubleSpinBox *cur_kf_roll_display_; QDoubleSpinBox *cur_kf_pitch_display_; QDoubleSpinBox *cur_kf_yaw_display_; QPushButton *play_through_btn_; QGroupBox *groupBox_5; QCheckBox *use_internal_loop_closing_; QPushButton *call_loop_closing_; QPushButton *fix_current_btn_; QPushButton *clear_fixed_btn_1; QGroupBox *groupBox_3; QLabel *label_14; QCheckBox *show_optimization_check_; QCheckBox *show_pose_graph_check_; QComboBox *resolution_box_; QLabel *label_15; QDoubleSpinBox *camera_height_; QCheckBox *show_pose_graph_check_1; QCheckBox *highlight_current_; QCheckBox *highlight_loop_; QCheckBox *show_point_cloud_; QSlider *play_speed_; QLabel *label_16; QCheckBox *camera_follow_current_; QFrame *line; QLabel *label_2; QLineEdit *cur_kf_info_; QLabel *label_3; QLineEdit *cur_map_info_; QPushButton *save_map_btn_; QPushButton *reset_map_btn_; QMenuBar *menuBar; QToolBar *mainToolBar; void setupUi(QMainWindow *MainWindow) { if (MainWindow->objectName().isEmpty()) MainWindow->setObjectName(QStringLiteral("MainWindow")); MainWindow->resize(1386, 717); centralWidget = new QWidget(MainWindow); centralWidget->setObjectName(QStringLiteral("centralWidget")); widget = new QWidget(centralWidget); widget->setObjectName(QStringLiteral("widget")); widget->setGeometry(QRect(7, 0, 1361, 651)); gridLayout = new QGridLayout(widget); gridLayout->setSpacing(6); gridLayout->setContentsMargins(11, 11, 11, 11); gridLayout->setObjectName(QStringLiteral("gridLayout")); gridLayout->setContentsMargins(0, 0, 0, 0); verticalLayout = new QVBoxLayout(); verticalLayout->setSpacing(6); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); label = new QLabel(widget); label->setObjectName(QStringLiteral("label")); verticalLayout->addWidget(label); horizontalLayout = new QHBoxLayout(); horizontalLayout->setSpacing(6); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); db_path_ = new QLineEdit(widget); db_path_->setObjectName(QStringLiteral("db_path_")); db_path_->setReadOnly(true); horizontalLayout->addWidget(db_path_); db_path_btn_ = new QToolButton(widget); db_path_btn_->setObjectName(QStringLiteral("db_path_btn_")); horizontalLayout->addWidget(db_path_btn_); verticalLayout->addLayout(horizontalLayout); horizontalLayout_2 = new QHBoxLayout(); horizontalLayout_2->setSpacing(6); horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2")); keyframe_path_ = new QLineEdit(widget); keyframe_path_->setObjectName(QStringLiteral("keyframe_path_")); keyframe_path_->setReadOnly(true); horizontalLayout_2->addWidget(keyframe_path_); kf_path_btn_ = new QToolButton(widget); kf_path_btn_->setObjectName(QStringLiteral("kf_path_btn_")); horizontalLayout_2->addWidget(kf_path_btn_); verticalLayout->addLayout(horizontalLayout_2); load_map_btn_ = new QPushButton(widget); load_map_btn_->setObjectName(QStringLiteral("load_map_btn_")); verticalLayout->addWidget(load_map_btn_); gridLayout->addLayout(verticalLayout, 0, 0, 1, 2); pcl_window_ = new QVTKWidget(widget); pcl_window_->setObjectName(QStringLiteral("pcl_window_")); gridLayout->addWidget(pcl_window_, 0, 2, 5, 3); groupBox = new QGroupBox(widget); groupBox->setObjectName(QStringLiteral("groupBox")); label_4 = new QLabel(groupBox); label_4->setObjectName(QStringLiteral("label_4")); label_4->setGeometry(QRect(0, 30, 91, 36)); loop_kf_1_ = new QSpinBox(groupBox); loop_kf_1_->setObjectName(QStringLiteral("loop_kf_1_")); loop_kf_1_->setGeometry(QRect(110, 30, 61, 33)); loop_kf_2_ = new QSpinBox(groupBox); loop_kf_2_->setObjectName(QStringLiteral("loop_kf_2_")); loop_kf_2_->setGeometry(QRect(110, 70, 61, 33)); label_13 = new QLabel(groupBox); label_13->setObjectName(QStringLiteral("label_13")); label_13->setGeometry(QRect(0, 70, 81, 36)); add_loop_btn_ = new QPushButton(groupBox); add_loop_btn_->setObjectName(QStringLiteral("add_loop_btn_")); add_loop_btn_->setGeometry(QRect(30, 110, 121, 32)); num_loops_ = new QLineEdit(groupBox); num_loops_->setObjectName(QStringLiteral("num_loops_")); num_loops_->setGeometry(QRect(80, 160, 91, 32)); num_loops_->setReadOnly(true); label_18 = new QLabel(groupBox); label_18->setObjectName(QStringLiteral("label_18")); label_18->setGeometry(QRect(10, 160, 71, 36)); gridLayout->addWidget(groupBox, 0, 5, 2, 2); groupBox_4 = new QGroupBox(widget); groupBox_4->setObjectName(QStringLiteral("groupBox_4")); opti_report_ = new QTextBrowser(groupBox_4); opti_report_->setObjectName(QStringLiteral("opti_report_")); opti_report_->setGeometry(QRect(10, 70, 241, 301)); call_optimize_btn_ = new QPushButton(groupBox_4); call_optimize_btn_->setObjectName(QStringLiteral("call_optimize_btn_")); call_optimize_btn_->setGeometry(QRect(10, 30, 97, 32)); reset_optimize_btn_ = new QPushButton(groupBox_4); reset_optimize_btn_->setObjectName(QStringLiteral("reset_optimize_btn_")); reset_optimize_btn_->setGeometry(QRect(120, 30, 97, 32)); gridLayout->addWidget(groupBox_4, 0, 7, 4, 3); groupBox_2 = new QGroupBox(widget); groupBox_2->setObjectName(QStringLiteral("groupBox_2")); label_5 = new QLabel(groupBox_2); label_5->setObjectName(QStringLiteral("label_5")); label_5->setGeometry(QRect(10, 30, 61, 36)); current_kf_id_box_ = new QSpinBox(groupBox_2); current_kf_id_box_->setObjectName(QStringLiteral("current_kf_id_box_")); current_kf_id_box_->setGeometry(QRect(70, 30, 111, 33)); focus_cur_kf_btn_ = new QPushButton(groupBox_2); focus_cur_kf_btn_->setObjectName(QStringLiteral("focus_cur_kf_btn_")); focus_cur_kf_btn_->setGeometry(QRect(10, 70, 91, 32)); label_6 = new QLabel(groupBox_2); label_6->setObjectName(QStringLiteral("label_6")); label_6->setGeometry(QRect(10, 100, 61, 36)); verticalLayoutWidget_3 = new QWidget(groupBox_2); verticalLayoutWidget_3->setObjectName(QStringLiteral("verticalLayoutWidget_3")); verticalLayoutWidget_3->setGeometry(QRect(20, 130, 31, 231)); verticalLayout_3 = new QVBoxLayout(verticalLayoutWidget_3); verticalLayout_3->setSpacing(6); verticalLayout_3->setContentsMargins(11, 11, 11, 11); verticalLayout_3->setObjectName(QStringLiteral("verticalLayout_3")); verticalLayout_3->setContentsMargins(0, 0, 0, 0); label_7 = new QLabel(verticalLayoutWidget_3); label_7->setObjectName(QStringLiteral("label_7")); verticalLayout_3->addWidget(label_7); label_8 = new QLabel(verticalLayoutWidget_3); label_8->setObjectName(QStringLiteral("label_8")); verticalLayout_3->addWidget(label_8); label_9 = new QLabel(verticalLayoutWidget_3); label_9->setObjectName(QStringLiteral("label_9")); verticalLayout_3->addWidget(label_9); label_10 = new QLabel(verticalLayoutWidget_3); label_10->setObjectName(QStringLiteral("label_10")); verticalLayout_3->addWidget(label_10); label_11 = new QLabel(verticalLayoutWidget_3); label_11->setObjectName(QStringLiteral("label_11")); verticalLayout_3->addWidget(label_11); label_12 = new QLabel(verticalLayoutWidget_3); label_12->setObjectName(QStringLiteral("label_12")); verticalLayout_3->addWidget(label_12); verticalLayoutWidget_2 = new QWidget(groupBox_2); verticalLayoutWidget_2->setObjectName(QStringLiteral("verticalLayoutWidget_2")); verticalLayoutWidget_2->setGeometry(QRect(60, 130, 115, 230)); verticalLayout_2 = new QVBoxLayout(verticalLayoutWidget_2); verticalLayout_2->setSpacing(6); verticalLayout_2->setContentsMargins(11, 11, 11, 11); verticalLayout_2->setObjectName(QStringLiteral("verticalLayout_2")); verticalLayout_2->setContentsMargins(0, 0, 0, 0); cur_kf_x_display_ = new QDoubleSpinBox(verticalLayoutWidget_2); cur_kf_x_display_->setObjectName(QStringLiteral("cur_kf_x_display_")); cur_kf_x_display_->setDecimals(3); cur_kf_x_display_->setMinimum(-99999); cur_kf_x_display_->setMaximum(99999); cur_kf_x_display_->setSingleStep(0.05); verticalLayout_2->addWidget(cur_kf_x_display_); cur_kf_y_display_ = new QDoubleSpinBox(verticalLayoutWidget_2); cur_kf_y_display_->setObjectName(QStringLiteral("cur_kf_y_display_")); cur_kf_y_display_->setDecimals(3); cur_kf_y_display_->setMinimum(-99999); cur_kf_y_display_->setMaximum(99999); cur_kf_y_display_->setSingleStep(0.05); verticalLayout_2->addWidget(cur_kf_y_display_); cur_kf_z_display_ = new QDoubleSpinBox(verticalLayoutWidget_2); cur_kf_z_display_->setObjectName(QStringLiteral("cur_kf_z_display_")); cur_kf_z_display_->setDecimals(3); cur_kf_z_display_->setMinimum(-99999); cur_kf_z_display_->setMaximum(99999); cur_kf_z_display_->setSingleStep(0.05); verticalLayout_2->addWidget(cur_kf_z_display_); cur_kf_roll_display_ = new QDoubleSpinBox(verticalLayoutWidget_2); cur_kf_roll_display_->setObjectName(QStringLiteral("cur_kf_roll_display_")); cur_kf_roll_display_->setDecimals(3); cur_kf_roll_display_->setMinimum(-180); cur_kf_roll_display_->setMaximum(180); cur_kf_roll_display_->setSingleStep(0.1); verticalLayout_2->addWidget(cur_kf_roll_display_); cur_kf_pitch_display_ = new QDoubleSpinBox(verticalLayoutWidget_2); cur_kf_pitch_display_->setObjectName(QStringLiteral("cur_kf_pitch_display_")); cur_kf_pitch_display_->setDecimals(3); cur_kf_pitch_display_->setMinimum(-180); cur_kf_pitch_display_->setMaximum(180); cur_kf_pitch_display_->setSingleStep(0.1); verticalLayout_2->addWidget(cur_kf_pitch_display_); cur_kf_yaw_display_ = new QDoubleSpinBox(verticalLayoutWidget_2); cur_kf_yaw_display_->setObjectName(QStringLiteral("cur_kf_yaw_display_")); cur_kf_yaw_display_->setDecimals(3); cur_kf_yaw_display_->setMinimum(-180); cur_kf_yaw_display_->setMaximum(180); cur_kf_yaw_display_->setSingleStep(0.1); verticalLayout_2->addWidget(cur_kf_yaw_display_); play_through_btn_ = new QPushButton(groupBox_2); play_through_btn_->setObjectName(QStringLiteral("play_through_btn_")); play_through_btn_->setGeometry(QRect(110, 70, 61, 32)); gridLayout->addWidget(groupBox_2, 1, 0, 4, 2); groupBox_5 = new QGroupBox(widget); groupBox_5->setObjectName(QStringLiteral("groupBox_5")); use_internal_loop_closing_ = new QCheckBox(groupBox_5); use_internal_loop_closing_->setObjectName(QStringLiteral("use_internal_loop_closing_")); use_internal_loop_closing_->setGeometry(QRect(10, 30, 151, 30)); use_internal_loop_closing_->setChecked(true); call_loop_closing_ = new QPushButton(groupBox_5); call_loop_closing_->setObjectName(QStringLiteral("call_loop_closing_")); call_loop_closing_->setGeometry(QRect(20, 70, 141, 32)); gridLayout->addWidget(groupBox_5, 2, 5, 1, 2); fix_current_btn_ = new QPushButton(widget); fix_current_btn_->setObjectName(QStringLiteral("fix_current_btn_")); gridLayout->addWidget(fix_current_btn_, 3, 5, 1, 1); clear_fixed_btn_1 = new QPushButton(widget); clear_fixed_btn_1->setObjectName(QStringLiteral("clear_fixed_btn_1")); gridLayout->addWidget(clear_fixed_btn_1, 3, 6, 1, 1); groupBox_3 = new QGroupBox(widget); groupBox_3->setObjectName(QStringLiteral("groupBox_3")); label_14 = new QLabel(groupBox_3); label_14->setObjectName(QStringLiteral("label_14")); label_14->setGeometry(QRect(12, 40, 131, 33)); show_optimization_check_ = new QCheckBox(groupBox_3); show_optimization_check_->setObjectName(QStringLiteral("show_optimization_check_")); show_optimization_check_->setGeometry(QRect(10, 110, 151, 30)); show_optimization_check_->setChecked(true); show_pose_graph_check_ = new QCheckBox(groupBox_3); show_pose_graph_check_->setObjectName(QStringLiteral("show_pose_graph_check_")); show_pose_graph_check_->setGeometry(QRect(10, 80, 151, 30)); show_pose_graph_check_->setChecked(true); resolution_box_ = new QComboBox(groupBox_3); resolution_box_->setObjectName(QStringLiteral("resolution_box_")); resolution_box_->setGeometry(QRect(100, 40, 86, 32)); resolution_box_->setMaxVisibleItems(4); label_15 = new QLabel(groupBox_3); label_15->setObjectName(QStringLiteral("label_15")); label_15->setGeometry(QRect(240, 40, 71, 33)); camera_height_ = new QDoubleSpinBox(groupBox_3); camera_height_->setObjectName(QStringLiteral("camera_height_")); camera_height_->setGeometry(QRect(310, 40, 81, 33)); camera_height_->setMinimum(10); camera_height_->setMaximum(200); camera_height_->setSingleStep(10); camera_height_->setValue(100); show_pose_graph_check_1 = new QCheckBox(groupBox_3); show_pose_graph_check_1->setObjectName(QStringLiteral("show_pose_graph_check_1")); show_pose_graph_check_1->setGeometry(QRect(160, 80, 91, 30)); show_pose_graph_check_1->setChecked(true); highlight_current_ = new QCheckBox(groupBox_3); highlight_current_->setObjectName(QStringLiteral("highlight_current_")); highlight_current_->setGeometry(QRect(160, 110, 111, 30)); highlight_current_->setChecked(true); highlight_loop_ = new QCheckBox(groupBox_3); highlight_loop_->setObjectName(QStringLiteral("highlight_loop_")); highlight_loop_->setEnabled(true); highlight_loop_->setGeometry(QRect(280, 80, 111, 30)); highlight_loop_->setChecked(false); show_point_cloud_ = new QCheckBox(groupBox_3); show_point_cloud_->setObjectName(QStringLiteral("show_point_cloud_")); show_point_cloud_->setGeometry(QRect(280, 110, 151, 30)); show_point_cloud_->setChecked(true); play_speed_ = new QSlider(groupBox_3); play_speed_->setObjectName(QStringLiteral("play_speed_")); play_speed_->setGeometry(QRect(120, 160, 160, 16)); play_speed_->setMinimum(1); play_speed_->setMaximum(20); play_speed_->setOrientation(Qt::Horizontal); play_speed_->setTickPosition(QSlider::TicksBelow); label_16 = new QLabel(groupBox_3); label_16->setObjectName(QStringLiteral("label_16")); label_16->setGeometry(QRect(10, 150, 111, 24)); camera_follow_current_ = new QCheckBox(groupBox_3); camera_follow_current_->setObjectName(QStringLiteral("camera_follow_current_")); camera_follow_current_->setGeometry(QRect(290, 150, 141, 30)); camera_follow_current_->setChecked(true); gridLayout->addWidget(groupBox_3, 4, 5, 1, 5); line = new QFrame(widget); line->setObjectName(QStringLiteral("line")); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); gridLayout->addWidget(line, 5, 0, 1, 10); label_2 = new QLabel(widget); label_2->setObjectName(QStringLiteral("label_2")); gridLayout->addWidget(label_2, 6, 0, 1, 1); cur_kf_info_ = new QLineEdit(widget); cur_kf_info_->setObjectName(QStringLiteral("cur_kf_info_")); cur_kf_info_->setReadOnly(true); gridLayout->addWidget(cur_kf_info_, 6, 1, 1, 2); label_3 = new QLabel(widget); label_3->setObjectName(QStringLiteral("label_3")); gridLayout->addWidget(label_3, 6, 3, 1, 1); cur_map_info_ = new QLineEdit(widget); cur_map_info_->setObjectName(QStringLiteral("cur_map_info_")); cur_map_info_->setReadOnly(true); gridLayout->addWidget(cur_map_info_, 6, 4, 1, 4); save_map_btn_ = new QPushButton(widget); save_map_btn_->setObjectName(QStringLiteral("save_map_btn_")); gridLayout->addWidget(save_map_btn_, 6, 8, 1, 1); reset_map_btn_ = new QPushButton(widget); reset_map_btn_->setObjectName(QStringLiteral("reset_map_btn_")); gridLayout->addWidget(reset_map_btn_, 6, 9, 1, 1); MainWindow->setCentralWidget(centralWidget); menuBar = new QMenuBar(MainWindow); menuBar->setObjectName(QStringLiteral("menuBar")); menuBar->setGeometry(QRect(0, 0, 1386, 29)); MainWindow->setMenuBar(menuBar); mainToolBar = new QToolBar(MainWindow); mainToolBar->setObjectName(QStringLiteral("mainToolBar")); MainWindow->addToolBar(Qt::TopToolBarArea, mainToolBar); retranslateUi(MainWindow); QMetaObject::connectSlotsByName(MainWindow); } // setupUi void retranslateUi(QMainWindow *MainWindow) { MainWindow->setWindowTitle(QApplication::translate("MainWindow", "\347\276\216\345\233\276\344\277\256\344\277\256 V1.0", Q_NULLPTR)); label->setText(QApplication::translate("MainWindow", "\351\200\211\346\213\251DB\345\222\214Keyframe", Q_NULLPTR)); db_path_btn_->setText(QApplication::translate("MainWindow", "...", Q_NULLPTR)); kf_path_btn_->setText(QApplication::translate("MainWindow", "...", Q_NULLPTR)); load_map_btn_->setText(QApplication::translate("MainWindow", "\350\257\273\345\217\226\345\234\260\345\233\276", Q_NULLPTR)); groupBox->setTitle(QApplication::translate("MainWindow", "\346\240\207\350\256\260\345\233\236\347\216\257", Q_NULLPTR)); label_4->setText(QApplication::translate("MainWindow", "\345\205\263\351\224\256\345\270\2471 \350\223\235", Q_NULLPTR)); label_13->setText(QApplication::translate("MainWindow", "\345\205\263\351\224\256\345\270\2472 \347\273\277", Q_NULLPTR)); #ifndef QT_NO_WHATSTHIS add_loop_btn_->setWhatsThis(QApplication::translate("MainWindow", "<html><head/><body><p>\345\220\214\344\275\215\347\275\256\346\230\257\346\214\207\357\274\232\346\243\200\346\237\245\345\221\230\350\256\244\344\270\272\346\255\244\345\244\204\344\270\244\344\270\252\345\205\263\351\224\256\345\270\247\345\272\224\350\257\245\344\275\215\344\272\216\345\220\214\344\270\200\347\202\271\344\270\212\357\274\214\344\275\206\345\256\236\351\231\205\350\256\241\347\256\227\350\275\250\350\277\271\344\270\215\345\234\250\345\220\214\344\270\200\347\202\271\357\274\214\345\257\274\350\207\264\345\234\260\345\233\276\345\207\272\347\216\260\351\207\215\345\275\261\343\200\202\346\240\207\350\256\260\345\220\216\357\274\214\347\256\227\346\263\225\344\274\232\345\260\235\350\257\225\346\212\212\346\255\244\345\244\204\344\270\244\345\270\247\345\220\210\345\271\266\345\210\260\345\220\214\344\270\200\347\202\271\343\200\202</p></body></html>", Q_NULLPTR)); #endif // QT_NO_WHATSTHIS add_loop_btn_->setText(QApplication::translate("MainWindow", "\346\240\207\350\256\260\345\233\236\347\216\257", Q_NULLPTR)); label_18->setText(QApplication::translate("MainWindow", "\346\240\207\350\256\260\346\225\260\351\207\217", Q_NULLPTR)); groupBox_4->setTitle(QApplication::translate("MainWindow", "\344\274\230\345\214\226\344\277\241\346\201\257", Q_NULLPTR)); call_optimize_btn_->setText(QApplication::translate("MainWindow", "\346\211\247\350\241\214\344\274\230\345\214\226", Q_NULLPTR)); reset_optimize_btn_->setText(QApplication::translate("MainWindow", "\351\207\215\347\275\256\344\274\230\345\214\226", Q_NULLPTR)); groupBox_2->setTitle(QApplication::translate("MainWindow", "\347\274\226\350\276\221\345\205\263\351\224\256\345\270\247", Q_NULLPTR)); label_5->setText(QApplication::translate("MainWindow", "\345\205\263\351\224\256\345\270\247", Q_NULLPTR)); focus_cur_kf_btn_->setText(QApplication::translate("MainWindow", "\345\210\207\346\215\242\350\207\263\346\255\244\345\270\247", Q_NULLPTR)); label_6->setText(QApplication::translate("MainWindow", "\345\276\256\350\260\203", Q_NULLPTR)); label_7->setText(QApplication::translate("MainWindow", "X", Q_NULLPTR)); label_8->setText(QApplication::translate("MainWindow", "Y", Q_NULLPTR)); label_9->setText(QApplication::translate("MainWindow", "Z", Q_NULLPTR)); label_10->setText(QApplication::translate("MainWindow", "R", Q_NULLPTR)); label_11->setText(QApplication::translate("MainWindow", "P", Q_NULLPTR)); label_12->setText(QApplication::translate("MainWindow", "Y", Q_NULLPTR)); play_through_btn_->setText(QApplication::translate("MainWindow", "Play!", Q_NULLPTR)); groupBox_5->setTitle(QApplication::translate("MainWindow", "\350\207\252\345\212\250\345\233\236\347\216\257\346\243\200\346\265\213", Q_NULLPTR)); use_internal_loop_closing_->setText(QApplication::translate("MainWindow", "\344\275\277\347\224\250\350\207\252\345\212\250\345\233\236\347\216\257\347\273\223\346\236\234", Q_NULLPTR)); call_loop_closing_->setText(QApplication::translate("MainWindow", "\346\211\247\350\241\214\350\207\252\345\212\250\345\233\236\347\216\257\346\243\200\346\265\213", Q_NULLPTR)); fix_current_btn_->setText(QApplication::translate("MainWindow", "\345\233\272\345\256\232\345\275\223\345\211\215\345\270\247", Q_NULLPTR)); clear_fixed_btn_1->setText(QApplication::translate("MainWindow", "\346\270\205\347\251\272\345\233\272\345\256\232\345\270\247", Q_NULLPTR)); groupBox_3->setTitle(QApplication::translate("MainWindow", "\346\230\276\347\244\272\345\217\202\346\225\260", Q_NULLPTR)); label_14->setText(QApplication::translate("MainWindow", "\347\202\271\344\272\221\345\210\206\350\276\250\347\216\207", Q_NULLPTR)); show_optimization_check_->setText(QApplication::translate("MainWindow", "\346\230\276\347\244\272\344\274\230\345\214\226\344\277\241\346\201\257", Q_NULLPTR)); show_pose_graph_check_->setText(QApplication::translate("MainWindow", "\346\230\276\347\244\272Pose Graph", Q_NULLPTR)); label_15->setText(QApplication::translate("MainWindow", "\344\277\257\350\247\206\351\253\230\345\272\246", Q_NULLPTR)); show_pose_graph_check_1->setText(QApplication::translate("MainWindow", "\346\230\276\347\244\272\350\275\250\350\277\271", Q_NULLPTR)); highlight_current_->setText(QApplication::translate("MainWindow", "\351\253\230\344\272\256\345\275\223\345\211\215\345\270\247", Q_NULLPTR)); highlight_loop_->setText(QApplication::translate("MainWindow", "\351\253\230\344\272\256\345\233\236\347\216\257\345\270\247", Q_NULLPTR)); show_point_cloud_->setText(QApplication::translate("MainWindow", "\346\230\276\347\244\272\345\205\250\345\261\200\347\202\271\344\272\221", Q_NULLPTR)); label_16->setText(QApplication::translate("MainWindow", "\350\207\252\345\212\250\346\222\255\346\224\276\351\200\237\345\272\246", Q_NULLPTR)); camera_follow_current_->setText(QApplication::translate("MainWindow", "\351\225\234\345\244\264\350\267\237\351\232\217\345\275\223\345\211\215\345\270\247", Q_NULLPTR)); label_2->setText(QApplication::translate("MainWindow", "\345\205\263\351\224\256\345\270\247\344\277\241\346\201\257", Q_NULLPTR)); label_3->setText(QApplication::translate("MainWindow", "\350\277\220\350\241\214\347\212\266\346\200\201", Q_NULLPTR)); save_map_btn_->setText(QApplication::translate("MainWindow", "\344\277\235\345\255\230\345\234\260\345\233\276", Q_NULLPTR)); reset_map_btn_->setText(QApplication::translate("MainWindow", "\351\207\215\347\275\256\345\234\260\345\233\276", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class MainWindow: public Ui_MainWindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_DEBUG_UI_MAINWINDOW_H
[ "wangqi@wangqideAir.lan" ]
wangqi@wangqideAir.lan
dab63d2057d9850df030467f661d1dce12587d93
38bd665e7a80f9aa8f3acac7317c7924ed3e745a
/src/server/gui/app/guis/GuiScreensaverOptions.cpp
6537694e5fed2bc28d5680c82f09528dc8102d0c
[ "BSD-3-Clause" ]
permissive
MayaPosch/NymphCast
855cb5e05a1b979a600a8b7baf62619f4cc431dd
7ac8d5a86e1a1b4987092a3398d1fa1987f18eb6
refs/heads/master
2023-08-30T06:06:25.443885
2023-08-07T17:58:57
2023-08-07T17:58:57
169,604,606
2,405
89
BSD-3-Clause
2023-04-14T08:54:58
2019-02-07T16:38:44
C++
UTF-8
C++
false
false
2,733
cpp
#include "guis/GuiScreensaverOptions.h" #include "guis/GuiTextEditPopup.h" #include "views/ViewController.h" #include "Settings.h" #include "SystemData.h" #include "Window.h" GuiScreensaverOptions::GuiScreensaverOptions(Window* window, const char* title) : GuiComponent(window), mMenu(window, title) { addChild(&mMenu); mMenu.addButton("BACK", "go back", [this] { delete this; }); setSize((float)Renderer::getScreenWidth(), (float)Renderer::getScreenHeight()); mMenu.setPosition((mSize.x() - mMenu.getSize().x()) / 2, Renderer::getScreenHeight() * 0.15f); } GuiScreensaverOptions::~GuiScreensaverOptions() { save(); } void GuiScreensaverOptions::save() { if(!mSaveFuncs.size()) return; for(auto it = mSaveFuncs.cbegin(); it != mSaveFuncs.cend(); it++) (*it)(); Settings::getInstance()->saveFile(); } bool GuiScreensaverOptions::input(InputConfig* config, Input input) { if(config->isMappedTo("b", input) && input.value != 0) { delete this; return true; } if(config->isMappedTo("start", input) && input.value != 0) { // close everything Window* window = mWindow; while(window->peekGui() && window->peekGui() != ViewController::get()) delete window->peekGui(); return true; } return GuiComponent::input(config, input); } HelpStyle GuiScreensaverOptions::getHelpStyle() { HelpStyle style = HelpStyle(); style.applyTheme(ViewController::get()->getState().getSystem()->getTheme(), "system"); return style; } std::vector<HelpPrompt> GuiScreensaverOptions::getHelpPrompts() { std::vector<HelpPrompt> prompts = mMenu.getHelpPrompts(); prompts.push_back(HelpPrompt("b", "back")); prompts.push_back(HelpPrompt("start", "close")); return prompts; } void GuiScreensaverOptions::addEditableTextComponent(ComponentListRow row, const std::string label, std::shared_ptr<GuiComponent> ed, std::string value) { row.elements.clear(); auto lbl = std::make_shared<TextComponent>(mWindow, Utils::String::toUpper(label), Font::get(FONT_SIZE_MEDIUM), 0x777777FF); row.addElement(lbl, true); // label row.addElement(ed, true); auto spacer = std::make_shared<GuiComponent>(mWindow); spacer->setSize(Renderer::getScreenWidth() * 0.005f, 0); row.addElement(spacer, false); auto bracket = std::make_shared<ImageComponent>(mWindow); bracket->setImage(":/arrow.svg"); bracket->setResize(Vector2f(0, lbl->getFont()->getLetterHeight())); row.addElement(bracket, false); auto updateVal = [ed](const std::string& newVal) { ed->setValue(newVal); }; // ok callback (apply new value to ed) row.makeAcceptInputHandler([this, label, ed, updateVal] { mWindow->pushGui(new GuiTextEditPopup(mWindow, label, ed->getValue(), updateVal, false)); }); assert(ed); addRow(row); ed->setValue(value); }
[ "maya@nyanko.ws" ]
maya@nyanko.ws
5cb4a165b831e946c7ca04703acddf806a376895
353c425bb93fa21fead24c5c6766a017289ccbea
/Project_moban01/Project_moban01/函数模板案例.cpp
ecb6278e1b6824d4c294e167521e3c4f5d397678
[]
no_license
kass31415926/Play
7b51ddd9b0657e6f53833f0569ceff117cca2029
9f7a92d79127513e72bd799220593e99fd0c3be5
refs/heads/master
2023-06-24T03:50:42.819532
2021-07-22T10:30:27
2021-07-22T10:30:27
347,595,022
1
0
null
null
null
null
GB18030
C++
false
false
1,062
cpp
//#include <iostream> //using namespace std; // ////对数组进行排序 ////从大到小 ////选择排序 ////测试char数组与int数组 // //template<class T> //void mySwap(T& a, T& b) //{ // T temp = a; // a = b; // b = temp; //} // //template<class T> //void mySort(T arr[],int len) //{ // for (int i = 0; i < len; i++) // { // int max = i; // for (int j = i + 1; j < len; j++) // { // if (arr[max] < arr[j]) // { // max = j; // } // } // if (max != i) // { // // mySwap(arr[max], arr[i]); // } // } //} // //template<class T> //void printArray(T arr[],int len) //{ // for (int i = 0; i < len; i++) // { // cout << arr[i] << " "; // } // cout << endl; //} // //void test01() //{ // char charArr[] = "badcfe"; // int num = sizeof(charArr) / sizeof(charArr[0]); // mySort(charArr, num); // printArray(charArr, num); //} // //void test02() //{ // int intArr[] = { 7,5,6,9,3,4,1,2,0 }; // int num = sizeof(intArr) / sizeof(intArr[0]); // mySort(intArr, num); // printArray(intArr, num); //} // //int main() //{ // test02(); // return 0; //}
[ "562964277@qq.com" ]
562964277@qq.com
bde7d0b19812e26265971bca3ddb94b13abda03e
d5cdab5845e11441824bf4843062b8b902d0e682
/mediaLibrary/Item.h
dba66b303a7bcf3b57d391ed3ed61bc1fce6e088
[]
no_license
lewisNotestine/cPlusP
7edb2b3bba0da67fc2f5b205cc8120b97f1cf46f
945d9f280924ee9c5aa06468f10bc917a837ea03
refs/heads/master
2020-04-05T22:55:27.075284
2014-01-08T23:53:07
2014-01-08T23:53:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,392
h
#pragma once #include <iostream> #include <ostream> #include <set> #include <string> #include <sstream> #include <iostream> #include <iomanip> #include <stdarg.h> using namespace std; class Item { private: static string classMediaType; // set by base classes. static const int PRINT_SPACES = 11; static const string TITLE; static const string KEYWORDS; string title; string creator; set<string> keyWords; int contentDivs; protected: bool hasKeyword(const string& keyWord) const; //Returns whether or not the Item has the keyword given as param. bool hasCreator(const string& creatorName) const; //returns whether the item has the creator given by name. virtual string getClassHeader() const; //returns the class header of the object. string outputKeywords() const; //outputs a string representation of the keywords as a comma-delimited list. int getContentDivs() const; //returns the number of contentDivs(pages etc). virtual string getCreatorAndDivs() const; //returns the string output for the creator and divs. string getTitleAndKeywds() const; //returns the string getEntryRow(string headerCol, string& contentCol) const; //void setMediaType(const string& newMediaType); //sets the media type. Different for each subclass. //void setDivType(const string& newDivType); //sets the div type for the media. //void setCreatorType(const string& newCreatorType); //sets the creator type for the object. void setTitle(const string& newTitle); //sets the title of the item. void setCreator(const string& newCreator); //sets the creator/artist name of the item. void setKeywords(const set<string>& newKeywords); //sets the keywords to be void setContentDivs(const int& newContentDivs); //sets the content divs equal to param. public: static string getMediaTypeName(); //virtual string mediaTypeName() const = 0; //virtual wrapper function for static getMediaTypeName(), returning the class' . string getCreator() const; //returns the name of the creator/artist. //set<string> getKeywords() const; //returns the set of keywords. virtual string getMediaType() const = 0; //returns the media type of teh object. virtual string getCreatorType() const = 0; //reutrns the creator type. virtual string getDivType() const = 0; //returns the div type of the object (pages, tracks, etc). set<string> getKeywords() const; //returns the set of keywords. void addKeyword(const string& wordToAdd); //adds a keyword to the list. void addKeywords(const set<string>& wordsToAdd); //adds a collection of keywords to the list. Item(const string& title, const string& artist); Item(); Item(const string& newTitle); Item(const string& newTitle, const string& newCreator, const int& newDivs); Item(const string& newTitle, const string& newCreator, const int& newDivs, const int& nKeywds, ...); //std ctor to populate relevant items. virtual ~Item(); string getTitle() const; //returns the title of the Item. virtual string toString() const = 0; //outputs a string representation of the object. }; // You can't store Item* in an ItemSet, because that would disable the automatic // sorting that set does. Containers in the C++ STL are designed to store // INSTANCES, not POINTERS to instances. // // Instead we store instances of ItemPtr in the ItemSet defined in Library.h. // Each instance of ItemPtr contains a pointer to an instance of Item. In this way, // the container can call operator< for ItemPtr (which can then call operator< // for Item) to determine the order in which to store the items it's given. // // When you add a Book instance to an ItemSet, you can do things like this: // // ItemSet books; // defined in Library.h // Item *book = new Book(...); // // books.insert(book); // // The STL's set class will internally generate an instance of ItemPtr // which will contain the pointer to the instance of Book. class ItemPtr { private: Item *ptr; public: ItemPtr(Item *ptr) : ptr(ptr) { } Item* getPtr() const { return ptr; } }; // compare two instances of Item bool operator<(const Item& i1, const Item& i2); // compare two instances of ItemPtr bool operator<(const ItemPtr& ip1, const ItemPtr& ip2); ostream& operator<<(ostream& out, const Item* const item);
[ "lewis.notestine@gmail.com" ]
lewis.notestine@gmail.com
9662619b2d6903489af7d86b1c113157e608c71d
6858cbebface7beec57e60b19621120da5020a48
/sym/lookup.hpp
c173441efd04ea08c9d9aadea95fc6801b440074
[]
no_license
ponyatov/PLAI
a68b712d9ef85a283e35f9688068b392d3d51cb2
6bb25422c68c4c7717b6f0d3ceb026a520e7a0a2
refs/heads/master
2020-09-17T01:52:52.066085
2017-03-28T07:07:30
2017-03-28T07:07:30
66,084,244
2
0
null
null
null
null
UTF-8
C++
false
false
43
hpp
map<string,Sym*> lookup; // lookup table
[ "dponyatov@gmail.com" ]
dponyatov@gmail.com
3aac90112c5e7000bbe12eccb7f0775dcedf0c16
e6581e760f20a75a0c2135e10f9bf2d0b1dabd37
/Code Framework/Actions/AddSwitch.h
f2fda02c43f15f929d369d1468eec72a1d1f5a7b
[]
no_license
tokaalokda/LogicSimulator
74f4d86c3381e600e00a19e9d05b0edcb26ea3d9
6093d6d242801c0f8764b5c16889e0b9c12a153e
refs/heads/main
2023-04-06T09:37:37.428674
2023-03-21T09:19:43
2023-03-21T09:19:43
321,353,472
0
0
null
null
null
null
UTF-8
C++
false
false
487
h
#ifndef _ADD_SWITCH #define _ADD_SWITCH #include "action.h" #include "..\Components\SWITCH.h" class AddSWITCH : public Action { private: //Parameters for rectangular area to be occupied by the gate int Cx, Cy; //Center point of the gate //int x1, y1, x2, y2; //Two corners of the rectangluar area public: AddSWITCH(ApplicationManager* pApp); virtual ~AddSWITCH(void); //Execute action (code depends on action type) virtual void Execute(); }; #endif
[ "noreply@github.com" ]
noreply@github.com
a763c6a385e10553751a349d6cd3c065f9f16cad
fe8269f5d71f85641e49fdea9015ae320dde227c
/bdtaunu_postgres/McCandidateInserterPQ.h
b093f5fc4eb0a9ead7030ba835d788b18df2406a
[]
no_license
dchao34/bdtaunu_postgres
2582ba87aabf1c5d101e67e775382297c6bc9aee
fb41ef576d0246a5c10885fe3fccb3f110ce042e
refs/heads/master
2021-01-23T07:21:21.197635
2015-06-12T23:16:26
2015-06-12T23:16:26
28,880,699
0
0
null
null
null
null
UTF-8
C++
false
false
470
h
#ifndef _MCCANDIDATEINSERTERPQ_H_ #define _MCCANDIDATEINSERTERPQ_H_ #include <string> #include <libpq-fe.h> #include <bdtaunu_tuple_analyzer/BDtaunuDef.h> #include "CandidateInserterPQ.h" class McCandidateInserterPQ : public CandidateInserterPQ { public: McCandidateInserterPQ() = default; McCandidateInserterPQ(PGconn*); virtual ~McCandidateInserterPQ() = default; void set_truth_match(int); private: std::string _truth_match; }; #endif
[ "dchao@caltech.edu" ]
dchao@caltech.edu
b18faf8e8dcb87a6749050206ed7f2c10af39321
353f96ac56f02b47c71f734b42f4af9da2b7d897
/api/helpers/gizmoHelper.hpp
8fed108531c1098db4228035c947fe40c3ef27c8
[ "MIT" ]
permissive
phisko/kengine_editor
6f5ae4497a1fd3cbcdbefab30fb235f12d14b9ae
cd11f067b1339c418acf8e568e73eb00c9340722
refs/heads/master
2023-04-16T01:36:15.787050
2021-04-29T06:54:28
2021-04-29T06:54:28
271,231,520
0
0
null
null
null
null
UTF-8
C++
false
false
580
hpp
#pragma once #include <functional> #include "kengine.hpp" #include "data/TransformComponent.hpp" #include "imgui.h" namespace gizmoHelper { enum class GizmoType { Translate, Scale, Rotate }; void newFrame(const ImVec2 & windowSize, const ImVec2 & windowPos) noexcept; void drawGizmo(kengine::TransformComponent & transform, const glm::mat4 & proj, const glm::mat4 & view, const glm::mat4 * parentMatrix = nullptr, bool revertParentMatrixBeforeTransform = false) noexcept; void handleContextMenu(const std::function<void()> & displayContextMenu = nullptr) noexcept; }
[ "nicolas@phister.fr" ]
nicolas@phister.fr
3767b29aaf58530af987bed7a9fc833940c7c79e
f568e3c3f3594f112764623ef65d64afcb7a117d
/contract/src/utility/eosio_misc.hpp
35270239ac437a7d183fee0e9416cc84c22c4928
[ "MIT" ]
permissive
kryptonQuest/eosio.gre.game
9d965427316d3e3f7088a1566b3ebd60b44763ce
d8a84bb8c34ce64c3d10fff0f0ed0849e9095aa3
refs/heads/master
2022-01-19T07:01:09.796374
2018-12-27T04:29:19
2018-12-27T04:29:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
731
hpp
#pragma once #define EOSIO_DISPATCH_RHOOK( TYPE, MEMBERS ) \ extern "C" { \ void apply( uint64_t receiver, uint64_t code, uint64_t action ) { \ bool to_continue = recipient_hook( receiver, code, action ); \ if (!to_continue) { return; } \ if( code == receiver ) { \ switch( action ) { \ EOSIO_DISPATCH_HELPER( TYPE, MEMBERS ) \ } \ /* does not allow destructor of thiscontract to run: eosio_exit(0); */ \ } \ } \ } \ /// @} dispatcher #define EOSIO_ASSERT_EX(x) { \ char szMsg[512] = {0}; \ snprintf(szMsg, sizeof(szMsg)-1, \ "%s %s %d: eosio_assert: %s", \ __FILE__, __FUNCTION__, __LINE__, \ #x); \ eosio_assert((x), szMsg); }
[ "root@danx-ubuntu-16.04.5" ]
root@danx-ubuntu-16.04.5
f0c51d5dc405ded3a189b7efe23da505706bf79a
3af68b32aaa9b7522a1718b0fc50ef0cf4a704a9
/cpp/A/C/D/A/A/AACDAA.cpp
4570c344aabdf05eb208487dc2b5d923b9bf26ae
[]
no_license
devsisters/2021-NDC-ICECREAM
7cd09fa2794cbab1ab4702362a37f6ab62638d9b
ac6548f443a75b86d9e9151ff9c1b17c792b2afd
refs/heads/master
2023-03-19T06:29:03.216461
2021-03-10T02:53:14
2021-03-10T02:53:14
341,872,233
0
0
null
null
null
null
UTF-8
C++
false
false
108
cpp
#include "AACDAA.h" namespace AACDAA { std::string run() { std::string out("AACDAA"); return out; } }
[ "nakhyun@devsisters.com" ]
nakhyun@devsisters.com
c2cc8c48b2c25edeb4ebfb14e129886774fa405c
d3d1d449f06726c23b6494854676694b39153b49
/ABC209/C/main.cpp
776804115e9724760d10f0117ae3bc03f2ec7f02
[]
no_license
KEI0124/atcoder
6bf22b0aec1e2353deb1fdc1a2f5c7ce350c034a
68412b7f89ba0ccd00cf3e7ce6a28ffe88b17768
refs/heads/master
2023-07-29T03:11:23.936440
2021-09-15T08:22:16
2021-09-15T08:22:16
381,680,428
0
0
null
2021-07-03T10:13:40
2021-06-30T11:35:15
C++
UTF-8
C++
false
false
377
cpp
#include <bits/stdc++.h> #include<iostream> #include<array> #include<algorithm> using namespace std; int main() { int N,M; cin >> N >> M; vector<int> C(N); for (int i = 0; i < N; i++) { cin >> C[i]; } sort(C.begin(),C.end()); long long answer = 1; for(int i = 0; i < N; i++) { answer = answer * max(0, C[i] - i) % 1000000007; } cout << answer << endl; }
[ "milktea3314@gmail.com" ]
milktea3314@gmail.com
02c3bef6cab34d8fd8297e916054ddcab320255d
9308104daab409c0796e53c35e2c8bf2c9a8115b
/src/physics/ChNodeBase.h
3a7e7d90d2600b0547bd0f26e94fa8a5f42b37e6
[ "BSD-3-Clause" ]
permissive
ruisebastiao/chrono
77481a819484af827d1ee35c1dad6ec4b7e20a48
f7f3adf94c8adf32b686830af36af287c7a37a30
refs/heads/develop
2020-12-28T21:28:39.505808
2015-06-02T15:45:13
2015-06-02T15:45:13
36,147,489
0
0
null
2015-05-23T23:42:46
2015-05-23T23:42:45
null
UTF-8
C++
false
false
5,195
h
// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2010 Alessandro Tasora // Copyright (c) 2013 Project Chrono // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // // File author: A.Tasora #ifndef CHNODEBASE_H #define CHNODEBASE_H //#include <math.h> #include "core/ChShared.h" #include "physics/ChPhysicsItem.h" #include "physics/ChVariablesInterface.h" #include "lcp/ChLcpVariablesBodyOwnMass.h" namespace chrono { /// Class for a node, that has some degrees of /// freedom and that contain a proxy to the solver. /// It is like a lightweight version of a ChPhysicsItem, /// often a ChPhysicsItem is used as a container for a cluster /// of these ChNodeBase. class ChApi ChNodeBase : public virtual ChShared, public ChVariablesInterface { protected: unsigned int offset_x; // offset in vector of state (position part) unsigned int offset_w; // offset in vector of state (speed part) public: ChNodeBase (); virtual ~ChNodeBase (); ChNodeBase (const ChNodeBase& other); // Copy constructor ChNodeBase& operator= (const ChNodeBase& other); //Assignment operator // // FUNCTIONS // // // Functions for interfacing to the state bookkeeping // /// Get the number of degrees of freedom virtual int Get_ndof_x() = 0; /// Get the number of degrees of freedom, derivative /// This might be different from ndof if quaternions are used for rotations, /// as derivative might be angular velocity. virtual int Get_ndof_w() { return this->Get_ndof_x(); } /// Get offset in the state vector (position part) unsigned int NodeGetOffset_x() { return this->offset_x; } /// Get offset in the state vector (speed part) unsigned int NodeGetOffset_w() { return this->offset_w; } /// Set offset in the state vector (position part) void NodeSetOffset_x(const unsigned int moff) { this->offset_x= moff; } /// Set offset in the state vector (speed part) void NodeSetOffset_w(const unsigned int moff) { this->offset_w = moff; } virtual void NodeIntStateGather(const unsigned int off_x, ChState& x, const unsigned int off_v, ChStateDelta& v, double& T) {}; virtual void NodeIntStateScatter(const unsigned int off_x, const ChState& x, const unsigned int off_v, const ChStateDelta& v, const double T) {}; virtual void NodeIntStateGatherAcceleration(const unsigned int off_a, ChStateDelta& a) {}; virtual void NodeIntStateScatterAcceleration(const unsigned int off_a, const ChStateDelta& a) {}; virtual void NodeIntStateIncrement(const unsigned int off_x, ChState& x_new, const ChState& x, const unsigned int off_v, const ChStateDelta& Dv) { for (int i = 0; i< this->Get_ndof_x(); ++i) { x_new(off_x + i) = x(off_x + i) + Dv(off_v + i); } } virtual void NodeIntLoadResidual_F(const unsigned int off, ChVectorDynamic<>& R, const double c ) {}; virtual void NodeIntLoadResidual_Mv(const unsigned int off, ChVectorDynamic<>& R, const ChVectorDynamic<>& w, const double c) {}; virtual void NodeIntToLCP(const unsigned int off_v, const ChStateDelta& v, const ChVectorDynamic<>& R) {}; virtual void NodeIntFromLCP(const unsigned int off_v, ChStateDelta& v) {}; // // Functions for interfacing to the LCP solver // /// Tell to a system descriptor that there are variables of type /// ChLcpVariables in this object (for further passing it to a LCP solver) virtual void InjectVariables(ChLcpSystemDescriptor& mdescriptor) {}; /// Sets the 'fb' part (the known term) of the encapsulated ChLcpVariables to zero. virtual void VariablesFbReset() {} /// Adds the current forces (applied to node) into the /// encapsulated ChLcpVariables, in the 'fb' part: qf+=forces*factor virtual void VariablesFbLoadForces(double factor=1.) {}; /// Initialize the 'qb' part of the ChLcpVariables with the /// current value of speeds. virtual void VariablesQbLoadSpeed() {}; /// Adds M*q (masses multiplied current 'qb') to Fb, ex. if qb is initialized /// with v_old using VariablesQbLoadSpeed, this method can be used in /// timestepping schemes that do: M*v_new = M*v_old + forces*dt virtual void VariablesFbIncrementMq() {}; /// Fetches the item speed (ex. linear velocity, in xyz nodes) from the /// 'qb' part of the ChLcpVariables and sets it as the current item speed. /// If 'step' is not 0, also should compute the approximate acceleration of /// the item using backward differences, that is accel=(new_speed-old_speed)/step. /// Mostly used after the LCP provided the solution in ChLcpVariables. virtual void VariablesQbSetSpeed(double step=0.) {}; /// Increment node positions by the 'qb' part of the ChLcpVariables, /// multiplied by a 'step' factor. /// pos+=qb*step /// If qb is a speed, this behaves like a single step of 1-st order /// numerical integration (Eulero integration). virtual void VariablesQbIncrementPosition(double step) {}; }; } // END_OF_NAMESPACE____ #endif
[ "tasora@ied.unipr.it" ]
tasora@ied.unipr.it
2678bf8a72f3a35b73b983061513343ee3bf915a
6b4807b776cb05e7726964e6dd8a978194c41418
/Multiple Classes/Author.hpp
de0b0debd3c60c30cbd19d3dbb1d63685b90021d
[]
no_license
mullerpoint/CS225-Assignment-3
87166b08de09b6aa83e8e24985f53b909c5a2e87
1761a272af409215388347c381b265ed1e84acbf
refs/heads/master
2021-01-20T06:57:29.958448
2015-02-22T23:12:50
2015-02-22T23:12:50
30,730,521
0
0
null
null
null
null
UTF-8
C++
false
false
478
hpp
// //Author Class declaration // class Author { private: int birthYear; int deathYear; std::string name; bool hasData; static int active; public: Author(); ~Author(); std::string getName(); void setBirth(int); void setDeath(int); void setName(std::string); void modified(bool); bool isEmpty(); int in_mem(); void toCout(); friend std::ostream& operator<<(std::ostream &out, Author &Auth); friend std::istream& operator>>(std::istream &in, Author &Auth); };
[ "gary@mullerpoint.com" ]
gary@mullerpoint.com
8e74c9c532a83970fb18d93779e4407652c02c63
215e9bc25fd847fae79874f1a229989a5f40d034
/box.hpp
118d5aae2a24d1c8497424cde7e203ce117af65e
[]
no_license
abochenkov/box
efa0900d3781f7d460787a8aafb3e95063460d95
238986a0d765821fd68d7839351db3b3e6069b00
refs/heads/main
2023-02-14T01:34:28.741995
2021-01-11T09:13:07
2021-01-11T09:13:07
328,603,344
0
0
null
null
null
null
UTF-8
C++
false
false
210
hpp
#pragma once #include <cstdlib> class Box { public: Box(); void draw(void); void gameover(void); void crash(void); int detect_x_cord(void); private: int y_cord{0}; int x_cord{0}; };
[ "bochenkov.artyomatgmail.com" ]
bochenkov.artyomatgmail.com
f1c60aa4de38f9ce8d2539ae43bcddb8525ae3b2
b5616089db52107b91bbf7b5f245bbf0ba386cb2
/workspace/AXI_DDR_ZC706/AXI_DDR_ZC706.srcs/sources_1/bd/design_v3/ip/design_v3_xbar_0/sim/design_v3_xbar_0_sc.cpp
48b7491ff197d53da1f8c13b095e7dc0c46cec3f
[]
no_license
CharlesTousignant/gallay_DDR_ZC706
19013fbbd0f4bd908802ceb4b6cd6ebbf347cf06
8c074b4f060ff2a757905b4da4b53d6886a2896d
refs/heads/main
2023-07-01T18:38:10.873888
2021-08-03T23:03:39
2021-08-03T23:03:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,122
cpp
// (c) Copyright 1995-2021 Xilinx, Inc. All rights reserved. // // This file contains confidential and proprietary information // of Xilinx, Inc. and is protected under U.S. and // international copyright and other intellectual property // laws. // // DISCLAIMER // This disclaimer is not a license and does not grant any // rights to the materials distributed herewith. Except as // otherwise provided in a valid license issued to you by // Xilinx, and to the maximum extent permitted by applicable // law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND // WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES // AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING // BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON- // INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and // (2) Xilinx shall not be liable (whether in contract or tort, // including negligence, or under any other theory of // liability) for any loss or damage of any kind or nature // related to, arising under or in connection with these // materials, including for any direct, or any indirect, // special, incidental, or consequential loss or damage // (including loss of data, profits, goodwill, or any type of // loss or damage suffered as a result of any action brought // by a third party) even if such damage or loss was // reasonably foreseeable or Xilinx had been advised of the // possibility of the same. // // CRITICAL APPLICATIONS // Xilinx products are not designed or intended to be fail- // safe, or for use in any application requiring fail-safe // performance, such as life-support or safety devices or // systems, Class III medical devices, nuclear facilities, // applications related to the deployment of airbags, or any // other applications that could lead to death, personal // injury, or severe property or environmental damage // (individually and collectively, "Critical // Applications"). Customer assumes the sole risk and // liability of any use of Xilinx products in Critical // Applications, subject only to applicable laws and // regulations governing limitations on product liability. // // THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS // PART OF THIS FILE AT ALL TIMES. // // DO NOT MODIFY THIS FILE. #include "design_v3_xbar_0_sc.h" #include "axi_crossbar.h" #include <map> #include <string> design_v3_xbar_0_sc::design_v3_xbar_0_sc(const sc_core::sc_module_name& nm) : sc_core::sc_module(nm), mp_impl(NULL) { // configure connectivity manager xsc::utils::xsc_sim_manager::addInstance("design_v3_xbar_0", this); // initialize module xsc::common_cpp::properties model_param_props; model_param_props.addLong("C_NUM_SLAVE_SLOTS", "1"); model_param_props.addLong("C_NUM_MASTER_SLOTS", "4"); model_param_props.addLong("C_AXI_ID_WIDTH", "1"); model_param_props.addLong("C_AXI_ADDR_WIDTH", "32"); model_param_props.addLong("C_AXI_DATA_WIDTH", "32"); model_param_props.addLong("C_AXI_PROTOCOL", "2"); model_param_props.addLong("C_NUM_ADDR_RANGES", "8"); model_param_props.addLong("C_AXI_SUPPORTS_USER_SIGNALS", "0"); model_param_props.addLong("C_AXI_AWUSER_WIDTH", "1"); model_param_props.addLong("C_AXI_ARUSER_WIDTH", "1"); model_param_props.addLong("C_AXI_WUSER_WIDTH", "1"); model_param_props.addLong("C_AXI_RUSER_WIDTH", "1"); model_param_props.addLong("C_AXI_BUSER_WIDTH", "1"); model_param_props.addLong("C_R_REGISTER", "1"); model_param_props.addLong("C_CONNECTIVITY_MODE", "0"); model_param_props.addString("C_FAMILY", "zynq"); model_param_props.addBitString("C_M_AXI_BASE_ADDR", "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111000000000000000000000000000000000100000100111010000000000000000000000000000000000000000000000000010000010011100100000000000000000000000000000000000000000000000001000001001110000000000000000000000000000000000000000000000000000100000100110111000000000000000000000000000000000000000000000000010000010011011000000000000000000000000000000000000000000000000001000001001101010000000000000000000000000000000000000000000000000100000100110100000000000000000000000000000000000000000000000000010000010011001100000000000000000000000000000000000000000000000001000001001100100000000000000000000000000000000000000000000000000100000100110001000000000000000000000000000000000000000000000000010000010011000000000000000000000000000000000000000000000000000001000001001011110000000000000000000000000000000000000000000000000100000100101110000000000000000000000000000000000000000000000000010000010010110100000000000000000000000000000000000000000000000001000001001011000000000000000000000000000000000000000000000000000100000100101011000000000000000000000000000000000000000000000000010000010010101000000000000000000000000000000000000000000000000001000001001010010000000000000000000000000000000000000000000000000100000100101000000000000000000000000000000000000000000000000000010000010010011100000000000000000000000000000000000000000000000001000001001001100000000000000000000000000000000000000000000000000100000100100101000000000000000000000000000000000000000000000000010000010010010000000000000000000000000000000000000000000000000001000001001000110000000000000000000000000000000000000000000000000100000100100010000000000000000000000000000000000000000000000000010000010010000100000000000000000000000000000000000000000000000001000001001000000000000000000000", 2048); model_param_props.addBitString("C_M_AXI_ADDR_WIDTH", "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000001000000000000000000000000000000010000000000000000000000000000000100000000000000000000000000000001000000000000000000000000000000010000000000000000000000000000000100000000000000000000000000000001000000000000000000000000000000010000000000000000000000000000000100000000000000000000000000000001000000000000000000000000000000010000000000000000000000000000000100000000000000000000000000000001000000000000000000000000000000010000000000000000000000000000000100000000000000000000000000000001000000000000000000000000000000010000000000000000000000000000000100000000000000000000000000000001000000000000000000000000000000010000000000000000000000000000000100000000000000000000000000000001000000000000000000000000000000010000000000000000000000000000000100000000000000000000000000000001000000000000000000000000000000010000", 1024); model_param_props.addBitString("C_S_AXI_BASE_ID", "00000000000000000000000000000000", 32); model_param_props.addBitString("C_S_AXI_THREAD_ID_WIDTH", "00000000000000000000000000001100", 32); model_param_props.addBitString("C_M_AXI_WRITE_CONNECTIVITY", "00000000000000000000000000000001000000000000000000000000000000010000000000000000000000000000000100000000000000000000000000000001", 128); model_param_props.addBitString("C_M_AXI_READ_CONNECTIVITY", "00000000000000000000000000000001000000000000000000000000000000010000000000000000000000000000000100000000000000000000000000000001", 128); model_param_props.addBitString("C_S_AXI_SINGLE_THREAD", "00000000000000000000000000000001", 32); model_param_props.addBitString("C_S_AXI_WRITE_ACCEPTANCE", "00000000000000000000000000000001", 32); model_param_props.addBitString("C_S_AXI_READ_ACCEPTANCE", "00000000000000000000000000000001", 32); model_param_props.addBitString("C_M_AXI_WRITE_ISSUING", "00000000000000000000000000000001000000000000000000000000000000010000000000000000000000000000000100000000000000000000000000000001", 128); model_param_props.addBitString("C_M_AXI_READ_ISSUING", "00000000000000000000000000000001000000000000000000000000000000010000000000000000000000000000000100000000000000000000000000000001", 128); model_param_props.addBitString("C_S_AXI_ARB_PRIORITY", "00000000000000000000000000000000", 32); model_param_props.addBitString("C_M_AXI_SECURE", "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 128); mp_impl = new axi_crossbar("inst", model_param_props); // initialize sockets target_0_rd_socket = mp_impl->target_0_rd_socket; target_0_wr_socket = mp_impl->target_0_wr_socket; initiator_0_rd_socket = mp_impl->initiator_0_rd_socket; initiator_0_wr_socket = mp_impl->initiator_0_wr_socket; initiator_1_rd_socket = mp_impl->initiator_1_rd_socket; initiator_1_wr_socket = mp_impl->initiator_1_wr_socket; initiator_2_rd_socket = mp_impl->initiator_2_rd_socket; initiator_2_wr_socket = mp_impl->initiator_2_wr_socket; initiator_3_rd_socket = mp_impl->initiator_3_rd_socket; initiator_3_wr_socket = mp_impl->initiator_3_wr_socket; } design_v3_xbar_0_sc::~design_v3_xbar_0_sc() { xsc::utils::xsc_sim_manager::clean(); delete mp_impl; }
[ "andy.gallay@gmail.com" ]
andy.gallay@gmail.com
0ca5bb7138b336b648f27beff8d27dc12d2fe1d2
d09187219b9fff373b1d76d16af8042309909f0a
/Forthress/main/Fortress.h
a87c2f75e8875d6803384be7d42b68ed22386ff8
[]
no_license
0xporky/OOP
203b123ba44765132fcd4718dbf23016ee85d73e
c504985c8dd3878c2b832457867c43f9bb2b6e6c
refs/heads/master
2016-09-06T19:37:59.804431
2015-07-04T00:25:30
2015-07-04T00:25:30
37,733,697
0
0
null
null
null
null
UTF-8
C++
false
false
221
h
#pragma once #include "ArcherTower.h" #include "Catapult.h" class Fortress : public ArcherTower, public Catapult { public: Fortress(const int arrows_number, const int stone_number); virtual void shoot(); };
[ "0xporky@gmail.com" ]
0xporky@gmail.com
28a3e868dd9ff9b7d08e20611df94bbbfa8afcb1
fdf6b5417ca8701824dd7562853e419633738391
/ABC/ABC167.cpp
3be952f513002183ea3d56c323cf92ea7db9c952
[]
no_license
canon4444/AtCoder
b2cdb61217c2cf9ba8c66cf703f8a6ad57e97a0e
17c43cc10e25d2c7465b55e5cf7cf469bac7fd2b
refs/heads/master
2021-05-22T08:54:40.428286
2020-11-08T17:39:11
2020-11-08T17:39:11
27,902,393
2
0
null
null
null
null
UTF-8
C++
false
false
2,311
cpp
#include <iostream> #include <string> #include <algorithm> using namespace std; struct structC { int C; vector<int> A; bool operator<( const structC& right ) const { return C == right.C ? C < right.C : C < right.C; } }; void A() { // 入力 string S, T; cin >> S >> T; // 出力 // Tの先頭からSの長さの部分文字列がSと一致すればOK if( S == T.substr(0, (int)S.length()) ) cout << "Yes" << endl; else cout << "No" << endl; } void B() { // 入力 int A, B, C, K; cin >> A >> B >> C >> K; // 出力 // できるだけ1のカードを取る // 1のカードだけでたりる if( K <= A ) cout << K << endl; // 1と0のカード else if( K <= A + B ) cout << A << endl; // 全部のカード else cout << A - (K - A - B) << endl; } void C() { // 入力 int N, M, X; cin >> N >> M >> X; vector<structC> CA(N); for( int i = 0; i < N; ++i ){ cin >> CA[i].C; vector<int> tmp(M); for( int j = 0; j < M; ++j ) cin >> tmp[j]; CA[i].A = tmp; } // Cが小さい順にソート sort(CA.begin(), CA.end()); // どの本を買うか、全列挙する vector<vector<int>> textBooks; for( int i = -1; i < N; ++i ){ if( i == -1 ){ vector<int> tmp(N, 0); textBooks.push_back(tmp); } else { for( auto j : textBooks ){ vector<int> tmp = j; tmp[i] = 1; textBooks.push_back(tmp); } } } // 全列挙に応じて、高橋くんが十分に学べるか、その金額はいくらか計算する int ans = -1; for( auto isBuyBook : textBooks ){ int tns = 0; vector<int> studyingAlgorithm(M, 0); for( int j = 0; j < N; ++j ){ // 買わない本は飛ばす if( isBuyBook[j] == 0 ) continue; // 金額と理解度を足す tns += CA[j].C; for( int k = 0; k < M; ++k ) studyingAlgorithm[k] += CA[j].A[k]; } // 理解度チェック bool isPerfect = true; for( int k = 0; k < M; ++k ) if( studyingAlgorithm[k] < X ) isPerfect = false; if( isPerfect ){ if( ans == -1 ) ans = tns; else ans = min(ans, tns); } } cout << ans << endl; } int main() { //A(); //B(); C(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
ca60f6d22669b5f7c5daab89cc399b6cfdedeee9
d7cfcea7a1f5b50971d4dc8eac10c30021b0ae2f
/BStyleLineDemo/BStyleLineDemo.cpp
1d1c07a8d490c8e483a7c1ee35e1c2c87aa044fc
[]
no_license
eglrp/BezierAndBStyleLine
3f15bb2ad5b382f9a97f930d41ab91ecccbfd933
be6799d62ad066ebf0e428114bcca7b63fdb7905
refs/heads/master
2020-04-07T23:11:26.607318
2016-10-18T02:56:06
2016-10-18T02:56:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,199
cpp
// BStyleLineDemo.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "BStyleLineDemo.h" #include "MainFrm.h" #include "BStyleLineDemoDoc.h" #include "BStyleLineDemoView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CBStyleLineDemoApp BEGIN_MESSAGE_MAP(CBStyleLineDemoApp, CWinApp) //{{AFX_MSG_MAP(CBStyleLineDemoApp) ON_COMMAND(ID_APP_ABOUT, OnAppAbout) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP // Standard file based document commands ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew) ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen) // Standard print setup command ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CBStyleLineDemoApp construction CBStyleLineDemoApp::CBStyleLineDemoApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } ///////////////////////////////////////////////////////////////////////////// // The one and only CBStyleLineDemoApp object CBStyleLineDemoApp theApp; ///////////////////////////////////////////////////////////////////////////// // CBStyleLineDemoApp initialization BOOL CBStyleLineDemoApp::InitInstance() { AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking to MFC statically #endif // Change the registry key under which our settings are stored. // TODO: You should modify this string to be something appropriate // such as the name of your company or organization. SetRegistryKey(_T("Local AppWizard-Generated Applications")); LoadStdProfileSettings(); // Load standard INI file options (including MRU) // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views. CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CBStyleLineDemoDoc), RUNTIME_CLASS(CMainFrame), // main SDI frame window RUNTIME_CLASS(CBStyleLineDemoView)); AddDocTemplate(pDocTemplate); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // Dispatch commands specified on the command line if (!ProcessShellCommand(cmdInfo)) return FALSE; // The one and only window has been initialized, so show and update it. m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) // No message handlers //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() // App command to run the dialog void CBStyleLineDemoApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } ///////////////////////////////////////////////////////////////////////////// // CBStyleLineDemoApp message handlers
[ "834171100@qq.com" ]
834171100@qq.com
79156470579ec4cef86997a9a0e27bc48840274a
82b22a4f716b816c4a006cb02031d2c97ebb3051
/ExternalDependencies/Engine/Renderable.cpp
d055cf7442088774a6e01c7e44434012abe6f84f
[]
no_license
zaery/ShellSimulator
5923091c3b3cd648cba50ecf8a862d23a0691a9f
2fcb12540268b7022a6ad9c60cc6064e27ab41ab
refs/heads/master
2016-09-05T14:38:23.202234
2014-11-07T21:26:14
2014-11-07T21:26:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,450
cpp
#include "Renderable.h" #include <Qt\qdebug.h> #include "Geometry.h" #include "Vertex.h" void Renderable::setGeometry(const Geometry* g){ geo = const_cast<Geometry*>(g); } void Renderable::setWhere(const glm::mat4& where){ this->where = where; } void Renderable::setShader(uint id){ how = id; } void Renderable::useUniforms(){ for (int i=0;i<numUniforms;i++){ applyUniform(uniformNames[i], uniformDatas[i], uniformTypes[i]); } } void Renderable::applyUniform(const char* name, void* data, const int& uniformType){ GLint uniformLoc = glGetUniformLocation(how, name); if (uniformLoc >= 0){ switch(uniformType){ case GLM1IV: glUniform1iv(uniformLoc, 1, reinterpret_cast<GLint*>(const_cast<void*>(data))); break; case GLM1FV: glUniform1fv(uniformLoc, 1, reinterpret_cast<GLfloat*>(const_cast<void*>(data))); break; case GLM2FV: glUniform2fv(uniformLoc, 2, reinterpret_cast<GLfloat*>(const_cast<void*>(data))); break; case GLM3FV: glUniform3fv(uniformLoc, 3, reinterpret_cast<GLfloat*>(const_cast<void*>(data))); break; case GLM4FV: glUniform4fv(uniformLoc, 4, reinterpret_cast<GLfloat*>(const_cast<void*>(data))); break; case GLMMAT2: glUniformMatrix2fv(uniformLoc, 1, GL_FALSE, reinterpret_cast<GLfloat*>(const_cast<void*>(data))); break; case GLMMAT3: glUniformMatrix3fv(uniformLoc, 1, GL_FALSE, reinterpret_cast<GLfloat*>(const_cast<void*>(data))); break; case GLMMAT4: glUniformMatrix4fv(uniformLoc, 1, GL_FALSE, reinterpret_cast<GLfloat*>(const_cast<void*>(data))); break; } } } void Renderable::addUniform(const char* name, const void* data, int uniformType){ if (numUniforms < MAX_NUM_UNIFORMS){ uniformNames[numUniforms] = const_cast<char*>(name); uniformDatas[numUniforms] = const_cast<void*>(data); uniformTypes[numUniforms] = uniformType; ++numUniforms; } } void Renderable::setDrawMode(const uint& mode){ drawMode = mode; } void Renderable::init( const Geometry* g, const glm::mat4& transform, uint id, bool dep, uint mode){ geo = const_cast<Geometry*>(g); where = transform; how = id; drawMode = mode; hasLife = false; depth = dep; numUniforms = 0; } void Renderable::setLife(const float& life){ hasLife = true; lifeRemaining = life; } void Renderable::paint(const glm::mat4& camMat, const glm::mat4& projection){ glBindBuffer(GL_ARRAY_BUFFER, geo->vBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, geo->iBuffer); glUseProgram(how); glm::mat4 fullTransform = projection * camMat * where; useUniforms(); GLint mvpUniformLocation = glGetUniformLocation(how, "transform"); glUniformMatrix4fv(mvpUniformLocation, 1, GL_FALSE, &fullTransform[0][0]); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, Neumont::Vertex::STRIDE, BUFFER_OFFSET(Neumont::Vertex::POSITION_OFFSET+geo->vOffset)); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, Neumont::Vertex::STRIDE, BUFFER_OFFSET(Neumont::Vertex::COLOR_OFFSET+geo->vOffset)); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, Neumont::Vertex::STRIDE, BUFFER_OFFSET(Neumont::Vertex::NORMAL_OFFSET+geo->vOffset)); glUniformMatrix4fv(mvpUniformLocation, 1, GL_FALSE, &fullTransform[0][0]); if (!depth) glDepthFunc( GL_ALWAYS ); glDrawElements( drawMode, geo->numIndices, GL_UNSIGNED_SHORT, BUFFER_OFFSET(geo->iOffset)); if (!depth) glDepthFunc( GL_LESS ); }
[ "zaryzen@gmail.com" ]
zaryzen@gmail.com
bdbc99b5fb4b851ba5ad331300594e145c06ad46
3b82c429e5cb18be36eadc69615a6aee81d5818d
/Queues/Reverse_Queue.cpp
6ce0c915e75466ebead6444a542ec1ea24320ea0
[]
no_license
mehra-deepak/CN-DS-ALGO
f165090d4804ca09e71ebb4ce58b782e91796b3d
322052ab2938e1d410f86e41f9fe4386ac04da75
refs/heads/master
2023-01-07T20:53:36.067823
2020-11-06T08:11:00
2020-11-06T08:11:00
284,454,031
1
0
null
null
null
null
UTF-8
C++
false
false
183
cpp
#include <queue> void reverseQueue(queue<int> &q) { if(q.empty()) return; int data=q.front(); q.pop(); reverseQueue(q); q.push(data); }
[ "mehradeepak0608@gmail.com" ]
mehradeepak0608@gmail.com
86f254ba972e232661c529d802274fb210e36734
502769e9b0c881ae1404ef078690e56c7cdf7413
/UVa_11520_DFS.cpp
da4129a51b4f6cf03451e4581d8bcfbbf873af83
[]
no_license
climberpi/problem-solving
8bfbb80c84be4b91736b05249fa40a71f53bd968
6c17198d453e46230912bddb5c44878657a4565c
refs/heads/master
2021-05-16T03:14:02.287645
2016-09-29T16:43:14
2016-09-29T16:43:14
8,769,274
0
0
null
null
null
null
UTF-8
C++
false
false
1,055
cpp
#include<cstdio> #include<cstring> const int MAXn = 10 + 5; int G[MAXn][MAXn], n; bool dfs(int i, int j) { if(i == n+1) return 1; if(j == n+1) return dfs(i+1, 1); if(G[i][j] != -1) return dfs(i, j+1); for(int k = 0; k < 26; k++) if(G[i-1][j] != k && G[i+1][j] != k && G[i][j-1] != k && G[i][j+1] != k) { G[i][j] = k; if(dfs(i, j+1)) return 1; } return 0; } int readit() { char x = 0; while(!(x == '.' || ('A' <= x && x <= 'Z'))) scanf("%c", &x); return x == '.' ? -1 : x - 'A'; } int main(){ int T; scanf("%d", &T); for(int k = 1; k <= T; k++) { memset(G, -1, sizeof(G)); scanf("%d", &n); for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) G[i][j] = readit(); dfs(1, 1); printf("Case %d:\n", k); for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) printf("%c", G[i][j] + 'A'); printf("\n"); } } return 0; }
[ "liuyupan@gmail.com" ]
liuyupan@gmail.com
7e9e3536b4553404fec98ccac14c08bc083893fb
93488a83bf37ddb73b65907a4006957f30618be6
/Spoj/ADDREV.cpp
8f705307efd9192686c65536da2bba852a70cad7
[]
no_license
techsand/Competitive-Programming
760de6cc71facf8b9434373995c85fcb871b83aa
a05940fcf31be6f82559fe6e2ee8e2ad4ed51026
refs/heads/master
2021-01-19T11:33:05.786681
2014-03-05T10:11:35
2014-03-05T10:11:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
344
cpp
#include<stdio.h> int reverse(int n){ int rev=0; while(n) { rev=10*rev+n%10; n/=10; } return rev; } int main(){ int a,b,cases; scanf("%d",&cases); while(cases--){ scanf("%d%d",&a,&b); printf("%d\n",reverse(reverse(a)+reverse(b))); } return 0; }
[ "nainybits@gmail.com" ]
nainybits@gmail.com
33976b75218026d901e4b94918aa5dd67ba97a8b
aaf7b95178b1342ef0f7cb41cda19e8d62dd82e4
/tests/UnitTests/ArrayRefTests.cpp
62c4fa3ca7f8556d59dd8ff3bd0e3ddd322ec26e
[ "MIT", "BSD-3-Clause" ]
permissive
mounirrquiba/novocoin-project
45c70b306eaa23350e2f398ae3057595dede6698
cb99bf47014343eabc0d1131d93fa050a07e430d
refs/heads/master
2020-03-10T03:07:01.908338
2018-04-09T22:29:13
2018-04-09T22:29:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,063
cpp
// Copyright (c) 2018 The Novocoin developers, Parts of this file are originally copyright (c) 2011-2016 The Cryptonote developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <Common/ArrayRef.h> #include <gtest/gtest.h> using namespace Common; TEST(ArrayRefTests, representations) { ASSERT_NE(nullptr, ArrayRef<>::EMPTY.getData()); ASSERT_EQ(0, ArrayRef<>::EMPTY.getSize()); ASSERT_EQ(nullptr, ArrayRef<>::NIL.getData()); ASSERT_EQ(0, ArrayRef<>::NIL.getSize()); } TEST(ArrayRefTests, directConstructor) { uint8_t data[4] = {2, 3, 5, 7}; ASSERT_EQ(data, ArrayRef<>(data, 4).getData()); ASSERT_EQ(4, ArrayRef<>(data, 4).getSize()); } TEST(ArrayRefTests, arrayConstructor) { uint8_t data[4] = {2, 3, 5, 7}; ASSERT_EQ(data, ArrayRef<>(data).getData()); ASSERT_EQ(4, ArrayRef<>(data).getSize()); } TEST(ArrayRefTests, copyConstructor) { uint8_t data[4] = {2, 3, 5, 7}; const ArrayRef<> ref(data); ASSERT_EQ(ref.getData(), ArrayRef<>(ref).getData()); ASSERT_EQ(ref.getSize(), ArrayRef<>(ref).getSize()); } TEST(ArrayRefTests, copyAssignment) { uint8_t data[4] = {2, 3, 5, 7}; const ArrayRef<> ref1(data); ArrayRef<> ref2; ref2 = ref1; ASSERT_EQ(ref1.getData(), ref2.getData()); ASSERT_EQ(ref1.getSize(), ref2.getSize()); } TEST(ArrayRefTests, arrayView) { uint8_t data[4] = {2, 3, 5, 7}; const ArrayRef<> ref(data); ArrayView<> view = ref; ASSERT_EQ(ref.getData(), view.getData()); ASSERT_EQ(ref.getSize(), view.getSize()); } TEST(ArrayRefTests, emptyNil) { ASSERT_TRUE(ArrayRef<>::EMPTY.isEmpty()); ASSERT_FALSE(ArrayRef<>::EMPTY.isNil()); ASSERT_TRUE(ArrayRef<>::NIL.isEmpty()); ASSERT_TRUE(ArrayRef<>::NIL.isNil()); uint8_t data[4] = {2, 3, 5, 7}; ASSERT_TRUE(ArrayRef<>(data, 0).isEmpty()); ASSERT_FALSE(ArrayRef<>(data, 0).isNil()); ASSERT_FALSE(ArrayRef<>(data).isEmpty()); ASSERT_FALSE(ArrayRef<>(data).isNil()); } TEST(ArrayRefTests, squareBrackets) { uint8_t data[4] = {2, 3, 5, 7}; const ArrayRef<> ref(data); ASSERT_EQ(data + 0, &ref[0]); ASSERT_EQ(data + 1, &ref[1]); ASSERT_EQ(data + 2, &ref[2]); ASSERT_EQ(data + 3, &ref[3]); } TEST(ArrayRefTests, firstLast) { uint8_t data[4] = {2, 3, 5, 7}; const ArrayRef<> ref(data); ASSERT_EQ(data + 0, &ref.first()); ASSERT_EQ(data + 3, &ref.last()); } TEST(ArrayRefTests, beginEnd) { uint8_t data[4] = {2, 3, 5, 7}; ASSERT_EQ(nullptr, ArrayRef<>::NIL.begin()); ASSERT_EQ(nullptr, ArrayRef<>::NIL.end()); ASSERT_EQ(data, ArrayRef<>(data).begin()); ASSERT_EQ(data + 4, ArrayRef<>(data).end()); size_t offset = 0; for (uint8_t& value : ArrayRef<>(data)) { ASSERT_EQ(data[offset], value); ++offset; } } TEST(ArrayRefTests, comparisons) { uint8_t data1[3] = {2, 3, 5}; uint8_t data2[4] = {2, 3, 5, 7}; uint8_t data3[4] = {2, 3, 5, 7}; uint8_t data4[5] = {2, 3, 5, 7, 11}; uint8_t data5[4] = {13, 17, 19, 23}; ASSERT_TRUE(ArrayRef<>::EMPTY == ArrayView<>::EMPTY); ASSERT_TRUE(ArrayRef<>::EMPTY == ArrayView<>::NIL); ASSERT_FALSE(ArrayRef<>::EMPTY == ArrayView<>(data1)); ASSERT_TRUE(ArrayRef<>::NIL == ArrayView<>::EMPTY); ASSERT_TRUE(ArrayRef<>::NIL == ArrayView<>::NIL); ASSERT_FALSE(ArrayRef<>::NIL == ArrayView<>(data1)); ASSERT_FALSE(ArrayRef<>(data2) == ArrayView<>::EMPTY); ASSERT_FALSE(ArrayRef<>(data2) == ArrayView<>::NIL); ASSERT_FALSE(ArrayRef<>(data2) == ArrayView<>(data1)); ASSERT_TRUE(ArrayRef<>(data2) == ArrayView<>(data2)); ASSERT_TRUE(ArrayRef<>(data2) == ArrayView<>(data3)); ASSERT_FALSE(ArrayRef<>(data2) == ArrayView<>(data4)); ASSERT_FALSE(ArrayRef<>(data2) == ArrayView<>(data5)); ASSERT_FALSE(ArrayRef<>::EMPTY != ArrayView<>::EMPTY); ASSERT_FALSE(ArrayRef<>::EMPTY != ArrayView<>::NIL); ASSERT_TRUE(ArrayRef<>::EMPTY != ArrayView<>(data1)); ASSERT_FALSE(ArrayRef<>::NIL != ArrayView<>::EMPTY); ASSERT_FALSE(ArrayRef<>::NIL != ArrayView<>::NIL); ASSERT_TRUE(ArrayRef<>::NIL != ArrayView<>(data1)); ASSERT_TRUE(ArrayRef<>(data2) != ArrayView<>::EMPTY); ASSERT_TRUE(ArrayRef<>(data2) != ArrayView<>::NIL); ASSERT_TRUE(ArrayRef<>(data2) != ArrayView<>(data1)); ASSERT_FALSE(ArrayRef<>(data2) != ArrayView<>(data2)); ASSERT_FALSE(ArrayRef<>(data2) != ArrayView<>(data3)); ASSERT_TRUE(ArrayRef<>(data2) != ArrayView<>(data4)); ASSERT_TRUE(ArrayRef<>(data2) != ArrayView<>(data5)); } TEST(ArrayRefTests, beginsWith) { uint8_t data1[3] = {2, 3, 5}; uint8_t data2[4] = {2, 3, 5, 7}; uint8_t data3[4] = {2, 3, 5, 7}; uint8_t data4[5] = {2, 3, 5, 7, 11}; uint8_t data5[4] = {13, 17, 19, 23}; ASSERT_FALSE(ArrayRef<>::EMPTY.beginsWith(data1[0])); ASSERT_TRUE(ArrayRef<>::EMPTY.beginsWith(ArrayView<>::EMPTY)); ASSERT_TRUE(ArrayRef<>::EMPTY.beginsWith(ArrayView<>::NIL)); ASSERT_FALSE(ArrayRef<>::EMPTY.beginsWith(ArrayView<>(data1))); ASSERT_FALSE(ArrayRef<>::NIL.beginsWith(data1[0])); ASSERT_TRUE(ArrayRef<>::NIL.beginsWith(ArrayView<>::EMPTY)); ASSERT_TRUE(ArrayRef<>::NIL.beginsWith(ArrayView<>::NIL)); ASSERT_FALSE(ArrayRef<>::NIL.beginsWith(ArrayView<>(data1))); ASSERT_TRUE(ArrayRef<>(data2).beginsWith(data1[0])); ASSERT_FALSE(ArrayRef<>(data2).beginsWith(data5[0])); ASSERT_TRUE(ArrayRef<>(data2).beginsWith(ArrayView<>::EMPTY)); ASSERT_TRUE(ArrayRef<>(data2).beginsWith(ArrayView<>::NIL)); ASSERT_TRUE(ArrayRef<>(data2).beginsWith(ArrayView<>(data1))); ASSERT_TRUE(ArrayRef<>(data2).beginsWith(ArrayView<>(data2))); ASSERT_TRUE(ArrayRef<>(data2).beginsWith(ArrayView<>(data3))); ASSERT_FALSE(ArrayRef<>(data2).beginsWith(ArrayView<>(data4))); ASSERT_FALSE(ArrayRef<>(data2).beginsWith(ArrayView<>(data5))); } TEST(ArrayRefTests, contains) { uint8_t data1[2] = {3, 5}; uint8_t data2[4] = {2, 3, 5, 7}; uint8_t data3[4] = {2, 3, 5, 7}; uint8_t data4[5] = {2, 3, 5, 7, 11}; uint8_t data5[4] = {13, 17, 19, 23}; ASSERT_FALSE(ArrayRef<>::EMPTY.contains(data1[1])); ASSERT_TRUE(ArrayRef<>::EMPTY.contains(ArrayView<>::EMPTY)); ASSERT_TRUE(ArrayRef<>::EMPTY.contains(ArrayView<>::NIL)); ASSERT_FALSE(ArrayRef<>::EMPTY.contains(ArrayView<>(data1))); ASSERT_FALSE(ArrayRef<>::NIL.contains(data1[1])); ASSERT_TRUE(ArrayRef<>::NIL.contains(ArrayView<>::EMPTY)); ASSERT_TRUE(ArrayRef<>::NIL.contains(ArrayView<>::NIL)); ASSERT_FALSE(ArrayRef<>::NIL.contains(ArrayView<>(data1))); ASSERT_TRUE(ArrayRef<>(data2).contains(data1[1])); ASSERT_FALSE(ArrayRef<>(data2).contains(data5[1])); ASSERT_TRUE(ArrayRef<>(data2).contains(ArrayView<>::EMPTY)); ASSERT_TRUE(ArrayRef<>(data2).contains(ArrayView<>::NIL)); ASSERT_TRUE(ArrayRef<>(data2).contains(ArrayView<>(data1))); ASSERT_TRUE(ArrayRef<>(data2).contains(ArrayView<>(data2))); ASSERT_TRUE(ArrayRef<>(data2).contains(ArrayView<>(data3))); ASSERT_FALSE(ArrayRef<>(data2).contains(ArrayView<>(data4))); ASSERT_FALSE(ArrayRef<>(data2).contains(ArrayView<>(data5))); } TEST(ArrayRefTests, endsWith) { uint8_t data1[3] = {3, 5, 7}; uint8_t data2[4] = {2, 3, 5, 7}; uint8_t data3[4] = {2, 3, 5, 7}; uint8_t data4[5] = {2, 3, 5, 7, 11}; uint8_t data5[4] = {13, 17, 19, 23}; ASSERT_FALSE(ArrayRef<>::EMPTY.endsWith(data1[2])); ASSERT_TRUE(ArrayRef<>::EMPTY.endsWith(ArrayView<>::EMPTY)); ASSERT_TRUE(ArrayRef<>::EMPTY.endsWith(ArrayView<>::NIL)); ASSERT_FALSE(ArrayRef<>::EMPTY.endsWith(ArrayView<>(data1))); ASSERT_FALSE(ArrayRef<>::NIL.endsWith(data1[2])); ASSERT_TRUE(ArrayRef<>::NIL.endsWith(ArrayView<>::EMPTY)); ASSERT_TRUE(ArrayRef<>::NIL.endsWith(ArrayView<>::NIL)); ASSERT_FALSE(ArrayRef<>::NIL.endsWith(ArrayView<>(data1))); ASSERT_TRUE(ArrayRef<>(data2).endsWith(data1[2])); ASSERT_FALSE(ArrayRef<>(data2).endsWith(data5[3])); ASSERT_TRUE(ArrayRef<>(data2).endsWith(ArrayView<>::EMPTY)); ASSERT_TRUE(ArrayRef<>(data2).endsWith(ArrayView<>::NIL)); ASSERT_TRUE(ArrayRef<>(data2).endsWith(ArrayView<>(data1))); ASSERT_TRUE(ArrayRef<>(data2).endsWith(ArrayView<>(data2))); ASSERT_TRUE(ArrayRef<>(data2).endsWith(ArrayView<>(data3))); ASSERT_FALSE(ArrayRef<>(data2).endsWith(ArrayView<>(data4))); ASSERT_FALSE(ArrayRef<>(data2).endsWith(ArrayView<>(data5))); } TEST(ArrayRefTests, find) { uint8_t data1[2] = {3, 5}; uint8_t data2[6] = {2, 3, 5, 3, 5, 7}; uint8_t data3[6] = {2, 3, 5, 3, 5, 7}; uint8_t data4[7] = {2, 3, 5, 3, 5, 7, 11}; uint8_t data5[4] = {13, 17, 19, 23}; ASSERT_EQ(ArrayRef<>::INVALID, ArrayRef<>::EMPTY.find(data1[0])); ASSERT_EQ(0, ArrayRef<>::EMPTY.find(ArrayView<>::EMPTY)); ASSERT_EQ(0, ArrayRef<>::EMPTY.find(ArrayView<>::NIL)); ASSERT_EQ(ArrayRef<>::INVALID, ArrayRef<>::EMPTY.find(ArrayView<>(data1))); ASSERT_EQ(ArrayRef<>::INVALID, ArrayRef<>::NIL.find(data1[0])); ASSERT_EQ(0, ArrayRef<>::NIL.find(ArrayView<>::EMPTY)); ASSERT_EQ(0, ArrayRef<>::NIL.find(ArrayView<>::NIL)); ASSERT_EQ(ArrayRef<>::INVALID, ArrayRef<>::NIL.find(ArrayView<>(data1))); ASSERT_EQ(1, ArrayRef<>(data2).find(data1[0])); ASSERT_EQ(ArrayRef<>::INVALID, ArrayRef<>(data2).find(data5[1])); ASSERT_EQ(0, ArrayRef<>(data2).find(ArrayView<>::EMPTY)); ASSERT_EQ(0, ArrayRef<>(data2).find(ArrayView<>::NIL)); ASSERT_EQ(1, ArrayRef<>(data2).find(ArrayView<>(data1))); ASSERT_EQ(0, ArrayRef<>(data2).find(ArrayView<>(data2))); ASSERT_EQ(0, ArrayRef<>(data2).find(ArrayView<>(data3))); ASSERT_EQ(ArrayRef<>::INVALID, ArrayRef<>(data2).find(ArrayView<>(data4))); ASSERT_EQ(ArrayRef<>::INVALID, ArrayRef<>(data2).find(ArrayView<>(data5))); } TEST(ArrayRefTests, findLast) { uint8_t data1[2] = {3, 5}; uint8_t data2[6] = {2, 3, 5, 3, 5, 7}; uint8_t data3[6] = {2, 3, 5, 3, 5, 7}; uint8_t data4[7] = {2, 3, 5, 3, 5, 7, 11}; uint8_t data5[4] = {13, 17, 19, 23}; ASSERT_EQ(ArrayRef<>::INVALID, ArrayRef<>::EMPTY.findLast(data1[0])); ASSERT_EQ(0, ArrayRef<>::EMPTY.findLast(ArrayView<>::EMPTY)); ASSERT_EQ(0, ArrayRef<>::EMPTY.findLast(ArrayView<>::NIL)); ASSERT_EQ(ArrayRef<>::INVALID, ArrayRef<>::EMPTY.findLast(ArrayView<>(data1))); ASSERT_EQ(ArrayRef<>::INVALID, ArrayRef<>::NIL.findLast(data1[0])); ASSERT_EQ(0, ArrayRef<>::NIL.findLast(ArrayView<>::EMPTY)); ASSERT_EQ(0, ArrayRef<>::NIL.findLast(ArrayView<>::NIL)); ASSERT_EQ(ArrayRef<>::INVALID, ArrayRef<>::NIL.findLast(ArrayView<>(data1))); ASSERT_EQ(3, ArrayRef<>(data2).findLast(data1[0])); ASSERT_EQ(ArrayRef<>::INVALID, ArrayRef<>(data2).findLast(data5[1])); ASSERT_EQ(6, ArrayRef<>(data2).findLast(ArrayView<>::EMPTY)); ASSERT_EQ(6, ArrayRef<>(data2).findLast(ArrayView<>::NIL)); ASSERT_EQ(3, ArrayRef<>(data2).findLast(ArrayView<>(data1))); ASSERT_EQ(0, ArrayRef<>(data2).findLast(ArrayView<>(data2))); ASSERT_EQ(0, ArrayRef<>(data2).findLast(ArrayView<>(data3))); ASSERT_EQ(ArrayRef<>::INVALID, ArrayRef<>(data2).findLast(ArrayView<>(data4))); ASSERT_EQ(ArrayRef<>::INVALID, ArrayRef<>(data2).findLast(ArrayView<>(data5))); } TEST(ArrayRefTests, head) { uint8_t data[4] = {2, 3, 5, 7}; ASSERT_EQ(0, ArrayRef<>::EMPTY.head(0).getSize()); ASSERT_EQ(ArrayRef<>(nullptr, 0), ArrayRef<>::NIL.head(0)); ASSERT_EQ(ArrayRef<>(data, 0), ArrayRef<>(data).head(0)); ASSERT_EQ(ArrayRef<>(data, 2), ArrayRef<>(data).head(2)); ASSERT_EQ(ArrayRef<>(data, 4), ArrayRef<>(data).head(4)); } TEST(ArrayRefTests, tail) { uint8_t data[4] = {2, 3, 5, 7}; ASSERT_EQ(0, ArrayRef<>::EMPTY.tail(0).getSize()); ASSERT_EQ(ArrayRef<>(nullptr, 0), ArrayRef<>::NIL.tail(0)); ASSERT_EQ(ArrayRef<>(data + 4, 0), ArrayRef<>(data).tail(0)); ASSERT_EQ(ArrayRef<>(data + 2, 2), ArrayRef<>(data).tail(2)); ASSERT_EQ(ArrayRef<>(data, 4), ArrayRef<>(data).tail(4)); } TEST(ArrayRefTests, unhead) { uint8_t data[4] = {2, 3, 5, 7}; ASSERT_EQ(0, ArrayRef<>::EMPTY.unhead(0).getSize()); ASSERT_EQ(ArrayRef<>(nullptr, 0), ArrayRef<>::NIL.unhead(0)); ASSERT_EQ(ArrayRef<>(data, 4), ArrayRef<>(data).unhead(0)); ASSERT_EQ(ArrayRef<>(data + 2, 2), ArrayRef<>(data).unhead(2)); ASSERT_EQ(ArrayRef<>(data + 4, 0), ArrayRef<>(data).unhead(4)); } TEST(ArrayRefTests, untail) { uint8_t data[4] = {2, 3, 5, 7}; ASSERT_EQ(0, ArrayRef<>::EMPTY.untail(0).getSize()); ASSERT_EQ(ArrayRef<>(nullptr, 0), ArrayRef<>::NIL.untail(0)); ASSERT_EQ(ArrayRef<>(data, 4), ArrayRef<>(data).untail(0)); ASSERT_EQ(ArrayRef<>(data, 2), ArrayRef<>(data).untail(2)); ASSERT_EQ(ArrayRef<>(data, 0), ArrayRef<>(data).untail(4)); } TEST(ArrayRefTests, range) { uint8_t data[4] = {2, 3, 5, 7}; ASSERT_EQ(0, ArrayRef<>::EMPTY.range(0, 0).getSize()); ASSERT_EQ(ArrayRef<>(nullptr, 0), ArrayRef<>::NIL.range(0, 0)); ASSERT_EQ(ArrayRef<>(data + 0, 0), ArrayRef<>(data).range(0, 0)); ASSERT_EQ(ArrayRef<>(data + 0, 2), ArrayRef<>(data).range(0, 2)); ASSERT_EQ(ArrayRef<>(data + 0, 4), ArrayRef<>(data).range(0, 4)); ASSERT_EQ(ArrayRef<>(data + 2, 0), ArrayRef<>(data).range(2, 2)); ASSERT_EQ(ArrayRef<>(data + 2, 2), ArrayRef<>(data).range(2, 4)); ASSERT_EQ(ArrayRef<>(data + 4, 0), ArrayRef<>(data).range(4, 4)); } TEST(ArrayRefTests, slice) { uint8_t data[4] = {2, 3, 5, 7}; ASSERT_EQ(0, ArrayRef<>::EMPTY.slice(0, 0).getSize()); ASSERT_EQ(ArrayRef<>(nullptr, 0), ArrayRef<>::NIL.slice(0, 0)); ASSERT_EQ(ArrayRef<>(data + 0, 0), ArrayRef<>(data).slice(0, 0)); ASSERT_EQ(ArrayRef<>(data + 0, 2), ArrayRef<>(data).slice(0, 2)); ASSERT_EQ(ArrayRef<>(data + 0, 4), ArrayRef<>(data).slice(0, 4)); ASSERT_EQ(ArrayRef<>(data + 2, 0), ArrayRef<>(data).slice(2, 0)); ASSERT_EQ(ArrayRef<>(data + 2, 2), ArrayRef<>(data).slice(2, 2)); ASSERT_EQ(ArrayRef<>(data + 4, 0), ArrayRef<>(data).slice(4, 0)); } TEST(ArrayRefTests, fill) { uint8_t data[4] = {2, 3, 5, 7}; const ArrayRef<> ref(data); ASSERT_EQ(ArrayRef<>(data), ref.fill(11)); ASSERT_EQ(11, data[0]); ASSERT_EQ(11, data[1]); ASSERT_EQ(11, data[2]); ASSERT_EQ(11, data[3]); } TEST(ArrayRefTests, reverse) { uint8_t data[4] = {2, 3, 5, 7}; const ArrayRef<> ref(data); ASSERT_EQ(ArrayRef<>(data), ref.reverse()); ASSERT_EQ(7, data[0]); ASSERT_EQ(5, data[1]); ASSERT_EQ(3, data[2]); ASSERT_EQ(2, data[3]); }
[ "37153171+techqc@users.noreply.github.com" ]
37153171+techqc@users.noreply.github.com
ac3beab43e483d2a22bc7ccbef6bdeb69aacc658
a2206795a05877f83ac561e482e7b41772b22da8
/Source/PV/build/VTK/Wrapping/Python/vtkCompositeInterpolatedVelocityFieldPython.cxx
0485c38190a18beb9479ffe72d18ad6266ba6b9c
[]
no_license
supreethms1809/mpas-insitu
5578d465602feb4d6b239a22912c33918c7bb1c3
701644bcdae771e6878736cb6f49ccd2eb38b36e
refs/heads/master
2020-03-25T16:47:29.316814
2018-08-08T02:00:13
2018-08-08T02:00:13
143,947,446
0
0
null
null
null
null
UTF-8
C++
false
false
20,450
cxx
// python wrapper for vtkCompositeInterpolatedVelocityField // #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include "vtkPythonArgs.h" #include "vtkPythonOverload.h" #include "vtkConfigure.h" #include <vtksys/ios/sstream> #include "vtkIndent.h" #include "vtkCompositeInterpolatedVelocityField.h" #if defined(VTK_BUILD_SHARED_LIBS) # define VTK_PYTHON_EXPORT VTK_ABI_EXPORT # define VTK_PYTHON_IMPORT VTK_ABI_IMPORT #else # define VTK_PYTHON_EXPORT VTK_ABI_EXPORT # define VTK_PYTHON_IMPORT VTK_ABI_EXPORT #endif extern "C" { VTK_PYTHON_EXPORT void PyVTKAddFile_vtkCompositeInterpolatedVelocityField(PyObject *, const char *); } extern "C" { VTK_PYTHON_EXPORT PyObject *PyVTKClass_vtkCompositeInterpolatedVelocityFieldNew(const char *); } #ifndef DECLARED_PyVTKClass_vtkAbstractInterpolatedVelocityFieldNew extern "C" { PyObject *PyVTKClass_vtkAbstractInterpolatedVelocityFieldNew(const char *); } #define DECLARED_PyVTKClass_vtkAbstractInterpolatedVelocityFieldNew #endif static const char **PyvtkCompositeInterpolatedVelocityField_Doc(); static PyObject * PyvtkCompositeInterpolatedVelocityField_GetClassName(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "GetClassName"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkCompositeInterpolatedVelocityField *op = static_cast<vtkCompositeInterpolatedVelocityField *>(vp); PyObject *result = NULL; if (op && ap.CheckArgCount(0)) { const char *tempr = (ap.IsBound() ? op->GetClassName() : op->vtkCompositeInterpolatedVelocityField::GetClassName()); if (!ap.ErrorOccurred()) { result = ap.BuildValue(tempr); } } return result; } static PyObject * PyvtkCompositeInterpolatedVelocityField_IsA(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "IsA"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkCompositeInterpolatedVelocityField *op = static_cast<vtkCompositeInterpolatedVelocityField *>(vp); char *temp0 = NULL; PyObject *result = NULL; if (op && ap.CheckArgCount(1) && ap.GetValue(temp0)) { int tempr = (ap.IsBound() ? op->IsA(temp0) : op->vtkCompositeInterpolatedVelocityField::IsA(temp0)); if (!ap.ErrorOccurred()) { result = ap.BuildValue(tempr); } } return result; } static PyObject * PyvtkCompositeInterpolatedVelocityField_NewInstance(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "NewInstance"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkCompositeInterpolatedVelocityField *op = static_cast<vtkCompositeInterpolatedVelocityField *>(vp); PyObject *result = NULL; if (op && ap.CheckArgCount(0)) { vtkCompositeInterpolatedVelocityField *tempr = (ap.IsBound() ? op->NewInstance() : op->vtkCompositeInterpolatedVelocityField::NewInstance()); if (!ap.ErrorOccurred()) { result = ap.BuildVTKObject(tempr); if (result && PyVTKObject_Check(result)) { PyVTKObject_GetObject(result)->UnRegister(0); PyVTKObject_SetFlag(result, VTK_PYTHON_IGNORE_UNREGISTER, 1); } } } return result; } static PyObject * PyvtkCompositeInterpolatedVelocityField_SafeDownCast(PyObject *, PyObject *args) { vtkPythonArgs ap(args, "SafeDownCast"); vtkObject *temp0 = NULL; PyObject *result = NULL; if (ap.CheckArgCount(1) && ap.GetVTKObject(temp0, "vtkObject")) { vtkCompositeInterpolatedVelocityField *tempr = vtkCompositeInterpolatedVelocityField::SafeDownCast(temp0); if (!ap.ErrorOccurred()) { result = ap.BuildVTKObject(tempr); } } return result; } static PyObject * PyvtkCompositeInterpolatedVelocityField_GetLastDataSetIndex(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "GetLastDataSetIndex"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkCompositeInterpolatedVelocityField *op = static_cast<vtkCompositeInterpolatedVelocityField *>(vp); PyObject *result = NULL; if (op && ap.CheckArgCount(0)) { int tempr = (ap.IsBound() ? op->GetLastDataSetIndex() : op->vtkCompositeInterpolatedVelocityField::GetLastDataSetIndex()); if (!ap.ErrorOccurred()) { result = ap.BuildValue(tempr); } } return result; } static PyObject * PyvtkCompositeInterpolatedVelocityField_GetLastDataSet(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "GetLastDataSet"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkCompositeInterpolatedVelocityField *op = static_cast<vtkCompositeInterpolatedVelocityField *>(vp); PyObject *result = NULL; if (op && ap.CheckArgCount(0)) { vtkDataSet *tempr = (ap.IsBound() ? op->GetLastDataSet() : op->vtkCompositeInterpolatedVelocityField::GetLastDataSet()); if (!ap.ErrorOccurred()) { result = ap.BuildVTKObject(tempr); } } return result; } static PyObject * PyvtkCompositeInterpolatedVelocityField_AddDataSet(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "AddDataSet"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkCompositeInterpolatedVelocityField *op = static_cast<vtkCompositeInterpolatedVelocityField *>(vp); vtkDataSet *temp0 = NULL; PyObject *result = NULL; if (op && !ap.IsPureVirtual() && ap.CheckArgCount(1) && ap.GetVTKObject(temp0, "vtkDataSet")) { op->AddDataSet(temp0); if (!ap.ErrorOccurred()) { result = ap.BuildNone(); } } return result; } static PyMethodDef PyvtkCompositeInterpolatedVelocityField_Methods[] = { {(char*)"GetClassName", PyvtkCompositeInterpolatedVelocityField_GetClassName, METH_VARARGS, (char*)"V.GetClassName() -> string\nC++: const char *GetClassName()\n\n"}, {(char*)"IsA", PyvtkCompositeInterpolatedVelocityField_IsA, METH_VARARGS, (char*)"V.IsA(string) -> int\nC++: int IsA(const char *name)\n\n"}, {(char*)"NewInstance", PyvtkCompositeInterpolatedVelocityField_NewInstance, METH_VARARGS, (char*)"V.NewInstance() -> vtkCompositeInterpolatedVelocityField\nC++: vtkCompositeInterpolatedVelocityField *NewInstance()\n\n"}, {(char*)"SafeDownCast", PyvtkCompositeInterpolatedVelocityField_SafeDownCast, METH_VARARGS | METH_STATIC, (char*)"V.SafeDownCast(vtkObject) -> vtkCompositeInterpolatedVelocityField\nC++: vtkCompositeInterpolatedVelocityField *SafeDownCast(\n vtkObject* o)\n\n"}, {(char*)"GetLastDataSetIndex", PyvtkCompositeInterpolatedVelocityField_GetLastDataSetIndex, METH_VARARGS, (char*)"V.GetLastDataSetIndex() -> int\nC++: int GetLastDataSetIndex()\n\nGet the most recently visited dataset and it id. The dataset is\nused for a guess regarding where the next point will be, without\nsearching through all datasets. When setting the last dataset,\ncare is needed as no reference counting or checks are performed.\nThis feature is intended for custom interpolators only that cache\ndatasets independently.\n"}, {(char*)"GetLastDataSet", PyvtkCompositeInterpolatedVelocityField_GetLastDataSet, METH_VARARGS, (char*)"V.GetLastDataSet() -> vtkDataSet\nC++: vtkDataSet *GetLastDataSet()\n\nGet the most recently visited dataset and it id. The dataset is\nused for a guess regarding where the next point will be, without\nsearching through all datasets. When setting the last dataset,\ncare is needed as no reference counting or checks are performed.\nThis feature is intended for custom interpolators only that cache\ndatasets independently.\n"}, {(char*)"AddDataSet", PyvtkCompositeInterpolatedVelocityField_AddDataSet, METH_VARARGS, (char*)"V.AddDataSet(vtkDataSet)\nC++: virtual void AddDataSet(vtkDataSet *dataset)\n\nAdd a dataset for implicit velocity function evaluation. If more\nthan one dataset is added, the evaluation point is searched in\nall until a match is found. THIS FUNCTION DOES NOT CHANGE THE\nREFERENCE COUNT OF dataset FOR THREAD SAFETY REASONS.\n"}, {NULL, NULL, 0, NULL} }; PyObject *PyVTKClass_vtkCompositeInterpolatedVelocityFieldNew(const char *modulename) { PyObject *cls = PyVTKClass_New(NULL, PyvtkCompositeInterpolatedVelocityField_Methods, "vtkCompositeInterpolatedVelocityField", modulename, NULL, NULL, PyvtkCompositeInterpolatedVelocityField_Doc(), PyVTKClass_vtkAbstractInterpolatedVelocityFieldNew(modulename)); return cls; } const char **PyvtkCompositeInterpolatedVelocityField_Doc() { static const char *docstring[] = { "vtkCompositeInterpolatedVelocityField - An abstract class for\n\n", "Superclass: vtkAbstractInterpolatedVelocityField\n\n", "vtkCompositeInterpolatedVelocityField acts as a continuous velocity\nfield\n by performing cell interpolation on the underlying vtkDataSet. This\nis an\n abstract sub-class of vtkFunctionSet, NumberOfIndependentVariables =\n4\n (x,y,z,t) and NumberOfFunctions = 3 (u,v,w). With a brute-force\nscheme,\n every time an evaluation is performed, the target cell containing\npoint\n (x,y,z) needs to be found by cal", "ling FindCell(), via either\nvtkDataSet or\n vtkAbstractCelllocator's sub-classes (vtkCellLocator &\nvtkModifiedBSPTree).\n As it incurs a large cost, one (for\nvtkCellLocatorInterpolatedVelocityField\n via vtkAbstractCellLocator) or two (for vtkInterpolatedVelocityField\nvia\n vtkDataSet that involves vtkPointLocator in addressing vtkPointSet)\nlevels\n of cell caching may be exploited to increase the perf", "ormance.\n\n\n For vtkInterpolatedVelocityField, level #0 begins with intra-cell\ncaching.\n Specifically if the previous cell is valid and the next point is\nstill in\n it ( i.e., vtkCell::EvaluatePosition() returns 1, coupled with newly\ncreated\n parametric coordinates & weights ), the function values can be\ninterpolated\n and only vtkCell::EvaluatePosition() is invoked. If this fails, then\nlevel #1\n fol", "lows by inter-cell search for the target cell that contains the\nnext point.\n By an inter-cell search, the previous cell provides an important\nclue or serves\n as an immediate neighbor to aid in locating the target cell via\nvtkPointSet::\n FindCell(). If this still fails, a global cell location / search is\ninvoked via\n vtkPointSet::FindCell(). Here regardless of either inter-cell or\nglobal search,\n v", "tkPointLocator is in fact employed (for datasets of type\nvtkPointSet only, note\n vtkImageData and vtkRectilinearGrid are able to provide rapid and\nrobust cell\n location due to the simple mesh topology) as a crucial tool\nunderlying the cell\n locator. However, the use of vtkPointLocator makes\nvtkInterpolatedVelocityField\n non-robust in cell location for vtkPointSet.\n\n\n For vtkCellLocatorInterpolated", "VelocityField, the only caching (level\n#0) works\n by intra-cell trial. In case of failure, a global search for the\ntarget cell is\n invoked via vtkAbstractCellLocator::FindCell() and the actual work\nis done by\n either vtkCellLocator or vtkModifiedBSPTree (for datasets of type\nvtkPointSet\n only, while vtkImageData and vtkRectilinearGrid themselves are able\nto provide\n fast robust cell location). Wit", "hout the involvement of\nvtkPointLocator, robust\n cell location is achieved for vtkPointSet.\n\nCaveats:\n\n\n vtkCompositeInterpolatedVelocityField is not thread safe. A new\ninstance\n should be created by each thread.\n\nSee Also:\n\n\n vtkInterpolatedVelocityField vtkCellLocatorInterpolatedVelocityField\n vtkGenericInterpolatedVelocityField\nvtkCachingInterpolatedVelocityField\n vtkTemporalInterpolatedVelocit", "yField vtkFunctionSet vtkStreamer\nvtkStreamTracer\n\n", NULL }; return docstring; } static const char **PyvtkCompositeInterpolatedVelocityFieldDataSetsType_Doc(); static PyMethodDef PyvtkCompositeInterpolatedVelocityFieldDataSetsType_Methods[] = { {NULL, NULL, 0, NULL} }; #ifndef DECLARED_PyvtkCompositeInterpolatedVelocityFieldDataSetsType_Type extern VTK_PYTHON_EXPORT PyTypeObject PyvtkCompositeInterpolatedVelocityFieldDataSetsType_Type; #define DECLARED_PyvtkCompositeInterpolatedVelocityFieldDataSetsType_Type #endif static PyObject * PyvtkCompositeInterpolatedVelocityFieldDataSetsType_vtkCompositeInterpolatedVelocityFieldDataSetsType(PyObject *, PyObject *args) { vtkPythonArgs ap(args, "vtkCompositeInterpolatedVelocityFieldDataSetsType"); PyObject *result = NULL; if (ap.CheckArgCount(0)) { vtkCompositeInterpolatedVelocityFieldDataSetsType *op = new vtkCompositeInterpolatedVelocityFieldDataSetsType(); result = PyVTKSpecialObject_New("vtkCompositeInterpolatedVelocityFieldDataSetsType", op); } return result; } static PyMethodDef PyvtkCompositeInterpolatedVelocityFieldDataSetsType_vtkCompositeInterpolatedVelocityFieldDataSetsType_Methods[] = { {NULL, NULL, 0, NULL} }; static PyMethodDef PyvtkCompositeInterpolatedVelocityFieldDataSetsType_NewMethod = \ { (char*)"vtkCompositeInterpolatedVelocityFieldDataSetsType", PyvtkCompositeInterpolatedVelocityFieldDataSetsType_vtkCompositeInterpolatedVelocityFieldDataSetsType, 1, (char*)"" }; #if PY_VERSION_HEX >= 0x02020000 static PyObject * PyvtkCompositeInterpolatedVelocityFieldDataSetsType_New(PyTypeObject *, PyObject *args, PyObject *kwds) { if (kwds && PyDict_Size(kwds)) { PyErr_SetString(PyExc_TypeError, "this function takes no keyword arguments"); return NULL; } return PyvtkCompositeInterpolatedVelocityFieldDataSetsType_vtkCompositeInterpolatedVelocityFieldDataSetsType(NULL, args); } #endif static void PyvtkCompositeInterpolatedVelocityFieldDataSetsType_Delete(PyObject *self) { PyVTKSpecialObject *obj = (PyVTKSpecialObject *)self; if (obj->vtk_ptr) { delete static_cast<vtkCompositeInterpolatedVelocityFieldDataSetsType *>(obj->vtk_ptr); } #if PY_MAJOR_VERSION >= 2 PyObject_Del(self); #else PyMem_DEL(self); #endif } static long PyvtkCompositeInterpolatedVelocityFieldDataSetsType_Hash(PyObject *self) { #if PY_VERSION_HEX >= 0x020600B2 return PyObject_HashNotImplemented(self); #else char text[256]; sprintf(text, "unhashable type: '%s'", self->ob_type->tp_name); PyErr_SetString(PyExc_TypeError, text); return -1; #endif } PyTypeObject PyvtkCompositeInterpolatedVelocityFieldDataSetsType_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, (char*)"vtkCompositeInterpolatedVelocityFieldDataSetsType", // tp_name sizeof(PyVTKSpecialObject), // tp_basicsize 0, // tp_itemsize PyvtkCompositeInterpolatedVelocityFieldDataSetsType_Delete, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare PyVTKSpecialObject_Repr, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping PyvtkCompositeInterpolatedVelocityFieldDataSetsType_Hash, // tp_hash 0, // tp_call 0, // tp_str #if PY_VERSION_HEX >= 0x02020000 PyObject_GenericGetAttr, // tp_getattro #else PyVTKSpecialObject_GetAttr, // tp_getattro #endif 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags 0, // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset #if PY_VERSION_HEX >= 0x02020000 0, // tp_iter 0, // tp_iternext PyvtkCompositeInterpolatedVelocityFieldDataSetsType_Methods, // tp_methods 0, // tp_members 0, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset 0, // tp_init 0, // tp_alloc PyvtkCompositeInterpolatedVelocityFieldDataSetsType_New, // tp_new #if PY_VERSION_HEX >= 0x02030000 PyObject_Del, // tp_free #else _PyObject_Del, // tp_free #endif 0, // tp_is_gc 0, // tp_bases 0, // tp_mro 0, // tp_cache 0, // tp_subclasses 0, // tp_weaklist #endif VTK_WRAP_PYTHON_SUPRESS_UNINITIALIZED }; static void *PyvtkCompositeInterpolatedVelocityFieldDataSetsType_CCopy(const void *obj) { if (obj) { return new vtkCompositeInterpolatedVelocityFieldDataSetsType(*static_cast<const vtkCompositeInterpolatedVelocityFieldDataSetsType*>(obj)); } return 0; } static PyObject *PyvtkCompositeInterpolatedVelocityFieldDataSetsType_TypeNew(const char *) { PyObject *cls = PyVTKSpecialType_New( &PyvtkCompositeInterpolatedVelocityFieldDataSetsType_Type, PyvtkCompositeInterpolatedVelocityFieldDataSetsType_Methods, PyvtkCompositeInterpolatedVelocityFieldDataSetsType_vtkCompositeInterpolatedVelocityFieldDataSetsType_Methods, &PyvtkCompositeInterpolatedVelocityFieldDataSetsType_NewMethod, PyvtkCompositeInterpolatedVelocityFieldDataSetsType_Doc(), &PyvtkCompositeInterpolatedVelocityFieldDataSetsType_CCopy); return cls; } const char **PyvtkCompositeInterpolatedVelocityFieldDataSetsType_Doc() { static const char *docstring[] = { "vtkCompositeInterpolatedVelocityField - An abstract class for\n\n", "vtkCompositeInterpolatedVelocityField acts as a continuous velocity\nfield\n by performing cell interpolation on the underlying vtkDataSet. This\nis an\n abstract sub-class of vtkFunctionSet, NumberOfIndependentVariables =\n4\n (x,y,z,t) and NumberOfFunctions = 3 (u,v,w). With a brute-force\nscheme,\n every time an evaluation is performed, the target cell containing\npoint\n (x,y,z) needs to be found by cal", "ling FindCell(), via either\nvtkDataSet or\n vtkAbstractCelllocator's sub-classes (vtkCellLocator &\nvtkModifiedBSPTree).\n As it incurs a large cost, one (for\nvtkCellLocatorInterpolatedVelocityField\n via vtkAbstractCellLocator) or two (for vtkInterpolatedVelocityField\nvia\n vtkDataSet that involves vtkPointLocator in addressing vtkPointSet)\nlevels\n of cell caching may be exploited to increase the perf", "ormance.\n\n\n For vtkInterpolatedVelocityField, level #0 begins with intra-cell\ncaching.\n Specifically if the previous cell is valid and the next point is\nstill in\n it ( i.e., vtkCell::EvaluatePosition() returns 1, coupled with newly\ncreated\n parametric coordinates & weights ), the function values can be\ninterpolated\n and only vtkCell::EvaluatePosition() is invoked. If this fails, then\nlevel #1\n fol", "lows by inter-cell search for the target cell that contains the\nnext point.\n By an inter-cell search, the previous cell provides an important\nclue or serves\n as an immediate neighbor to aid in locating the target cell via\nvtkPointSet::\n FindCell(). If this still fails, a global cell location / search is\ninvoked via\n vtkPointSet::FindCell(). Here regardless of either inter-cell or\nglobal search,\n v", "tkPointLocator is in fact employed (for datasets of type\nvtkPointSet only, note\n vtkImageData and vtkRectilinearGrid are able to provide rapid and\nrobust cell\n location due to the simple mesh topology) as a crucial tool\nunderlying the cell\n locator. However, the use of vtkPointLocator makes\nvtkInterpolatedVelocityField\n non-robust in cell location for vtkPointSet.\n\n\n For vtkCellLocatorInterpolated", "VelocityField, the only caching (level\n#0) works\n by intra-cell trial. In case of failure, a global search for the\ntarget cell is\n invoked via vtkAbstractCellLocator::FindCell() and the actual work\nis done by\n either vtkCellLocator or vtkModifiedBSPTree (for datasets of type\nvtkPointSet\n only, while vtkImageData and vtkRectilinearGrid themselves are able\nto provide\n fast robust cell location). Wit", "hout the involvement of\nvtkPointLocator, robust\n cell location is achieved for vtkPointSet.\n\nCaveats:\n\n\n vtkCompositeInterpolatedVelocityField is not thread safe. A new\ninstance\n should be created by each thread.\n\nSee Also:\n\n\n vtkInterpolatedVelocityField vtkCellLocatorInterpolatedVelocityField\n vtkGenericInterpolatedVelocityField\nvtkCachingInterpolatedVelocityField\n vtkTemporalInterpolatedVelocit", "yField vtkFunctionSet vtkStreamer\nvtkStreamTracer\n\n", "V.vtkCompositeInterpolatedVelocityFieldDataSetsType()\nC++: vtkCompositeInterpolatedVelocityFieldDataSetsType()\n", NULL }; return docstring; } void PyVTKAddFile_vtkCompositeInterpolatedVelocityField( PyObject *dict, const char *modulename) { PyObject *o; o = PyVTKClass_vtkCompositeInterpolatedVelocityFieldNew(modulename); if (o && PyDict_SetItemString(dict, (char *)"vtkCompositeInterpolatedVelocityField", o) != 0) { Py_DECREF(o); } o = PyvtkCompositeInterpolatedVelocityFieldDataSetsType_TypeNew(modulename); if (o && PyDict_SetItemString(dict, (char *)"vtkCompositeInterpolatedVelocityFieldDataSetsType", o) != 0) { Py_DECREF(o); } }
[ "mpasVM@localhost.org" ]
mpasVM@localhost.org
16e8168d0a78ab5f21464391c31279436a12de56
24bc32fec5dd08770408f5ed64e12376dd8ef4fa
/src/rpcblockchain.cpp
9f4d0a5ca2c04b1da7ff50d1749b40a015bd4a5a
[ "MIT" ]
permissive
AdnCoin/AdnCoin
3336fee3b6326a6cb9019e7e38cc65626d16f8d8
0c835e35dcf2ef56b5728f4edf1ec7bc31ed68aa
refs/heads/master
2021-01-01T20:02:55.462318
2017-07-30T09:42:07
2017-07-30T09:42:07
98,750,581
0
0
null
null
null
null
UTF-8
C++
false
false
45,500
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The Adn Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "amount.h" #include "chain.h" #include "chainparams.h" #include "checkpoints.h" #include "coins.h" #include "consensus/validation.h" #include "main.h" #include "policy/policy.h" #include "primitives/transaction.h" #include "rpcserver.h" #include "streams.h" #include "sync.h" #include "txmempool.h" #include "util.h" #include "utilstrencodings.h" #include <stdint.h> #include <univalue.h> using namespace std; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry); void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex); double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (chainActive.Tip() == NULL) return 1.0; else blockindex = chainActive.Tip(); } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } UniValue blockheaderToJSON(const CBlockIndex* blockindex) { UniValue result(UniValue::VOBJ); result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", blockindex->nVersion)); result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex())); result.push_back(Pair("time", (int64_t)blockindex->nTime)); result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast())); result.push_back(Pair("nonce", (uint64_t)blockindex->nNonce)); result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex())); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); CBlockIndex *pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); return result; } UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false) { UniValue result(UniValue::VOBJ); result.push_back(Pair("hash", block.GetHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); UniValue txs(UniValue::VARR); BOOST_FOREACH(const CTransaction&tx, block.vtx) { if(txDetails) { UniValue objTx(UniValue::VOBJ); TxToJSON(tx, uint256(), objTx); txs.push_back(objTx); } else txs.push_back(tx.GetHash().GetHex()); } result.push_back(Pair("tx", txs)); result.push_back(Pair("time", block.GetBlockTime())); result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast())); result.push_back(Pair("nonce", (uint64_t)block.nNonce)); result.push_back(Pair("bits", strprintf("%08x", block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex())); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); CBlockIndex *pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); return result; } UniValue getblockcount(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockcount\n" "\nReturns the number of blocks in the longest block chain.\n" "\nResult:\n" "n (numeric) The current block count\n" "\nExamples:\n" + HelpExampleCli("getblockcount", "") + HelpExampleRpc("getblockcount", "") ); LOCK(cs_main); return chainActive.Height(); } UniValue getbestblockhash(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getbestblockhash\n" "\nReturns the hash of the best (tip) block in the longest block chain.\n" "\nResult\n" "\"hex\" (string) the block hash hex encoded\n" "\nExamples\n" + HelpExampleCli("getbestblockhash", "") + HelpExampleRpc("getbestblockhash", "") ); LOCK(cs_main); return chainActive.Tip()->GetBlockHash().GetHex(); } UniValue getdifficulty(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getdifficulty\n" "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n" "\nResult:\n" "n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n" "\nExamples:\n" + HelpExampleCli("getdifficulty", "") + HelpExampleRpc("getdifficulty", "") ); LOCK(cs_main); return GetDifficulty(); } UniValue mempoolToJSON(bool fVerbose = false) { if (fVerbose) { LOCK(mempool.cs); UniValue o(UniValue::VOBJ); BOOST_FOREACH(const CTxMemPoolEntry& e, mempool.mapTx) { const uint256& hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); info.push_back(Pair("size", (int)e.GetTxSize())); info.push_back(Pair("fee", ValueFromAmount(e.GetFee()))); info.push_back(Pair("modifiedfee", ValueFromAmount(e.GetModifiedFee()))); info.push_back(Pair("time", e.GetTime())); info.push_back(Pair("height", (int)e.GetHeight())); info.push_back(Pair("startingpriority", e.GetPriority(e.GetHeight()))); info.push_back(Pair("currentpriority", e.GetPriority(chainActive.Height()))); info.push_back(Pair("descendantcount", e.GetCountWithDescendants())); info.push_back(Pair("descendantsize", e.GetSizeWithDescendants())); info.push_back(Pair("descendantfees", e.GetModFeesWithDescendants())); const CTransaction& tx = e.GetTx(); set<string> setDepends; BOOST_FOREACH(const CTxIn& txin, tx.vin) { if (mempool.exists(txin.prevout.hash)) setDepends.insert(txin.prevout.hash.ToString()); } UniValue depends(UniValue::VARR); BOOST_FOREACH(const string& dep, setDepends) { depends.push_back(dep); } info.push_back(Pair("depends", depends)); o.push_back(Pair(hash.ToString(), info)); } return o; } else { vector<uint256> vtxid; mempool.queryHashes(vtxid); UniValue a(UniValue::VARR); BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } } UniValue getrawmempool(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getrawmempool ( verbose )\n" "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n" "\nArguments:\n" "1. verbose (boolean, optional, default=false) true for a json object, false for array of transaction ids\n" "\nResult: (for verbose = false):\n" "[ (json array of string)\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" "]\n" "\nResult: (for verbose = true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" " \"size\" : n, (numeric) transaction size in bytes\n" " \"fee\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + "\n" " \"modifiedfee\" : n, (numeric) transaction fee with fee deltas used for mining priority\n" " \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n" " \"height\" : n, (numeric) block height when transaction entered pool\n" " \"startingpriority\" : n, (numeric) priority when transaction entered pool\n" " \"currentpriority\" : n, (numeric) transaction priority now\n" " \"descendantcount\" : n, (numeric) number of in-mempool descendant transactions (including this one)\n" " \"descendantsize\" : n, (numeric) size of in-mempool descendants (including this one)\n" " \"descendantfees\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one)\n" " \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n" " \"transactionid\", (string) parent transaction id\n" " ... ]\n" " }, ...\n" "}\n" "\nExamples\n" + HelpExampleCli("getrawmempool", "true") + HelpExampleRpc("getrawmempool", "true") ); LOCK(cs_main); bool fVerbose = false; if (params.size() > 0) fVerbose = params[0].get_bool(); return mempoolToJSON(fVerbose); } UniValue getblockhashes(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "getblockhashes timestamp\n" "\nReturns array of hashes of blocks within the timestamp range provided.\n" "\nArguments:\n" "1. high (numeric, required) The newer block timestamp\n" "2. low (numeric, required) The older block timestamp\n" "\nResult:\n" "[\n" " \"hash\" (string) The block hash\n" "]\n" "\nExamples:\n" + HelpExampleCli("getblockhashes", "1231614698 1231024505") + HelpExampleRpc("getblockhashes", "1231614698, 1231024505") ); unsigned int high = params[0].get_int(); unsigned int low = params[1].get_int(); std::vector<uint256> blockHashes; if (!GetTimestampIndex(high, low, blockHashes)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for block hashes"); } UniValue result(UniValue::VARR); for (std::vector<uint256>::const_iterator it=blockHashes.begin(); it!=blockHashes.end(); it++) { result.push_back(it->GetHex()); } return result; } UniValue getblockhash(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblockhash index\n" "\nReturns hash of block in best-block-chain at index provided.\n" "\nArguments:\n" "1. index (numeric, required) The block index\n" "\nResult:\n" "\"hash\" (string) The block hash\n" "\nExamples:\n" + HelpExampleCli("getblockhash", "1000") + HelpExampleRpc("getblockhash", "1000") ); LOCK(cs_main); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > chainActive.Height()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range"); CBlockIndex* pblockindex = chainActive[nHeight]; return pblockindex->GetBlockHash().GetHex(); } UniValue getblockheader(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblockheader \"hash\" ( verbose )\n" "\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n" "If verbose is true, returns an Object with information about blockheader <hash>.\n" "\nArguments:\n" "1. \"hash\" (string, required) The block hash\n" "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n" "\nResult (for verbose = true):\n" "{\n" " \"hash\" : \"hash\", (string) the block hash (same as provided)\n" " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" " \"height\" : n, (numeric) The block height or index\n" " \"version\" : n, (numeric) The block version\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"nextblockhash\" : \"hash\", (string) The hash of the next block\n" " \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n" "}\n" "\nResult (for verbose=false):\n" "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n" "\nExamples:\n" + HelpExampleCli("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"") + HelpExampleRpc("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"") ); LOCK(cs_main); std::string strHash = params[0].get_str(); uint256 hash(uint256S(strHash)); bool fVerbose = true; if (params.size() > 1) fVerbose = params[1].get_bool(); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << pblockindex->GetBlockHeader(); std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockheaderToJSON(pblockindex); } UniValue getblockheaders(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "getblockheaders \"hash\" ( count verbose )\n" "\nReturns an array of items with information about <count> blockheaders starting from <hash>.\n" "\nIf verbose is false, each item is a string that is serialized, hex-encoded data for a single blockheader.\n" "If verbose is true, each item is an Object with information about a single blockheader.\n" "\nArguments:\n" "1. \"hash\" (string, required) The block hash\n" "2. count (numeric, optional, default/max=" + strprintf("%s", MAX_HEADERS_RESULTS) +")\n" "3. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n" "\nResult (for verbose = true):\n" "[ {\n" " \"hash\" : \"hash\", (string) The block hash\n" " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" " \"height\" : n, (numeric) The block height or index\n" " \"version\" : n, (numeric) The block version\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"nextblockhash\" : \"hash\", (string) The hash of the next block\n" " \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n" "}, {\n" " ...\n" " },\n" "...\n" "]\n" "\nResult (for verbose=false):\n" "[\n" " \"data\", (string) A string that is serialized, hex-encoded data for block header.\n" " ...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getblockheaders", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 2000") + HelpExampleRpc("getblockheaders", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 2000") ); LOCK(cs_main); std::string strHash = params[0].get_str(); uint256 hash(uint256S(strHash)); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); int nCount = MAX_HEADERS_RESULTS; if (params.size() > 1) nCount = params[1].get_int(); if (nCount <= 0 || nCount > (int)MAX_HEADERS_RESULTS) throw JSONRPCError(RPC_INVALID_PARAMETER, "Count is out of range"); bool fVerbose = true; if (params.size() > 2) fVerbose = params[2].get_bool(); CBlockIndex* pblockindex = mapBlockIndex[hash]; UniValue arrHeaders(UniValue::VARR); if (!fVerbose) { for (; pblockindex; pblockindex = chainActive.Next(pblockindex)) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << pblockindex->GetBlockHeader(); std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); arrHeaders.push_back(strHex); if (--nCount <= 0) break; } return arrHeaders; } for (; pblockindex; pblockindex = chainActive.Next(pblockindex)) { arrHeaders.push_back(blockheaderToJSON(pblockindex)); if (--nCount <= 0) break; } return arrHeaders; } UniValue getblock(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock \"hash\" ( verbose )\n" "\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash'.\n" "If verbose is true, returns an Object with information about block <hash>.\n" "\nArguments:\n" "1. \"hash\" (string, required) The block hash\n" "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n" "\nResult (for verbose = true):\n" "{\n" " \"hash\" : \"hash\", (string) the block hash (same as provided)\n" " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" " \"size\" : n, (numeric) The block size\n" " \"height\" : n, (numeric) The block height or index\n" " \"version\" : n, (numeric) The block version\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"tx\" : [ (array of string) The transaction ids\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" " ],\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"chainwork\" : \"xxxx\", (string) Expected number of hashes required to produce the chain up to this block (in hex)\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"nextblockhash\" : \"hash\" (string) The hash of the next block\n" "}\n" "\nResult (for verbose=false):\n" "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n" "\nExamples:\n" + HelpExampleCli("getblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"") + HelpExampleRpc("getblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"") ); LOCK(cs_main); std::string strHash = params[0].get_str(); uint256 hash(uint256S(strHash)); bool fVerbose = true; if (params.size() > 1) fVerbose = params[1].get_bool(); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0) throw JSONRPCError(RPC_INTERNAL_ERROR, "Block not available (pruned data)"); if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << block; std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockToJSON(block, pblockindex); } UniValue gettxoutsetinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "gettxoutsetinfo\n" "\nReturns statistics about the unspent transaction output set.\n" "Note this call may take some time.\n" "\nResult:\n" "{\n" " \"height\":n, (numeric) The current block height (index)\n" " \"bestblock\": \"hex\", (string) the best block hash hex\n" " \"transactions\": n, (numeric) The number of transactions\n" " \"txouts\": n, (numeric) The number of output transactions\n" " \"bytes_serialized\": n, (numeric) The serialized size\n" " \"hash_serialized\": \"hash\", (string) The serialized hash\n" " \"total_amount\": x.xxx (numeric) The total amount\n" "}\n" "\nExamples:\n" + HelpExampleCli("gettxoutsetinfo", "") + HelpExampleRpc("gettxoutsetinfo", "") ); UniValue ret(UniValue::VOBJ); CCoinsStats stats; FlushStateToDisk(); if (pcoinsTip->GetStats(stats)) { ret.push_back(Pair("height", (int64_t)stats.nHeight)); ret.push_back(Pair("bestblock", stats.hashBlock.GetHex())); ret.push_back(Pair("transactions", (int64_t)stats.nTransactions)); ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs)); ret.push_back(Pair("bytes_serialized", (int64_t)stats.nSerializedSize)); ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex())); ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount))); } return ret; } UniValue gettxout(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) throw runtime_error( "gettxout \"txid\" n ( includemempool )\n" "\nReturns details about an unspent transaction output.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "2. n (numeric, required) vout value\n" "3. includemempool (boolean, optional) Whether to included the mem pool\n" "\nResult:\n" "{\n" " \"bestblock\" : \"hash\", (string) the block hash\n" " \"confirmations\" : n, (numeric) The number of confirmations\n" " \"value\" : x.xxx, (numeric) The transaction value in " + CURRENCY_UNIT + "\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"code\", (string) \n" " \"hex\" : \"hex\", (string) \n" " \"reqSigs\" : n, (numeric) Number of required signatures\n" " \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n" " \"addresses\" : [ (array of string) array of adn addresses\n" " \"adnaddress\" (string) adn address\n" " ,...\n" " ]\n" " },\n" " \"version\" : n, (numeric) The version\n" " \"coinbase\" : true|false (boolean) Coinbase or not\n" "}\n" "\nExamples:\n" "\nGet unspent transactions\n" + HelpExampleCli("listunspent", "") + "\nView the details\n" + HelpExampleCli("gettxout", "\"txid\" 1") + "\nAs a json rpc call\n" + HelpExampleRpc("gettxout", "\"txid\", 1") ); LOCK(cs_main); UniValue ret(UniValue::VOBJ); std::string strHash = params[0].get_str(); uint256 hash(uint256S(strHash)); int n = params[1].get_int(); bool fMempool = true; if (params.size() > 2) fMempool = params[2].get_bool(); CCoins coins; if (fMempool) { LOCK(mempool.cs); CCoinsViewMemPool view(pcoinsTip, mempool); if (!view.GetCoins(hash, coins)) return NullUniValue; mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool } else { if (!pcoinsTip->GetCoins(hash, coins)) return NullUniValue; } if (n<0 || (unsigned int)n>=coins.vout.size() || coins.vout[n].IsNull()) return NullUniValue; BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock()); CBlockIndex *pindex = it->second; ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex())); if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT) ret.push_back(Pair("confirmations", 0)); else ret.push_back(Pair("confirmations", pindex->nHeight - coins.nHeight + 1)); ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue))); UniValue o(UniValue::VOBJ); ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o, true); ret.push_back(Pair("scriptPubKey", o)); ret.push_back(Pair("version", coins.nVersion)); ret.push_back(Pair("coinbase", coins.fCoinBase)); return ret; } UniValue verifychain(const UniValue& params, bool fHelp) { int nCheckLevel = GetArg("-checklevel", DEFAULT_CHECKLEVEL); int nCheckDepth = GetArg("-checkblocks", DEFAULT_CHECKBLOCKS); if (fHelp || params.size() > 2) throw runtime_error( "verifychain ( checklevel numblocks )\n" "\nVerifies blockchain database.\n" "\nArguments:\n" "1. checklevel (numeric, optional, 0-4, default=" + strprintf("%d", nCheckLevel) + ") How thorough the block verification is.\n" "2. numblocks (numeric, optional, default=" + strprintf("%d", nCheckDepth) + ", 0=all) The number of blocks to check.\n" "\nResult:\n" "true|false (boolean) Verified or not\n" "\nExamples:\n" + HelpExampleCli("verifychain", "") + HelpExampleRpc("verifychain", "") ); LOCK(cs_main); if (params.size() > 0) nCheckLevel = params[0].get_int(); if (params.size() > 1) nCheckDepth = params[1].get_int(); return CVerifyDB().VerifyDB(Params(), pcoinsTip, nCheckLevel, nCheckDepth); } /** Implementation of IsSuperMajority with better feedback */ static UniValue SoftForkMajorityDesc(int minVersion, CBlockIndex* pindex, int nRequired, const Consensus::Params& consensusParams) { int nFound = 0; CBlockIndex* pstart = pindex; for (int i = 0; i < consensusParams.nMajorityWindow && pstart != NULL; i++) { if (pstart->nVersion >= minVersion) ++nFound; pstart = pstart->pprev; } UniValue rv(UniValue::VOBJ); rv.push_back(Pair("status", nFound >= nRequired)); rv.push_back(Pair("found", nFound)); rv.push_back(Pair("required", nRequired)); rv.push_back(Pair("window", consensusParams.nMajorityWindow)); return rv; } static UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex* pindex, const Consensus::Params& consensusParams) { UniValue rv(UniValue::VOBJ); rv.push_back(Pair("id", name)); rv.push_back(Pair("version", version)); rv.push_back(Pair("enforce", SoftForkMajorityDesc(version, pindex, consensusParams.nMajorityEnforceBlockUpgrade, consensusParams))); rv.push_back(Pair("reject", SoftForkMajorityDesc(version, pindex, consensusParams.nMajorityRejectBlockOutdated, consensusParams))); return rv; } static UniValue BIP9SoftForkDesc(const std::string& name, const Consensus::Params& consensusParams, Consensus::DeploymentPos id) { UniValue rv(UniValue::VOBJ); rv.push_back(Pair("id", name)); switch (VersionBitsTipState(consensusParams, id)) { case THRESHOLD_DEFINED: rv.push_back(Pair("status", "defined")); break; case THRESHOLD_STARTED: rv.push_back(Pair("status", "started")); break; case THRESHOLD_LOCKED_IN: rv.push_back(Pair("status", "locked_in")); break; case THRESHOLD_ACTIVE: rv.push_back(Pair("status", "active")); break; case THRESHOLD_FAILED: rv.push_back(Pair("status", "failed")); break; } return rv; } UniValue getblockchaininfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockchaininfo\n" "Returns an object containing various state info regarding block chain processing.\n" "\nResult:\n" "{\n" " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n" " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n" " \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n" " \"bestblockhash\": \"...\", (string) the hash of the currently best block\n" " \"difficulty\": xxxxxx, (numeric) the current difficulty\n" " \"mediantime\": xxxxxx, (numeric) median time for the current best block\n" " \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n" " \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n" " \"pruned\": xx, (boolean) if the blocks are subject to pruning\n" " \"pruneheight\": xxxxxx, (numeric) heighest block available\n" " \"softforks\": [ (array) status of softforks in progress\n" " {\n" " \"id\": \"xxxx\", (string) name of softfork\n" " \"version\": xx, (numeric) block version\n" " \"enforce\": { (object) progress toward enforcing the softfork rules for new-version blocks\n" " \"status\": xx, (boolean) true if threshold reached\n" " \"found\": xx, (numeric) number of blocks with the new version found\n" " \"required\": xx, (numeric) number of blocks required to trigger\n" " \"window\": xx, (numeric) maximum size of examined window of recent blocks\n" " },\n" " \"reject\": { ... } (object) progress toward rejecting pre-softfork blocks (same fields as \"enforce\")\n" " }, ...\n" " ],\n" " \"bip9_softforks\": [ (array) status of BIP9 softforks in progress\n" " {\n" " \"id\": \"xxxx\", (string) name of the softfork\n" " \"status\": \"xxxx\", (string) one of \"defined\", \"started\", \"lockedin\", \"active\", \"failed\"\n" " }\n" " ]\n" "}\n" "\nExamples:\n" + HelpExampleCli("getblockchaininfo", "") + HelpExampleRpc("getblockchaininfo", "") ); LOCK(cs_main); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("chain", Params().NetworkIDString())); obj.push_back(Pair("blocks", (int)chainActive.Height())); obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1)); obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex())); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("mediantime", (int64_t)chainActive.Tip()->GetMedianTimePast())); obj.push_back(Pair("verificationprogress", Checkpoints::GuessVerificationProgress(Params().Checkpoints(), chainActive.Tip()))); obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex())); obj.push_back(Pair("pruned", fPruneMode)); const Consensus::Params& consensusParams = Params().GetConsensus(); CBlockIndex* tip = chainActive.Tip(); UniValue softforks(UniValue::VARR); UniValue bip9_softforks(UniValue::VARR); softforks.push_back(SoftForkDesc("bip34", 2, tip, consensusParams)); softforks.push_back(SoftForkDesc("bip66", 3, tip, consensusParams)); softforks.push_back(SoftForkDesc("bip65", 4, tip, consensusParams)); bip9_softforks.push_back(BIP9SoftForkDesc("csv", consensusParams, Consensus::DEPLOYMENT_CSV)); obj.push_back(Pair("softforks", softforks)); obj.push_back(Pair("bip9_softforks", bip9_softforks)); if (fPruneMode) { CBlockIndex *block = chainActive.Tip(); while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA)) block = block->pprev; obj.push_back(Pair("pruneheight", block->nHeight)); } return obj; } /** Comparison function for sorting the getchaintips heads. */ struct CompareBlocksByHeight { bool operator()(const CBlockIndex* a, const CBlockIndex* b) const { /* Make sure that unequal blocks with the same height do not compare equal. Use the pointers themselves to make a distinction. */ if (a->nHeight != b->nHeight) return (a->nHeight > b->nHeight); return a < b; } }; UniValue getchaintips(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getchaintips ( count branchlen )\n" "Return information about all known tips in the block tree," " including the main chain as well as orphaned branches.\n" "\nArguments:\n" "1. count (numeric, optional) only show this much of latest tips\n" "2. branchlen (numeric, optional) only show tips that have equal or greater length of branch\n" "\nResult:\n" "[\n" " {\n" " \"height\": xxxx, (numeric) height of the chain tip\n" " \"hash\": \"xxxx\", (string) block hash of the tip\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n" " \"branchlen\": 0 (numeric) zero for main chain\n" " \"status\": \"active\" (string) \"active\" for the main chain\n" " },\n" " {\n" " \"height\": xxxx,\n" " \"hash\": \"xxxx\",\n" " \"difficulty\" : x.xxx,\n" " \"chainwork\" : \"0000...1f3\"\n" " \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n" " \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n" " }\n" "]\n" "Possible values for status:\n" "1. \"invalid\" This branch contains at least one invalid block\n" "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n" "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n" "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n" "5. \"active\" This is the tip of the active main chain, which is certainly valid\n" "\nExamples:\n" + HelpExampleCli("getchaintips", "") + HelpExampleRpc("getchaintips", "") ); LOCK(cs_main); /* Build up a list of chain tips. We start with the list of all known blocks, and successively remove blocks that appear as pprev of another block. */ std::set<const CBlockIndex*, CompareBlocksByHeight> setTips; BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex) setTips.insert(item.second); BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex) { const CBlockIndex* pprev = item.second->pprev; if (pprev) setTips.erase(pprev); } // Always report the currently active tip. setTips.insert(chainActive.Tip()); int nBranchMin = -1; int nCountMax = INT_MAX; if(params.size() >= 1) nCountMax = params[0].get_int(); if(params.size() == 2) nBranchMin = params[1].get_int(); /* Construct the output array. */ UniValue res(UniValue::VARR); BOOST_FOREACH(const CBlockIndex* block, setTips) { const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight; if(branchLen < nBranchMin) continue; if(nCountMax-- < 1) break; UniValue obj(UniValue::VOBJ); obj.push_back(Pair("height", block->nHeight)); obj.push_back(Pair("hash", block->phashBlock->GetHex())); obj.push_back(Pair("difficulty", GetDifficulty(block))); obj.push_back(Pair("chainwork", block->nChainWork.GetHex())); obj.push_back(Pair("branchlen", branchLen)); string status; if (chainActive.Contains(block)) { // This block is part of the currently active chain. status = "active"; } else if (block->nStatus & BLOCK_FAILED_MASK) { // This block or one of its ancestors is invalid. status = "invalid"; } else if (block->nChainTx == 0) { // This block cannot be connected because full block data for it or one of its parents is missing. status = "headers-only"; } else if (block->IsValid(BLOCK_VALID_SCRIPTS)) { // This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized. status = "valid-fork"; } else if (block->IsValid(BLOCK_VALID_TREE)) { // The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain. status = "valid-headers"; } else { // No clue. status = "unknown"; } obj.push_back(Pair("status", status)); res.push_back(obj); } return res; } UniValue mempoolInfoToJSON() { UniValue ret(UniValue::VOBJ); ret.push_back(Pair("size", (int64_t) mempool.size())); ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize())); ret.push_back(Pair("usage", (int64_t) mempool.DynamicMemoryUsage())); size_t maxmempool = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000; ret.push_back(Pair("maxmempool", (int64_t) maxmempool)); ret.push_back(Pair("mempoolminfee", ValueFromAmount(mempool.GetMinFee(maxmempool).GetFeePerK()))); return ret; } UniValue getmempoolinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmempoolinfo\n" "\nReturns details on the active state of the TX memory pool.\n" "\nResult:\n" "{\n" " \"size\": xxxxx, (numeric) Current tx count\n" " \"bytes\": xxxxx, (numeric) Sum of all tx sizes\n" " \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n" " \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n" " \"mempoolminfee\": xxxxx (numeric) Minimum fee for tx to be accepted\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmempoolinfo", "") + HelpExampleRpc("getmempoolinfo", "") ); return mempoolInfoToJSON(); } UniValue invalidateblock(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "invalidateblock \"hash\"\n" "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n" "\nArguments:\n" "1. hash (string, required) the hash of the block to mark as invalid\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("invalidateblock", "\"blockhash\"") + HelpExampleRpc("invalidateblock", "\"blockhash\"") ); std::string strHash = params[0].get_str(); uint256 hash(uint256S(strHash)); CValidationState state; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; InvalidateBlock(state, Params().GetConsensus(), pblockindex); } if (state.IsValid()) { ActivateBestChain(state, Params()); } if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; } UniValue reconsiderblock(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "reconsiderblock \"hash\"\n" "\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n" "This can be used to undo the effects of invalidateblock.\n" "\nArguments:\n" "1. hash (string, required) the hash of the block to reconsider\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("reconsiderblock", "\"blockhash\"") + HelpExampleRpc("reconsiderblock", "\"blockhash\"") ); std::string strHash = params[0].get_str(); uint256 hash(uint256S(strHash)); CValidationState state; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; ReconsiderBlock(state, pblockindex); } if (state.IsValid()) { ActivateBestChain(state, Params()); } if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; }
[ "onecoin@sfr.fr" ]
onecoin@sfr.fr
a1d7faf85302069c3d622522161e53a872483489
a7ee1785f3897a7e6598c646d850456dbaabf965
/cppBackend.cpp
c03dc8f137172eae97b579d061daf2e649711dfc
[ "Apache-2.0" ]
permissive
kennychou0529/lpc
d3c2ca3294d66c59c7c49cbdd9d0d5a2e537dd00
de4d7e389ae16736f3dbbf2c4a339145e2cc6e1d
refs/heads/master
2022-04-19T23:20:57.923944
2020-03-08T04:44:33
2020-03-08T04:44:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,593
cpp
// Copyright 2018 LPC Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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 <limits> #include "cppBackend.h" // make sure we're not breaking <limits> // #undef min #undef max namespace cpp { /////////////////////////////////////////////////////////////////////////////// // // the recursive helper for generating "record" definitions // string TypeGen::_recordDef(const ts::RecordFields* pFields) { std::stringstream code; // fixed fields // if(pFields->pFixedFields != nullptr) { auto pList = pFields->pFixedFields; for(auto it = pList->begin(); it != pList->end(); ++it) { auto pFieldType = (*it)->pType; m_pBackend->_generateType(pFieldType); auto pNames = (*it)->pNames; for(auto idIt = pNames->begin(); idIt != pNames->end(); ++idIt) { code << typeExt(pFieldType)->genName; code << " " << genSimpleName((*idIt)->name) << ";\n"; } } } // variable fields & tag // if(pFields->pVariableFields != nullptr) { auto pSelField = pFields->pVariableFields->pVariantSelector; if(pSelField->pId != nullptr) { m_pBackend->_generateType(pSelField->pType); code << "// variable fields selector\n"; code << typeExt(pSelField->pType)->genName; code << " " << genSimpleName(pSelField->pId->name) << ";\n"; } std::stringstream varFields; auto pList = pFields->pVariableFields->pVariantFields; for(auto it = pList->begin(); it != pList->end(); ++it) { auto pVarFields = (*it)->pFields; // a nicer output for single fields // if(pVarFields->pVariableFields == nullptr && pVarFields->pFixedFields != nullptr && pVarFields->pFixedFields->size() == 1 && pVarFields->pFixedFields->front()->pNames->size() == 1) { auto pFieldSet = pVarFields->pFixedFields->front(); m_pBackend->_generateType(pFieldSet->pType); varFields << typeExt(pFieldSet->pType)->genName; varFields << " " << genSimpleName(pFieldSet->pNames->front()->name) << ";\n"; } else if(pVarFields->pFixedFields != nullptr || pVarFields->pVariableFields != nullptr) { varFields << "struct\n" << _recordDef(pVarFields) << ";\n"; } } code << "// variable fields\n"; code << "union\n" << genBlock(varFields.str()) << ";\n"; } return genBlock(code.str()); } /////////////////////////////////////////////////////////////////////////////// // VarPtr TypeGen::visit(ts::RecordType* pType) { assert(!m_name.empty()); std::stringstream code; code << "struct " << m_name << "\n" << _recordDef(pType->fields()) << ";\n"; return allocStr(code); } /////////////////////////////////////////////////////////////////////////////// // VarPtr TypeGen::visit(ts::SubroutineType* pType) { std::stringstream code; code << "_T_Pfn<"; // return type // if(pType->isFunction()) { m_pBackend->_generateType(pType->returnType()); code << typeExt(pType->returnType())->genName; } else code << "void"; // argument types // code << " (*)(void*"; auto pParamList = pType->paramList(); for(auto it = pParamList->begin(); it != pParamList->end(); ++it) { m_pBackend->_generateType(it->pType); code << ", " << typeExt(it->pType)->genName; if(it->byRef) code << "&"; } code << ")>"; return _typedefType(code); } /////////////////////////////////////////////////////////////////////////////// // VarPtr TypeGen::visit(ts::FileType* pType) { m_pBackend->_generateType(pType->elemType()); if(!pType->elemType()->isChar()) { context()->warning(pType->line(), "only Text files are supported"); } return _typedefType("_T_Text"); } /////////////////////////////////////////////////////////////////////////////// // VarPtr TypeGen::visit(ts::PointerType* pType) { m_pBackend->_generateType(pType->baseType()); assert(!m_name.empty()); std::stringstream code; code << "_PTR_TYPE(" << m_name << ", " << typeExt(pType->baseType())->genName << ")\n"; return allocStr(code); } /////////////////////////////////////////////////////////////////////////////// // VarPtr TypeGen::visit(ts::ArrayType* pType) { m_pBackend->_generateType(pType->elemType()); std::stringstream code; auto pIndexType = pType->indexType(); code << "_T_Array< " << pIndexType->minValue() << ", "; code << pIndexType->maxValue() << ", "; code << typeExt(pType->elemType())->genName << " >"; return _typedefType(code); } /////////////////////////////////////////////////////////////////////////////// // template<typename T> bool _fits(int min, int max) { assert(min <= max); return min >= std::numeric_limits<T>::min() && max <= std::numeric_limits<T>::max(); } /////////////////////////////////////////////////////////////////////////////// // VarPtr TypeGen::visit(ts::RangeType* pType) { string baseType = "?"; const int min = pType->minValue(); const int max = pType->maxValue(); if(pType->baseType()->isChar()) baseType = "char"; else if(_fits<signed __int8>(min, max)) baseType = "signed __int8"; else if(_fits<unsigned __int8>(min, max)) baseType = "unsigned __int8"; else if(_fits<signed __int16>(min, max)) baseType = "signed __int16"; else if(_fits<unsigned __int16>(min, max)) baseType = "unsigned __int16"; else baseType = "signed __int32"; std::stringstream code; code << "_T_Range<" << pType->minValue() << ", " << pType->maxValue() << ", " << baseType << ">"; return _typedefType(code); } } // end namespace cpp
[ "lemo1234@gmail.com" ]
lemo1234@gmail.com
7658a0db7cfefd9254feca8859f8edd943f03a8f
f553f5e7755f92de755e7f57c2eacf584d4c5cbe
/Classs-sort/insertion.h
9cee88fd4a649f08d0eb5e2eda4dcabc059c8cd4
[]
no_license
Eduardojav/LP2
83b1651663d075e8039d5441ee7767002d7fe709
150b093a6d30bd363c240d0a91c520ac00c0300e
refs/heads/master
2020-05-01T14:58:55.950015
2019-06-20T19:02:01
2019-06-20T19:02:01
177,534,518
0
1
null
null
null
null
UTF-8
C++
false
false
681
h
#ifndef INSERTION_H_INCLUDED #define INSERTION_H_INCLUDED #include "sort.h" template<class T> class Insertion:public Sort<T>{ private: public: Insertion(){} ~Insertion(){} void sortq(T *&A,int a){ int ext; int j=1; int aux; while(j<a){ ext=A[j]; for(int i=j-1;i>=0;i--){ if(A[i]>ext){ A[i+1]=A[i]; } else{ A[i+1]=ext; i=-1; } aux=i; } if(aux==0){ A[0]=ext; } j++; } } }; #endif // INSERTION_H_INCLUDED
[ "noreply@github.com" ]
noreply@github.com
b6bd1bc7cd62287fb2f4253412241355a4f42b1d
407d7aa4fec490602fd68d28867fe7d6fbe7612a
/Arduino Projects/Tweedekeer/Labo07_Nicholas/Labo07_Oefening4_Nicholas/Labo07_Oefening4_Nicholas.ino
fd222d2d79d549a5cf227d417a1a2dd96dceb1f8
[]
no_license
Nicholas-Osei/Arduino-
7c7b034bc0b44c287089d2b4d044a39b391d0b2f
926ac4a123144c9f465b4b2048d5f6127415ee79
refs/heads/master
2022-12-16T17:19:46.707031
2020-09-22T10:35:27
2020-09-22T10:35:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
809
ino
#include <Stepper.h> #include <Servo.h> const int trigPin = 3, echoPin = 2; float distance, duration; Servo myservo; void setup() { // put your setup code here, to run once: myservo.attach(4); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance = (duration / 2) * 0.0343; Serial.print("Distance = "); Serial.print(distance); Serial.println(" cm"); if (distance > 50) { myservo.write(135); } else if (distance < 20) { myservo.write(45); } else { myservo.write(90); } delay(500); }
[ "noreply@github.com" ]
noreply@github.com
88d3896b2a7aa3915ec6323df9226e6279c8805c
f66e343bd16f5dd4c2652c2f8753efd90fb4e813
/ext/NativePacket.h
41e48139596409812f5ec26616e1238ffbcc0796
[]
no_license
footprint4me/rcapdissector
7046307f9053fe515a9a0b5c6212a5f4d0e5c1c1
399a2da4229f8f371a8c3f4c88fa99ce1985a0eb
refs/heads/master
2021-01-14T10:28:15.490402
2010-11-07T17:47:42
2010-11-07T17:47:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,205
h
#pragma once #include <map> #include <string> #include <set> #include "RubyAndShit.h" #include "rcapdissector.h" #include "ProtocolTreeNode.h" #ifdef USE_LOOKASIDE_LIST #include "RubyAllocator.h" #include "ProtocolTreeNodeLookasideList.h" #endif #include "YamlGenerator.h" #include "Blob.h" /** THe maximum number of bytes in a field value that will be * encoded inline in the field's YAML representation. Any * binary values longer than this will be encoded as * offset/length references into the blob containing the * field's value * * This number is based on the approximate overhead for the * blob name/offset/length reference above the overhead for * a binary value. It's very approximate */ #define MAX_INLINE_VALUE_LENGTH 64 class Packet { public: /** Contains fields keyed by their name */ typedef std::multimap<std::string, ProtocolTreeNode*> NodeNameMap; /** Contains nodes keyed by their parent node's memory address */ typedef std::multimap<guint64, ProtocolTreeNode*> NodeParentMap; static VALUE createClass(); /** Gets the next packet from a capfile object, returning false if the end of the capfile is reached */ static gboolean getNextPacket(VALUE capFileObject, capture_file& cf, VALUE& packet); /** Frees the native resources associated with a Ruby Packet object */ static void freePacket(VALUE packet); epan_dissect_t* getEpanDissect() { return _edt; } /** Gets the range of nodes, including the given node and any siblings nodes, which share the same parent node */ void getNodeSiblings(ProtocolTreeNode& node, NodeParentMap::iterator& lbound, NodeParentMap::iterator& ubound); /** Finds the ProtocolTreeNode wrapper for a given proto_node */ ProtocolTreeNode* getProtocolTreeNodeFromProtoNode(proto_node* node); /** Find the Blob object that wraps the given data_source pointer, or NULL if not found */ const Blob* getBlobByDataSourcePtr(data_source* ds); /** Find the Blob object that wraps the data_source which contains the given tvb */ const Blob* getBlobByTvbuffPtr(tvbuff_t* tvb); /** Releases the protocol tree nodes allocated for this packet. Needs to happen before CapFile is GC'd if using lookaside list*/ void free(); private: /** A version of the less<> comparator that operates on ProtocolTreeNode pointers, using the ordinal to sort */ class ProtocolTreeNodeLess { public: typedef ProtocolTreeNode* first_argument_type; typedef ProtocolTreeNode* second_argument_type; typedef bool result_type; ProtocolTreeNodeLess() {} bool operator()(ProtocolTreeNode const* lhs, ProtocolTreeNode const* rhs) { return lhs->getOrdinal() < rhs->getOrdinal(); } }; typedef std::set<ProtocolTreeNode*, ProtocolTreeNodeLess> ProtocolTreeNodeOrderedSet; typedef std::list<Blob*> BlobsList; Packet(); virtual ~Packet(void); const Packet& operator=(const Packet&) { //TODO: Implement return *this; } /** Applies whatever filter is outstanding, and if packet passes filter, creates a Ruby Packet object and its corresponding native object */ static VALUE processPacket(VALUE capFileObject, capture_file& cf, gint64 offset); /*@ Packet capture helper methods */ static void fillInFdata(frame_data *fdata, capture_file& cf, const struct wtap_pkthdr *phdr, gint64 offset); static void clearFdata(frame_data *fdata); /*@ Methods implementing the Packet Ruby object methods */ static void free(void* p); static void mark(void* p); static VALUE alloc(VALUE klass); static VALUE initialize(VALUE self, VALUE capFileObject); static VALUE init_copy(VALUE copy, VALUE orig); static VALUE number(VALUE self); static VALUE timestamp(VALUE self); static VALUE source_address(VALUE self); static VALUE destination_address(VALUE self); static VALUE protocol(VALUE self); static VALUE info(VALUE self); static VALUE field_exists(VALUE self, VALUE fieldName); static VALUE descendant_field_exists(VALUE self, VALUE parentField, VALUE fieldName); static VALUE find_first_field(VALUE self, VALUE fieldName); static VALUE each_field(int argc, VALUE* argv, VALUE self); static VALUE find_first_descendant_field(VALUE self, VALUE parentField, VALUE fieldName); static VALUE each_descendant_field(int argc, VALUE* argv, VALUE self); static VALUE each_root_field(VALUE self); static VALUE field_matches(VALUE self, VALUE query); static VALUE descendant_field_matches(VALUE self, VALUE parentField, VALUE query); static VALUE find_first_field_match(VALUE self, VALUE query); static VALUE each_field_match(VALUE self, VALUE query); static VALUE find_first_descendant_field_match(VALUE self, VALUE parentField, VALUE query); static VALUE each_descendant_field_match(VALUE self, VALUE parentField, VALUE query); static VALUE blobs(VALUE self); static VALUE to_yaml(VALUE self); /*@ Instance methods that actually perform the Packet-specific work */ void buildPacket(); void addNode(proto_node* node); VALUE getRubyFieldObjectForField(ProtocolTreeNode& node); void mark(); VALUE getNumber(); VALUE getTimestamp(); VALUE getSourceAddress(); VALUE getDestinationAddress(); VALUE getProtocol(); VALUE getInfo(); VALUE fieldExists(VALUE fieldName); VALUE descendantFieldExists(VALUE parentField, VALUE fieldName); VALUE findFirstField(VALUE fieldName); VALUE eachField(int argc, VALUE* argv); VALUE findFirstDescendantField(VALUE parentField, VALUE fieldName); VALUE eachDescendantField(int argc, VALUE* argv); VALUE eachRootField(); VALUE fieldMatches(VALUE query); VALUE descendantFieldMatches(VALUE parentField, VALUE query); VALUE findFirstFieldMatch(VALUE query); VALUE eachFieldMatch(VALUE query); VALUE findFirstDescendantFieldMatch(VALUE parentField, VALUE query); VALUE eachDescendantFieldMatch(VALUE parentField, VALUE query); VALUE getBlobs(); VALUE toYaml(); VALUE getColumn(gint colFormat); void addFieldToYaml(ProtocolTreeNode* node, YamlGenerator& yaml); /** Recursive function that adds nodes in a protocol tree to the node list */ void addProtocolNodes(proto_tree *tree); void ensureBlobsLoaded(); /** Adds the data_source's for the packet as Blobs */ void addDataSourcesAsBlobs(GSList* dses); void addDataSourceAsBlob(data_source* ds); /** Recursive function that searches a branch of the protocol tree for a field of a given name */ ProtocolTreeNode* findDescendantNodeByName(ProtocolTreeNode* parent, const gchar* name); /** Recursive function that searches a branch of the protocol tree for a field of a given name */ VALUE findDescendantFieldByName(ProtocolTreeNode* parent, const gchar* name); /** Recursive function that searches a branch of the protocol tree and adds every field that matches to the set */ void findDescendantFieldByName(ProtocolTreeNode* parent, const gchar* name, ProtocolTreeNodeOrderedSet& set); /** Recursive function that searches a branch of the protocol tree for a field matching a given query */ ProtocolTreeNode* findDescendantNodeByQuery(ProtocolTreeNode* parent, VALUE fieldQueryObject, VALUE query); /** Recursive function that searches a branch of the protocol tree for a field matching a given query */ VALUE findDescendantFieldByQuery(ProtocolTreeNode* parent, VALUE fieldQueryObject, VALUE query); /** Recursive function that searches a branch of the protocol tree and adds every field that matches to the set */ void findDescendantFieldByQuery(ProtocolTreeNode* parent, VALUE fieldQueryObject, VALUE query, ProtocolTreeNodeOrderedSet& set); /** Sorts a range of ProtocolTreeNode* objects identified by iterators of Pair<>s, then calls rb_yield with the Field object for each node */ template <typename T> void sortAndYield(T begin, T end) { ProtocolTreeNodeOrderedSet sorted; fillSetWithRange(begin, end, sorted); for (ProtocolTreeNodeOrderedSet::iterator iter = sorted.begin(); iter != sorted.end(); ++iter) { ::rb_yield(getRubyFieldObjectForField(*(*iter))); } } /** Specialization of sortAndYield for ProtocolTreeNodeOrderedSet iterators */ void sortAndYield(ProtocolTreeNodeOrderedSet::iterator begin, ProtocolTreeNodeOrderedSet::iterator end) { for (ProtocolTreeNodeOrderedSet::iterator iter = begin; iter != end; ++iter) { ::rb_yield(getRubyFieldObjectForField(*(*iter))); } } /** Fills a ProtocolTreeNodeORderedSet with the ProtocolTreeNode objects from a range of iterators */ template<typename T> void fillSetWithRange(T begin, T end, ProtocolTreeNodeOrderedSet& sorted) { while (begin != end) { sorted.insert(begin->second); ++begin; } } VALUE _self; epan_dissect_t* _edt; frame_data _frameData; wtap* _wth; capture_file* _cf; NodeNameMap _nodesByName; NodeParentMap _nodesByParent; VALUE _blobsHash; BlobsList _blobs; guint _nodeCounter; #ifdef USE_LOOKASIDE_LIST ProtocolTreeNodeLookasideList* _nodeLookaside; #endif };
[ "anelson@apocryph.org" ]
anelson@apocryph.org
9147fcc9a8f9afeccfcc8f16d1dea3091f12d440
4157cbf83aa33b5cc611165b4839b92d9e37b3d4
/srcs/request_parsing/cdtl_headers.cpp
73bd4a67c0b5fbd88132fbbb422d27becee0e825
[]
no_license
trixky/webserver
032e7eb317bc7ab1e98e5bfe07031ae664e7aebe
debeed38c71637f98a3c7b89802b01ec95ee7009
refs/heads/master
2022-06-13T14:23:47.077388
2020-05-06T11:50:38
2020-05-06T11:50:38
261,736,952
0
0
null
null
null
null
UTF-8
C++
false
false
3,674
cpp
#include "../webserver.hpp" bool modified_since(const std::string &header, const std::string &file) { std::string date; date = get_file_date(file); if (compare_date(file, header)) return (true); return (false); } bool if_match(const std::string &line, const std::string &file_name) { if (!file_name.compare("")) return (false); std::vector<t_etag> etag_vector(ft_parse_line_etag(line)); for (std::vector<t_etag>::iterator it(etag_vector.begin()); it != etag_vector.end(); it++) if (it->hash == ft_sha256(ft_get_features(file_name, it->validation_mod))) return (true); return (false); } std::vector<t_etag> ft_parse_line_etag(const std::string &line) { size_t i(0); t_etag etag_temp; std::vector<t_etag> etag_vector; while (i < line.size()) { etag_temp.hash.clear(); etag_temp.validation_mod = STRONG_VALIDATION; if (line[i] == 'W') { etag_temp.validation_mod = WEAK_VALIDATION; i += 2; } i++; while (line[i] != '"' && line[i]) { etag_temp.hash += line[i]; i++; } etag_vector.push_back(etag_temp); i += 2; } return (etag_vector); } std::string ft_hexa_sha256(int n) { std::string ret; if (n <= 16) ret = '0'; ret += ft_int_to_hex(n, LOWER_CASE); return (ret); } std::string ft_sha256(const std::string source) { unsigned char hash[SHA256_DIGEST_LENGTH + 1]; SHA256_CTX sha256; SHA256_Init(&sha256); SHA256_Update(&sha256, source.c_str(), source.size()); SHA256_Final(hash, &sha256); std::string final_hash; for(int i = 0; i < SHA256_DIGEST_LENGTH; i++) final_hash += ft_hexa_sha256((int)hash[i]); return (final_hash); } std::string ft_read_file(const std::string &file_name) { int fd(0); int ret(0); char buffer[HASH_BUFFER_SIZE + 1]; std::string source; if ((fd = open(file_name.c_str(), O_RDONLY)) < 0) error("open", true); while ((ret = read(fd, buffer, HASH_BUFFER_SIZE)) > 0) { buffer[ret] = '\0'; source += buffer; } if (close(fd) == -1) error("close", true); return (source); } std::string ft_get_info_file(const std::string &file_name) { struct stat buf; std::string info_file; if (stat(file_name.c_str(), &buf) == -1) error("stat", true); info_file += ft_int_to_string(buf.st_ino); /* File serial number */ info_file += ft_int_to_string(buf.st_uid); /* User ID of the file */ info_file += ft_int_to_string(buf.st_gid); /* Group ID of the file */ info_file += ft_int_to_string(buf.st_rdev); /* Device ID */ info_file += ft_int_to_string(buf.st_mtimespec.tv_nsec); /* time of last data modification (nsec)*/ info_file += ft_int_to_string(buf.st_mtimespec.tv_sec); /* time of last data modification (sec)*/ info_file += ft_int_to_string(buf.st_size); /* file size, in bytes */ info_file += ft_int_to_string(buf.st_blocks); /* blocks allocated for file */ info_file += ft_int_to_string(buf.st_blksize); /* optimal blocksize for I/O */ info_file += ft_int_to_string(buf.st_flags); /* user defined flags for file */ info_file += ft_int_to_string(buf.st_gen); /* file generation number */ return (info_file); } std::string ft_get_features(const std::string &file_name, const int mod) { std::string features(ft_read_file(file_name)); switch (mod) { case STRONG_VALIDATION: features += ft_get_info_file(file_name); break; case WEAK_VALIDATION: break; default: error("hash: validition mod is unknown", false); } return (features); }
[ "mathisbois.dev@gmail.com" ]
mathisbois.dev@gmail.com
c0f323e81a91af2524dd62b0124131d78704cfda
a1c88dd6bd8ec97b2f8824ec6f68fe5b4e1784d7
/src/configuration/expr/write_expression.cpp
7cc023b9c7512b25749cccf7775fd5faac94c455
[]
no_license
Milerius/LibLapin
8b3d08acec2e25a143daed2f57ddb1283a060fc4
192020979c0d8ef58b7c6015de3571102ed9175a
refs/heads/master
2021-01-24T03:13:04.415050
2019-04-06T17:23:45
2019-04-06T17:23:45
122,881,637
0
2
null
2019-04-06T16:58:08
2018-02-25T22:02:11
C++
UTF-8
C++
false
false
2,608
cpp
// Jason Brillante "Damdoshi" // Hanged Bunny Studio 2014-2016 // // Lapin library #include <string.h> #include "lapin_private.h" void restore_expression(std::ostream &ss, Expression &expr, bool complete) { size_t i, j; if ((expr.is_const && complete == false) || expr.optor_family == -1) { writevalue(ss, expr.val); return ; } if (expr.optor_family == Expression::LAST_OPERATOR_FAMILY) { ss << expr.val.name; ss << "("; if (expr.type_cast == Expression::NO_CAST) for (j = 0; j < expr.operand.size(); ++j) { if (expr.operand[j] != NULL) { if (expr.operand[j]->val.name != "") ss << expr.operand[j]->val.name << " = "; restore_expression(ss, *expr.operand[j], true); } if (j + 1 < expr.operand.size()) ss << ", "; } else restore_expression(ss, *expr.operand[0], complete); ss << ")"; return ; } for (i = 0; i < expr.operand.size(); ++i) { if (i != 0) { ss << " " << Expression::OperatorToken [expr.optor_family][expr.operand[i]->optor][0] << " "; } if (expr.optor_family > expr.operand[i]->optor_family && expr.operand[i]->optor_family != Expression::LAST_OPERATOR_FAMILY && expr.operand[i]->optor_family != -1) { ss << "("; restore_expression(ss, *expr.operand[i], complete); ss << ")"; } else restore_expression(ss, *expr.operand[i], complete); } } char *_bunny_write_expression_prec(const t_bunny_configuration *cnf) { SmallConf *config = (SmallConf*)cnf; std::stringstream ss; char *ret; if (config->expression == NULL) return (NULL); restore_expression(ss, *config->expression, false); if ((ret = (char*)bunny_malloc(sizeof(*ret) * (ss.str().size() + 1))) == NULL) scream_error_if (return (NULL), bunny_errno, "%p -> %s", "ressource,configuraton", config, ret); strcpy(ret, ss.str().c_str()); scream_log_if("%p -> %s", "ressource,configuration", config, ret); return (ret); } char *_bunny_write_expression(const t_bunny_configuration *cnf) { SmallConf *config = (SmallConf*)cnf; std::stringstream ss; char *ret; if (config->expression == NULL) return (NULL); restore_expression(ss, *config->expression, true); if ((ret = (char*)bunny_malloc(sizeof(*ret) * (ss.str().size() + 1))) == NULL) scream_error_if (return (NULL), bunny_errno, "%p -> %s", "ressource,configuration", config, ret); strcpy(ret, ss.str().c_str()); scream_log_if("%p -> %s", "ressource,configuration", config, ret); return (ret); }
[ "jbrillante@anevia.com" ]
jbrillante@anevia.com
79ebe6d0d394f9eaa05610bd225447e760d36d09
d17c617779c8fbdca28e7a823f528483ff0caf12
/Android/AndroidVirtualControllerNative/jni/GLUtils.cpp
fbd4e4e909a4f6fb720acfcfd6888ab72525cd09
[]
no_license
MasashiWada/ouya-sdk-examples
1d2665749bc58396ff7d017d1f8fb7ce41237e1d
854422922fa2c8700d13c9c4b6ecfed756b56355
refs/heads/master
2020-06-08T22:00:56.703540
2016-09-19T20:57:12
2016-09-19T20:57:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,638
cpp
#include <android/log.h> #include <jni.h> #include "GLUtils.h" #define LOG_TAG "android_opengl_GLUtils" namespace android_opengl_GLUtils { JNIEnv* GLUtils::_env = 0; jclass GLUtils::_jcGlUtils = 0; jmethodID GLUtils::_mTexImage2D = 0; int GLUtils::InitJNI(JNIEnv* env) { { const char* strGlUtilsClass = "android/opengl/GLUtils"; __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, "Searching for %s", strGlUtilsClass); _jcGlUtils = env->FindClass(strGlUtilsClass); if (_jcGlUtils) { __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, "Found %s", strGlUtilsClass); } else { __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "Failed to find %s", strGlUtilsClass); return JNI_ERR; } } { const char* strGlUtilsTexImage2D = "texImage2D"; _mTexImage2D = env->GetStaticMethodID(_jcGlUtils, strGlUtilsTexImage2D, "(IILandroid/graphics/Bitmap;I)V"); if (_mTexImage2D) { __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, "Found %s", strGlUtilsTexImage2D); } else { __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "Failed to find %s", strGlUtilsTexImage2D); return JNI_ERR; } } _env = env; return JNI_OK; } void GLUtils::texImage2D(int target, int level, android_graphics_Bitmap::Bitmap bitmap, int border) { if (!_env) { __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "JNI must be initialized with a valid environment!"); return; } jobject arg3 = bitmap.GetInstance(); _env->CallStaticIntMethod(_jcGlUtils, _mTexImage2D, target, level, arg3, border); __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, "Success on texImage2D"); } }
[ "tgraupmann@gmail.com" ]
tgraupmann@gmail.com
3b4490a2837367bdf2294194e70adfe9f1f464ee
cf0b3a67f92b8a2063b100e35e955d7270fd7975
/ICG_SourceCodes/SplashState.h
03f195d72d35ec2ec0a08b90157ed882cb818818
[]
no_license
andrewnvu/Indie-Card-Game
e662698f91f019cf2fcb83e79fd2bbed2b838a3f
219179a04e189c81c9fa72206ec386110ae0d269
refs/heads/master
2020-03-14T15:09:19.429985
2018-05-01T03:15:41
2018-05-01T03:15:41
131,669,921
0
0
null
null
null
null
UTF-8
C++
false
false
376
h
#pragma once #include <SFML\Graphics.hpp> #include "State.h" #include "Game.h" namespace ASGames { class SplashState :public State { public: SplashState(GameDataRef data); void Init(); void HandleInput(); void Update(float dt); void Draw(float dt); private: GameDataRef _data; sf::Clock _clock; sf::Sprite _background; }; }
[ "noreply@github.com" ]
noreply@github.com
8593ff24f4b1a33509b58f3eab336623f4f9a223
e49cfa86c472356574ed5ef109a199feb031d2bd
/programs/basics/test01/commentTest02.cc
e05e800c1e0cfcc6042ca9b61e1caa18b523d68d
[]
no_license
zfreiberg/zfreibergLearningCPP
a851e9f8aa1f719c2ffb03fabe43410e69f9400e
2b56b5f79a61f29fe1efe274867f830670e61537
refs/heads/master
2021-06-04T14:48:18.970218
2016-07-19T23:56:39
2016-07-19T23:56:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
272
cc
#include <iostream> /* * Testing Comments */ int main () { std::cout << "/*"; std::cout << std::endl; std::cout << "*/"; std::cout << std::endl; //std::cout << /* "*/" */; //std::cout << std::endl; std::cout << /* "*/" /* "/*" */; std::cout << std::endl; }
[ "zachary.freiberg@gmail.com" ]
zachary.freiberg@gmail.com
33e17958cb3e3584e74fc83be7d4462ec566bdd6
753839345d394de155ce5d78877049f6bf16ce6f
/9.回文数.cpp
41729d2a0301a26d2755e860d967414b52b85e3d
[]
no_license
WonderfulUnknown/LeetCode
2df5a68b855f84787cee8fa5e553e70e9f62512d
c392622e567bf5551a92d7fc47d4477000b4d7ee
refs/heads/master
2021-01-02T05:50:59.457795
2020-03-18T09:47:15
2020-03-18T09:47:15
239,516,921
0
0
null
null
null
null
UTF-8
C++
false
false
568
cpp
/* * @lc app=leetcode.cn id=9 lang=cpp * * [9] 回文数 */ // @lc code=start class Solution { public: bool isPalindrome(int x) { if (x == 0) return true; if (x < 0) return false; vector<int> v; while (x > 0) { v.push_back(x % 10); x /= 10; } for (int i = 0, j = v.size() - 1; i < j; i++, j--) { if (v[i] != v[j]) return false; } return true; } }; // @lc code=end
[ "389038968@qq.com" ]
389038968@qq.com
f578959d9c624fd34c35124ecafad44000bf5880
3ab9e81f2d216d46871170c2fb1052444a759dba
/drawing.h
4c0077ef41fcdc371cd58f280925357c54844443
[]
no_license
alexaverill/CompileADrawing
7ba855dceec1c91185d987d79e451cb340993094
16b513563da862477e50907d978510eb379c0352
refs/heads/master
2021-05-04T13:24:20.079564
2018-02-05T14:19:45
2018-02-05T14:19:45
120,314,598
0
0
null
null
null
null
UTF-8
C++
false
false
554
h
#ifndef DRAWING_H #define DRAWING_H #include <QObject> #include<QVariant> #include<vector> #include<tuple> #include "rgbvalue.h" class Drawing : public QObject { Q_OBJECT Q_PROPERTY(QVariantList imageData READ imageData WRITE setImageData NOTIFY imageDataChanged) public: explicit Drawing(QObject *parent = nullptr); QVariantList imageData(); void setImageData(QVariantList); public slots: void processData(QVariantList input); signals: void imageDataChanged(); private: QVariantList m_imageData; }; #endif // DRAWING_H
[ "alex.averill2013@gmail.com" ]
alex.averill2013@gmail.com
143527ea73f4dd77f7becda351f653416139072a
b3f0037b6483e6be647cd8b64d06befc3f6ce8c4
/codeforces/1497/E1.cpp
9e6b3be2208711f9f8764e626519e680fc92a63e
[]
no_license
arnab000/Problem-Solving
7b658ac19b7e8ec926e6f689f989637926b8089b
b407c0d7382961c50edd59fed9ca746b057a90fd
refs/heads/master
2023-04-05T14:40:50.634735
2021-04-21T01:45:00
2021-04-23T01:05:39
328,335,023
4
0
null
null
null
null
UTF-8
C++
false
false
4,957
cpp
/*#pragma GCC target ("avx2") #pragma GCC optimization ("O3") #pragma GCC optimization ("unroll-loops") */ #include<bits/stdc++.h> using namespace std; void __print(int x) {cerr << x;} void __print(long x) {cerr << x;} void __print(long long x) {cerr << x;} void __print(unsigned x) {cerr << x;} void __print(unsigned long x) {cerr << x;} void __print(unsigned long long x) {cerr << x;} void __print(float x) {cerr << x;} void __print(double x) {cerr << x;} void __print(long double x) {cerr << x;} void __print(char x) {cerr << '\'' << x << '\'';} void __print(const char *x) {cerr << '\"' << x << '\"';} void __print(const string &x) {cerr << '\"' << x << '\"';} void __print(bool x) {cerr << (x ? "true" : "false");} template<typename T, typename V> void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';} template<typename T> void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";} void _print() {cerr << "]\n";} template <typename T, typename... V> void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);} #ifndef ONLINE_JUDGE #define debug(x...) cerr << "[" << #x << "] = ["; _print(x) #else #define debug(x...) #endif #define ll long long #define f first #define s second #define Fast ios_base::sync_with_stdio(false);cin.tie(NULL); typedef pair<ll , pair<ll, ll> > pi; int pow(int x,int y){ int res=1; while(y){ if(y&1) res*=x; y>>=1; x*=x; } return res; } struct Compare { constexpr bool operator()(pi const & a, pi const & b) const noexcept { return a.first < b.first || (a.first == b.first && a.second.first > b.second.first); } }; void prefix_function( string s,ll arr[] ) { long long border=0; arr[0]=0; for(long long i=1;i<s.size();i++) { while(border>0 && s[i]!=s[border]) border=arr[border-1]; if(s[i]==s[border]) border++; else border=0; arr[i]=border; } }//send mod-2 for a^-1 if mod is a prime number ll mod=998244353; ll add( ll a , ll b) { return (((a%mod)+(b%mod))%mod); } ll mul(ll a,ll b) { return (((a%mod)*(b%mod))%mod); } ll binpow(ll a, ll b) { ll res = 1; while (b) { if (b & 1) res = mul(res, a); a = mul(a, a); b >>= 1; } return res; } ll subs(ll a,ll b) { return (((a%mod)-(b%mod)+mod)%mod); } ll dv(ll a,ll b) { ll inv=binpow(b,mod-2); return mul(a,inv); } ll dsu_arr[100000]; ll dsu_sz[100000]; void dsu(ll n) { for(ll i=0;i<=n;i++) { dsu_arr[i]=i; dsu_sz[i]=1; } } ll find(ll x) { ll root=x; while (root!=dsu_arr[root]) { root=dsu_arr[root]; } while(x!=dsu_arr[x]) { dsu_arr[x]=root; x=dsu_arr[x]; } return root; } ll merge(ll x,ll y) { ll root1=find(x); ll root2=find(y); if(root1==root2) return 0ll; if(dsu_sz[x]>dsu_sz[y]){ dsu_arr[root2]=root1; dsu_sz[root1]+=dsu_sz[root2]; } else { dsu_sz[root2]+=dsu_sz[root1]; dsu_arr[root1]=root2; } return 1ll; } /* vector<ll>adj[100005]; bool vis[100005]; ll dist[100005]; void bfs(ll c) { vis[c]=true; dist[c]=0; queue<ll>q; q.push(c); while(!q.empty()) { ll x=q.front(); q.pop(); for(ll i=0;i<adj[x].size();i++) { ll y=adj[x][i]; if(!vis[y]) { vis[y]=true; dist[y]=dist[x]+1; q.push(y); } } } } */ vector<ll>primes; bool prime[10000005]; void sieve(ll x) { for(ll i=2;i<=x;i++) { if(!prime[i]) { for(ll j=i*i;j<=x;j+=i) { prime[j]=true; } } } for(ll i=2;i<=x;i++) { if(!prime[i]) primes.push_back(i); } } ll fact(ll y) { ll ans=1; for(ll i=0;i<primes.size();i++) { ll cnt=0; if(primes[i]*primes[i]>y) break; while(y%primes[i]==0) { y/=primes[i]; cnt++; } if(cnt%2) ans*=primes[i]; if(y==1) break; } if(y>1) ans*=y; return ans; } int main() { Fast ll test; cin>>test; sieve(10000003); while(test--) { ll n,m; cin>>n>>m; vector<ll>sura; map<ll,ll>mp; ll a=1; for(ll i=0;i<n;i++) { ll k; cin>>k; ll u=fact(k); if(mp[u]) { mp.clear(); mp[u]++; a++; } else { mp[u]++; } } cout<<a<<'\n'; } }
[ "arnab.saintjoseph@gmail.com" ]
arnab.saintjoseph@gmail.com
967df92a0d330379e564860020c3f9c789e51c3d
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/collectd/gumtree/collectd_repos_function_1153_collectd-4.10.2.cpp
7955b07b7a7adceb847815375a719db3ae96cbf5
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
350
cpp
static int set_timeout (oconfig_item_t *ci, int *timeout) { if ((0 != ci->children_num) || (1 != ci->values_num) || (OCONFIG_TYPE_NUMBER != ci->values[0].type)) { log_err ("%s expects a single number argument.", ci->key); return 1; } *timeout = (int)ci->values[0].value.number; if (0 > *timeout) *timeout = DEFAULT_TIMEOUT; return 0; }
[ "993273596@qq.com" ]
993273596@qq.com
d85496e04b8d4fcd7e24f901eb2dd65cc1851ce1
0e44257aa418a506b1bb2f76c715e403cb893f13
/NWNXLib/API/Mac/API/SASL.cpp
070d84e2e87d655f13388f21abb5ce47b2258477
[ "MIT" ]
permissive
Silvard/nwnxee
58bdfa023348edcc88f9d3cfd9ff77fdd6194058
0989acb86e4d2b2bdcf25f6eabc16df7a72fb315
refs/heads/master
2020-04-15T22:04:43.925619
2019-10-10T14:18:53
2019-10-10T14:18:53
165,058,523
0
0
MIT
2019-10-10T14:18:57
2019-01-10T12:44:36
C++
UTF-8
C++
false
false
148
cpp
#include "SASL.hpp" #include "API/Functions.hpp" #include "Platform/ASLR.hpp" #include "SASLproto.hpp" namespace NWNXLib { namespace API { } }
[ "liarethnwn@gmail.com" ]
liarethnwn@gmail.com
97ad424dabb3b2e317cfc2bae38a6ed6ed07ec29
0543967d1fcd1ce4d682dbed0866a25b4fef73fd
/Midterm/solutions/midterm2017_154/J/001006-midterm2017_154-J.cpp
6dd16b8ae5ef357d1909781b0ecfd1e2163a814d
[]
no_license
Beisenbek/PP12017
5e21fab031db8a945eb3fa12aac0db45c7cbb915
85a314d47cd067f4ecbbc24df1aa7a1acd37970a
refs/heads/master
2021-01-19T18:42:22.866838
2017-11-25T12:13:24
2017-11-25T12:13:24
101,155,127
0
0
null
null
null
null
UTF-8
C++
false
false
512
cpp
#include <iostream> using namespace std; int main() { int n, m; cin >> n >> m; int arr[n][m], sum[n]; int mx1 = -1, mx2 = -1; for(int i = 0; i < n; i++) { sum[i] = 0; for(int j = 0; j < m; j++) { cin >> arr[i][j]; sum[i] += arr[i][j]; if(mx1 < arr[i][j]) { mx1 = arr[i][j]; } cout <<i; } } return 0; }
[ "beysenbek@gmail.com" ]
beysenbek@gmail.com
77794f83e30b56d3a0513803650f8dd8571e5f5e
cc2bdea20b5f558ad098c9cee6adc73635929877
/measurement_test.cc
cad79656b395e9cbbce209bc6d52956d9bf75b3f
[]
no_license
unrstuart/power_cycling
d0890de5b278d3d4728111266b9f2227df4f425a
ba181e3e99c9eff61bbad216dc7c4a8ff33b27f7
refs/heads/master
2021-01-22T03:18:12.942344
2017-02-19T10:01:21
2017-02-19T10:01:21
81,112,916
0
0
null
null
null
null
UTF-8
C++
false
false
900
cc
#include "measurement.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "si_unit.h" using TimePoint = cycling::TimeSample::TimePoint; namespace cycling { namespace { TEST(MeasurementTest, Test) { Measurement m0(Measurement::NO_TYPE, 1); Measurement m1(Measurement::NO_TYPE, 2); Measurement m2(Measurement::HEART_RATE, 150); Measurement m3(Measurement::HRV, 8.2); Measurement m4(Measurement::POWER, 250); Measurement m5(Measurement::POWER, SiVar(SiUnit::Watt(), 250)); EXPECT_EQ(m0, m0); EXPECT_EQ(m1, m1); EXPECT_EQ(m2, m2); EXPECT_EQ(m3, m3); EXPECT_LT(m0, m1); EXPECT_GT(m1, m0); EXPECT_LE(m0, m0); EXPECT_GE(m2, m2); EXPECT_NE(m0, m3); EXPECT_NE(m1, m2); EXPECT_EQ(m4, m5); EXPECT_EQ(m4.value(), m5.value()); EXPECT_DEATH(Measurement(Measurement::TOTAL_JOULES, SiVar(SiUnit::Unitless(), 10)); } } // namespace } // namespace cycling
[ "cpunerd@gmail.com" ]
cpunerd@gmail.com
a4a819a31dad47c8c1f34791693640ceb8d81505
81fd1df1f51e75a9d6fe11b009df8c0d422d3871
/src/qt/rpcconsole.cpp
7167c2c263b47e7951d9b17afd0446eaac3b3365
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
BardonMe/Aevo
8e938b8afa4b908a0e36205c39935b9dc7648d3f
b831188abd5367ff00307fe5b12cc6683bb542c5
refs/heads/master
2020-03-08T05:04:56.219151
2018-04-03T16:48:43
2018-04-03T16:48:43
127,938,891
3
2
null
null
null
null
UTF-8
C++
false
false
28,854
cpp
#include "rpcconsole.h" #include "ui_rpcconsole.h" #include "bantablemodel.h" #include "clientmodel.h" #include "guiutil.h" #include "peertablemodel.h" #include "main.h" #include "chainparams.h" #include "util.h" #include "rpcserver.h" #include "rpcclient.h" #include <QClipboard> #include <QTime> #include <QThread> #include <QKeyEvent> #include <QMenu> #include <QUrl> #include <QScrollBar> #include <QSignalMapper> #include <openssl/crypto.h> // TODO: add a scrollback limit, as there is currently none // TODO: make it possible to filter out categories (esp debug messages when implemented) // TODO: receive errors and debug messages through ClientModel const int CONSOLE_HISTORY = 50; const QSize ICON_SIZE(24, 24); const int INITIAL_TRAFFIC_GRAPH_MINS = 30; const struct { const char *url; const char *source; } ICON_MAPPING[] = { {"cmd-request", ":/icons/tx_input"}, {"cmd-reply", ":/icons/tx_output"}, {"cmd-error", ":/icons/tx_output"}, {"misc", ":/icons/tx_inout"}, {NULL, NULL} }; /* Object for executing console RPC commands in a separate thread. */ class RPCExecutor : public QObject { Q_OBJECT public slots: void start(); void request(const QString &command); signals: void reply(int category, const QString &command); }; #include "rpcconsole.moc" void RPCExecutor::start() { // Nothing to do } /** * Split Aevo command line into a list of arguments. Aims to emulate \c bash and friends. * * - Arguments are delimited with whitespace * - Extra whitespace at the beginning and end and between arguments will be ignored * - Text can be "double" or 'single' quoted * - The backslash \c \ is used as escape character * - Outside quotes, any character can be escaped * - Within double quotes, only escape \c " and backslashes before a \c " or another backslash * - Within single quotes, no escaping is possible and no special interpretation takes place * * @param[out] args Parsed arguments will be appended to this list * @param[in] strCommand Command line to split */ bool parseCommandLine(std::vector<std::string> &args, const std::string &strCommand) { enum CmdParseState { STATE_EATING_SPACES, STATE_ARGUMENT, STATE_SINGLEQUOTED, STATE_DOUBLEQUOTED, STATE_ESCAPE_OUTER, STATE_ESCAPE_DOUBLEQUOTED } state = STATE_EATING_SPACES; std::string curarg; foreach(char ch, strCommand) { switch(state) { case STATE_ARGUMENT: // In or after argument case STATE_EATING_SPACES: // Handle runs of whitespace switch(ch) { case '"': state = STATE_DOUBLEQUOTED; break; case '\'': state = STATE_SINGLEQUOTED; break; case '\\': state = STATE_ESCAPE_OUTER; break; case ' ': case '\n': case '\t': if(state == STATE_ARGUMENT) // Space ends argument { args.push_back(curarg); curarg.clear(); } state = STATE_EATING_SPACES; break; default: curarg += ch; state = STATE_ARGUMENT; } break; case STATE_SINGLEQUOTED: // Single-quoted string switch(ch) { case '\'': state = STATE_ARGUMENT; break; default: curarg += ch; } break; case STATE_DOUBLEQUOTED: // Double-quoted string switch(ch) { case '"': state = STATE_ARGUMENT; break; case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break; default: curarg += ch; } break; case STATE_ESCAPE_OUTER: // '\' outside quotes curarg += ch; state = STATE_ARGUMENT; break; case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself curarg += ch; state = STATE_DOUBLEQUOTED; break; } } switch(state) // final state { case STATE_EATING_SPACES: return true; case STATE_ARGUMENT: args.push_back(curarg); return true; default: // ERROR to end in one of the other states return false; } } void RPCExecutor::request(const QString &command) { std::vector<std::string> args; if(!parseCommandLine(args, command.toStdString())) { emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \"")); return; } if(args.empty()) return; // Nothing to do try { std::string strPrint; // Convert argument list to JSON objects in method-dependent way, // and pass it along with the method name to the dispatcher. json_spirit::Value result = tableRPC.execute( args[0], RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end()))); // Format result reply if (result.type() == json_spirit::null_type) strPrint = ""; else if (result.type() == json_spirit::str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint)); } catch (json_spirit::Object& objError) { try // Nice formatting for standard-format error { int code = find_value(objError, "code").get_int(); std::string message = find_value(objError, "message").get_str(); emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")"); } catch(std::runtime_error &) // raised when converting to invalid type, i.e. missing code or message { // Show raw JSON object emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false))); } } catch (std::exception& e) { emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what())); } } RPCConsole::RPCConsole(QWidget *parent) : QWidget(parent), ui(new Ui::RPCConsole), historyPtr(0), cachedNodeid(-1), peersTableContextMenu(0), banTableContextMenu(0) { ui->setupUi(this); #ifndef Q_OS_MAC ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export")); ui->showCLOptionsButton->setIcon(QIcon(":/icons/options")); #endif // Install event filter for up and down arrow ui->lineEdit->installEventFilter(this); ui->messagesWidget->installEventFilter(this); // set OpenSSL version label ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION)); startExecutor(); setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS); ui->detailWidget->hide(); ui->peerHeading->setText(tr("Select a peer to view detailed information.")); clear(); } RPCConsole::~RPCConsole() { emit stopExecutor(); delete ui; } bool RPCConsole::eventFilter(QObject* obj, QEvent *event) { if(event->type() == QEvent::KeyPress) // Special key handling { QKeyEvent *keyevt = static_cast<QKeyEvent*>(event); int key = keyevt->key(); Qt::KeyboardModifiers mod = keyevt->modifiers(); switch(key) { case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break; case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break; case Qt::Key_PageUp: /* pass paging keys to messages widget */ case Qt::Key_PageDown: if(obj == ui->lineEdit) { QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt)); return true; } break; default: // Typing in messages widget brings focus to line edit, and redirects key there // Exclude most combinations and keys that emit no text, except paste shortcuts if(obj == ui->messagesWidget && ( (!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) || ((mod & Qt::ControlModifier) && key == Qt::Key_V) || ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert))) { ui->lineEdit->setFocus(); QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt)); return true; } } } return QWidget::eventFilter(obj, event); } void RPCConsole::setClientModel(ClientModel *model) { clientModel = model; ui->trafficGraph->setClientModel(model); if (model && clientModel->getPeerTableModel() && clientModel->getBanTableModel()) { // Subscribe to information, replies, messages, errors connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); setNumBlocks(model->getNumBlocks()); connect(model, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int))); setMasternodeCount(model->getMasternodeCountString()); connect(model, SIGNAL(strMasternodesChanged(QString)), this, SLOT(setMasternodeCount(QString))); updateTrafficStats(model->getTotalBytesRecv(), model->getTotalBytesSent()); connect(model, SIGNAL(bytesChanged(quint64,quint64)), this, SLOT(updateTrafficStats(quint64, quint64))); // set up peer table ui->peerWidget->setModel(model->getPeerTableModel()); ui->peerWidget->verticalHeader()->hide(); ui->peerWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->peerWidget->setSelectionBehavior(QAbstractItemView::SelectRows); ui->peerWidget->setSelectionMode(QAbstractItemView::SingleSelection); ui->peerWidget->setContextMenuPolicy(Qt::CustomContextMenu); ui->peerWidget->setColumnWidth(PeerTableModel::Address, ADDRESS_COLUMN_WIDTH); ui->peerWidget->setColumnWidth(PeerTableModel::Subversion, SUBVERSION_COLUMN_WIDTH); ui->peerWidget->setColumnWidth(PeerTableModel::Ping, PING_COLUMN_WIDTH); // create context menu actions QAction* disconnectAction = new QAction(tr("&Disconnect Node"), this); QAction* banAction1h = new QAction(tr("Ban Node for") + " " + tr("1 &hour"), this); QAction* banAction24h = new QAction(tr("Ban Node for") + " " + tr("1 &day"), this); QAction* banAction7d = new QAction(tr("Ban Node for") + " " + tr("1 &week"), this); QAction* banAction365d = new QAction(tr("Ban Node for") + " " + tr("1 &year"), this); // create peer table context menu peersTableContextMenu = new QMenu(); peersTableContextMenu->addAction(disconnectAction); peersTableContextMenu->addAction(banAction1h); peersTableContextMenu->addAction(banAction24h); peersTableContextMenu->addAction(banAction7d); peersTableContextMenu->addAction(banAction365d); // Add a signal mapping to allow dynamic context menu arguments. // We need to use int (instead of int64_t), because signal mapper only supports // int or objects, which is okay because max bantime (1 year) is < int_max. QSignalMapper* signalMapper = new QSignalMapper(this); signalMapper->setMapping(banAction1h, 60*60); signalMapper->setMapping(banAction24h, 60*60*24); signalMapper->setMapping(banAction7d, 60*60*24*7); signalMapper->setMapping(banAction365d, 60*60*24*365); connect(banAction1h, SIGNAL(triggered()), signalMapper, SLOT(map())); connect(banAction24h, SIGNAL(triggered()), signalMapper, SLOT(map())); connect(banAction7d, SIGNAL(triggered()), signalMapper, SLOT(map())); connect(banAction365d, SIGNAL(triggered()), signalMapper, SLOT(map())); connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(banSelectedNode(int))); // peer table context menu signals connect(ui->peerWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showPeersTableContextMenu(const QPoint&))); connect(disconnectAction, SIGNAL(triggered()), this, SLOT(disconnectSelectedNode())); // peer table signal handling - update peer details when selecting new node connect(ui->peerWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), this, SLOT(peerSelected(const QItemSelection &, const QItemSelection &))); // peer table signal handling - update peer details when new nodes are added to the model connect(model->getPeerTableModel(), SIGNAL(layoutChanged()), this, SLOT(peerLayoutChanged())); // set up ban table ui->banlistWidget->setModel(model->getBanTableModel()); ui->banlistWidget->verticalHeader()->hide(); ui->banlistWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->banlistWidget->setSelectionBehavior(QAbstractItemView::SelectRows); ui->banlistWidget->setSelectionMode(QAbstractItemView::SingleSelection); ui->banlistWidget->setContextMenuPolicy(Qt::CustomContextMenu); ui->banlistWidget->setColumnWidth(BanTableModel::Address, BANSUBNET_COLUMN_WIDTH); ui->banlistWidget->setColumnWidth(BanTableModel::Bantime, BANTIME_COLUMN_WIDTH); ui->banlistWidget->horizontalHeader()->setStretchLastSection(true); // create ban table context menu action QAction* unbanAction = new QAction(tr("&Unban Node"), this); // create ban table context menu banTableContextMenu = new QMenu(); banTableContextMenu->addAction(unbanAction); // ban table context menu signals connect(ui->banlistWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showBanTableContextMenu(const QPoint&))); connect(unbanAction, SIGNAL(triggered()), this, SLOT(unbanSelectedNode())); // ban table signal handling - clear peer details when clicking a peer in the ban table connect(ui->banlistWidget, SIGNAL(clicked(const QModelIndex&)), this, SLOT(clearSelectedNode())); // ban table signal handling - ensure ban table is shown or hidden (if empty) connect(model->getBanTableModel(), SIGNAL(layoutChanged()), this, SLOT(showOrHideBanTableIfRequired())); showOrHideBanTableIfRequired(); // Provide initial values ui->clientVersion->setText(model->formatFullVersion()); ui->clientName->setText(model->clientName()); ui->buildDate->setText(model->formatBuildDate()); ui->startupTime->setText(model->formatClientStartupTime()); setNumConnections(model->getNumConnections()); ui->isTestNet->setChecked(model->isTestNet()); } } static QString categoryClass(int category) { switch(category) { case RPCConsole::CMD_REQUEST: return "cmd-request"; break; case RPCConsole::CMD_REPLY: return "cmd-reply"; break; case RPCConsole::CMD_ERROR: return "cmd-error"; break; default: return "misc"; } } void RPCConsole::clear() { ui->messagesWidget->clear(); history.clear(); historyPtr = 0; ui->lineEdit->clear(); ui->lineEdit->setFocus(); // Add smoothly scaled icon images. // (when using width/height on an img, Qt uses nearest instead of linear interpolation) for(int i=0; ICON_MAPPING[i].url; ++i) { ui->messagesWidget->document()->addResource( QTextDocument::ImageResource, QUrl(ICON_MAPPING[i].url), QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); } // Set default style sheet ui->messagesWidget->document()->setDefaultStyleSheet( "table { }" "td.time { color: #808080; padding-top: 3px; } " "td.message { font-family: Monospace; font-size: 12px; } " "td.cmd-request { color: #00C0C0; } " "td.cmd-error { color: red; } " "b { color: #00C0C0; } " ); message(CMD_REPLY, (tr("Welcome to the Aevo RPC console.") + "<br>" + tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" + tr("Type <b>help</b> for an overview of available commands.")), true); } void RPCConsole::keyPressEvent(QKeyEvent *event) { if(windowType() != Qt::Widget && event->key() == Qt::Key_Escape) { close(); } } void RPCConsole::message(int category, const QString &message, bool html) { QTime time = QTime::currentTime(); QString timeString = time.toString(); QString out; out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>"; out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>"; out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">"; if(html) out += message; else out += GUIUtil::HtmlEscape(message, true); out += "</td></tr></table>"; ui->messagesWidget->append(out); } void RPCConsole::setNumConnections(int count) { ui->numberOfConnections->setText(QString::number(count)); } void RPCConsole::setNumBlocks(int count) { ui->numberOfBlocks->setText(QString::number(count)); if(clientModel) ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString()); } void RPCConsole::setMasternodeCount(const QString &strMasternodes) { ui->masternodeCount->setText(strMasternodes); } void RPCConsole::on_lineEdit_returnPressed() { QString cmd = ui->lineEdit->text(); ui->lineEdit->clear(); if(!cmd.isEmpty()) { message(CMD_REQUEST, cmd); emit cmdRequest(cmd); // Remove command, if already in history history.removeOne(cmd); // Append command to history history.append(cmd); // Enforce maximum history size while(history.size() > CONSOLE_HISTORY) history.removeFirst(); // Set pointer to end of history historyPtr = history.size(); // Scroll console view to end scrollToEnd(); } } void RPCConsole::browseHistory(int offset) { historyPtr += offset; if(historyPtr < 0) historyPtr = 0; if(historyPtr > history.size()) historyPtr = history.size(); QString cmd; if(historyPtr < history.size()) cmd = history.at(historyPtr); ui->lineEdit->setText(cmd); } void RPCConsole::startExecutor() { QThread* thread = new QThread; RPCExecutor *executor = new RPCExecutor(); executor->moveToThread(thread); // Notify executor when thread started (in executor thread) connect(thread, SIGNAL(started()), executor, SLOT(start())); // Replies from executor object must go to this object connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString))); // Requests from this object must go to executor connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString))); // On stopExecutor signal // - queue executor for deletion (in execution thread) // - quit the Qt event loop in the execution thread connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit())); // Queue the thread for deletion (in this thread) when it is finished connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); // Default implementation of QThread::run() simply spins up an event loop in the thread, // which is what we want. thread->start(); } void RPCConsole::on_tabWidget_currentChanged(int index) { if(ui->tabWidget->widget(index) == ui->tab_console) { ui->lineEdit->setFocus(); } } void RPCConsole::on_openDebugLogfileButton_clicked() { GUIUtil::openDebugLogfile(); } void RPCConsole::scrollToEnd() { QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar(); scrollbar->setValue(scrollbar->maximum()); } void RPCConsole::on_showCLOptionsButton_clicked() { GUIUtil::HelpMessageBox help; help.exec(); } void RPCConsole::on_sldGraphRange_valueChanged(int value) { const int multiplier = 5; // each position on the slider represents 5 min int mins = value * multiplier; setTrafficGraphRange(mins); } QString RPCConsole::FormatBytes(quint64 bytes) { if(bytes < 1024) return QString(tr("%1 B")).arg(bytes); if(bytes < 1024 * 1024) return QString(tr("%1 KB")).arg(bytes / 1024); if(bytes < 1024 * 1024 * 1024) return QString(tr("%1 MB")).arg(bytes / 1024 / 1024); return QString(tr("%1 GB")).arg(bytes / 1024 / 1024 / 1024); } void RPCConsole::setTrafficGraphRange(int mins) { ui->trafficGraph->setGraphRangeMins(mins); ui->lblGraphRange->setText(GUIUtil::formatDurationStr(mins * 60)); } void RPCConsole::on_copyButton_clicked() { GUIUtil::setClipboard(ui->lineEdit->text()); } void RPCConsole::on_pasteButton_clicked() { ui->lineEdit->setText(QApplication::clipboard()->text()); } void RPCConsole::updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut) { ui->lblBytesIn->setText(FormatBytes(totalBytesIn)); ui->lblBytesOut->setText(FormatBytes(totalBytesOut)); } void RPCConsole::on_btnClearTrafficGraph_clicked() { ui->trafficGraph->clear(); } void RPCConsole::showBackups() { GUIUtil::showBackups(); } void RPCConsole::peerSelected(const QItemSelection &selected, const QItemSelection &deselected) { if (!clientModel || !clientModel->getPeerTableModel() || selected.indexes().isEmpty()) return; const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.indexes().first().row()); if (stats) updateNodeDetail(stats); } void RPCConsole::peerLayoutChanged() { if (!clientModel || !clientModel->getPeerTableModel()) return; const CNodeCombinedStats *stats = NULL; bool fUnselect = false; bool fReselect = false; if (cachedNodeid == -1) // no node selected yet return; // find the currently selected row int selectedRow; QModelIndexList selectedModelIndex = ui->peerWidget->selectionModel()->selectedIndexes(); if (selectedModelIndex.isEmpty()) selectedRow = -1; else selectedRow = selectedModelIndex.first().row(); // check if our detail node has a row in the table (it may not necessarily // be at selectedRow since its position can change after a layout change) int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeid); if (detailNodeRow < 0) { // detail node dissapeared from table (node disconnected) fUnselect = true; cachedNodeid = -1; ui->detailWidget->hide(); ui->peerHeading->setText(tr("Select a peer to view detailed information.")); } else { if (detailNodeRow != selectedRow) { // detail node moved position fUnselect = true; fReselect = true; } // get fresh stats on the detail node. stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow); } if (fUnselect && selectedRow >= 0) { ui->peerWidget->selectionModel()->select(QItemSelection(selectedModelIndex.first(), selectedModelIndex.last()), QItemSelectionModel::Deselect); } if (fReselect) { ui->peerWidget->selectRow(detailNodeRow); } if (stats) updateNodeDetail(stats); } void RPCConsole::updateNodeDetail(const CNodeCombinedStats *stats) { // Update cached nodeid cachedNodeid = stats->nodeStats.nodeid; // update the detail ui with latest node information QString peerAddrDetails(QString::fromStdString(stats->nodeStats.addrName)); if (!stats->nodeStats.addrLocal.empty()) peerAddrDetails += "<br />" + tr("via %1").arg(QString::fromStdString(stats->nodeStats.addrLocal)); ui->peerHeading->setText(peerAddrDetails); ui->peerServices->setText(GUIUtil::formatServicesStr(stats->nodeStats.nServices)); ui->peerLastSend->setText(stats->nodeStats.nLastSend ? GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nLastSend) : tr("never")); ui->peerLastRecv->setText(stats->nodeStats.nLastRecv ? GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nLastRecv) : tr("never")); ui->peerBytesSent->setText(FormatBytes(stats->nodeStats.nSendBytes)); ui->peerBytesRecv->setText(FormatBytes(stats->nodeStats.nRecvBytes)); ui->peerConnTime->setText(GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nTimeConnected)); ui->peerPingTime->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingTime)); ui->timeoffset->setText(GUIUtil::formatTimeOffset(stats->nodeStats.nTimeOffset)); ui->peerVersion->setText(QString("%1").arg(stats->nodeStats.nVersion)); ui->peerSubversion->setText(QString::fromStdString(stats->nodeStats.cleanSubVer)); ui->peerDirection->setText(stats->nodeStats.fInbound ? tr("Inbound") : tr("Outbound")); ui->peerHeight->setText(QString("%1").arg(stats->nodeStats.nStartingHeight)); ui->peerSyncNode->setText(stats->nodeStats.fSyncNode ? tr("Yes") : tr("No")); // This check fails for example if the lock was busy and // nodeStateStats couldn't be fetched. if (stats->fNodeStateStatsAvailable) { // Ban score is init to 0 ui->peerBanScore->setText(QString("%1").arg(stats->nodeStateStats.nMisbehavior)); } else { ui->peerBanScore->setText(tr("Fetching...")); } ui->detailWidget->show(); } void RPCConsole::resizeEvent(QResizeEvent *event) { QWidget::resizeEvent(event); } void RPCConsole::showEvent(QShowEvent *event) { QWidget::showEvent(event); if (!clientModel || !clientModel->getPeerTableModel()) return; // start PeerTableModel auto refresh clientModel->getPeerTableModel()->startAutoRefresh(); } void RPCConsole::hideEvent(QHideEvent *event) { QWidget::hideEvent(event); if (!clientModel || !clientModel->getPeerTableModel()) return; // stop PeerTableModel auto refresh clientModel->getPeerTableModel()->stopAutoRefresh(); } void RPCConsole::showPeersTableContextMenu(const QPoint& point) { QModelIndex index = ui->peerWidget->indexAt(point); if (index.isValid()) peersTableContextMenu->exec(QCursor::pos()); } void RPCConsole::showBanTableContextMenu(const QPoint& point) { QModelIndex index = ui->banlistWidget->indexAt(point); if (index.isValid()) banTableContextMenu->exec(QCursor::pos()); } void RPCConsole::disconnectSelectedNode() { // Get currently selected peer address QString strNode = GUIUtil::getEntryData(ui->peerWidget, 0, PeerTableModel::Address); // Find the node, disconnect it and clear the selected node if (CNode *bannedNode = FindNode(strNode.toStdString())) { bannedNode->CloseSocketDisconnect(); ui->peerWidget->selectionModel()->clearSelection(); } } void RPCConsole::banSelectedNode(int bantime) { if (!clientModel) return; // Get currently selected peer address QString strNode = GUIUtil::getEntryData(ui->peerWidget, 0, PeerTableModel::Address); // Find possible nodes, ban it and clear the selected node if (CNode *bannedNode = FindNode(strNode.toStdString())) { std::string nStr = strNode.toStdString(); std::string addr; int port = 0; SplitHostPort(nStr, port, addr); CNode::Ban(CNetAddr(addr), BanReasonManuallyAdded, bantime); bannedNode->fDisconnect = true; DumpBanlist(); clearSelectedNode(); clientModel->getBanTableModel()->refresh(); } } void RPCConsole::unbanSelectedNode() { if (!clientModel) return; // Get currently selected ban address QString strNode = GUIUtil::getEntryData(ui->banlistWidget, 0, BanTableModel::Address); CSubNet possibleSubnet(strNode.toStdString()); if (possibleSubnet.IsValid()) { CNode::Unban(possibleSubnet); DumpBanlist(); clientModel->getBanTableModel()->refresh(); } } void RPCConsole::clearSelectedNode() { ui->peerWidget->selectionModel()->clearSelection(); cachedNodeid = -1; ui->detailWidget->hide(); ui->peerHeading->setText(tr("Select a peer to view detailed information.")); } void RPCConsole::showOrHideBanTableIfRequired() { if (!clientModel) return; bool visible = clientModel->getBanTableModel()->shouldShow(); ui->banlistWidget->setVisible(visible); ui->banHeading->setVisible(visible); }
[ "38047495+BardonMe@users.noreply.github.com" ]
38047495+BardonMe@users.noreply.github.com
cbec0bb9ee6c9ca4a71260035dbb30675c192251
b4d50bae9a154211ded1ca3b97de4fa86939e72d
/examples/atlasSimbicon/Humanoid.hpp
4933ede5b80e51b444df7de715e1670b046c4ae9
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
fredowski/dart
8e5d0e54800b1bca87775aa4d0f5cb25dbea2c99
89214fb29faa9227d39aa24821212cc30ead906b
refs/heads/master
2021-01-13T08:39:11.383009
2017-08-30T09:23:09
2017-08-30T09:23:09
71,817,674
0
0
null
2016-10-24T18:14:35
2016-10-24T18:14:34
null
UTF-8
C++
false
false
3,712
hpp
/* * Copyright (c) 2014-2016, Graphics Lab, Georgia Tech Research Corporation * Copyright (c) 2014-2016, Humanoid Lab, Georgia Tech Research Corporation * Copyright (c) 2016, Personal Robotics Lab, Carnegie Mellon University * All rights reserved. * * This file is provided under the following "BSD-style" License: * 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. * 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. */ #ifndef EXAMPLES_ATLASSIMBICON_HUMANOID_HPP_ #define EXAMPLES_ATLASSIMBICON_HUMANOID_HPP_ #include <vector> #include <string> #include <Eigen/Dense> #include "dart/dart.hpp" class State; //============================================================================== /// \brief class Humanoid /// \warning This class is not used now. class Humanoid { public: /// \brief Constructor Humanoid(dart::dynamics::Skeleton* _skeleton); /// \brief Destructor virtual ~Humanoid(); /// \brief Get skeleton dart::dynamics::Skeleton* getSkeleton(); /// \brief Get pelvis dart::dynamics::BodyNode* getPelvis(); /// \brief Get left thigh dart::dynamics::BodyNode* getLeftThigh(); /// \brief Get right thigh dart::dynamics::BodyNode* getRightThigh(); /// \brief Get left foot dart::dynamics::BodyNode* getLeftFoot(); /// \brief Get right foot dart::dynamics::BodyNode* getRightFoot(); protected: /// \brief State dart::dynamics::Skeleton* mSkeleton; /// \brief Pelvis dart::dynamics::BodyNode* mPelvis; /// \brief LeftThigh dart::dynamics::BodyNode* mLeftThigh; /// \brief LeftThigh dart::dynamics::BodyNode* mRightThigh; /// \brief Left foot dart::dynamics::BodyNode* mLeftFoot; /// \brief Right foot dart::dynamics::BodyNode* mRightFoot; /// \brief Left ankle on sagital plane dart::dynamics::Joint* mLeftAnkleSagital; /// \brief Left ankle on coronal plane dart::dynamics::Joint* mLeftAnkleCoronal; /// \brief Right ankle on sagital plane dart::dynamics::Joint* mRightAnkleSagital; /// \brief Right ankle on coronal plane dart::dynamics::Joint* mRightAnkleCoronal; }; //============================================================================== /// \brief class AtlasRobot /// \warning This class is not used now. class AtlasRobot : public Humanoid { public: /// \brief Constructor AtlasRobot(dart::dynamics::Skeleton* _skeleton); /// \brief Destructor virtual ~AtlasRobot(); protected: }; #endif // EXAMPLES_ATLASSIMBICON_HUMANOID_HPP_
[ "jslee02@gmail.com" ]
jslee02@gmail.com
7e918384fd39733eb62df2a62c4c4602dffb3441
275ec6905a664e6d50f6f7593d62066740b241a0
/13_58.cpp
9919d3381bc13c11f1ea943c5820dd0733b55cd2
[]
no_license
huangjiahua/cppLearningFiles
0f135624d5d7d2256e8fd55146a408170737b603
7000ac6111b33c880a66c2c3cc2e4f41390aff9e
refs/heads/master
2021-09-10T15:11:48.991007
2018-03-28T08:57:41
2018-03-28T08:57:41
122,352,150
0
0
null
null
null
null
UTF-8
C++
false
false
403
cpp
#include <iostream> #include <vector> #include <utility> #include <algorithm> using namespace std; class Foo { private: vector<int> vi; public: Foo(): vi() { }; Foo(const Foo &f): vi(f.vi) { } Foo sorted() && { sort(vi.begin(), vi.end()); return *this; } Foo sorted() const & { return Foo(*this).sorted(); } }; int main() { return 0; }
[ "hjh4477@outlook.com" ]
hjh4477@outlook.com
b8e3af96527148a1221be9e1bb9aa6e24c25379b
6741a0288cab73cde3b963658027dd80ce4f3526
/AbstractPoseDetector.h
5a8af08bd444399536e7fe952adc1c463b51af3f
[]
no_license
ardy30/KinectServer
0a6d6a3b524b3ab905892d91ccb9571574d1bd05
1d4407a0a2748d905488c78ffa85532ad8bd7999
refs/heads/master
2020-06-16T19:21:21.739966
2012-03-12T08:23:55
2012-03-12T08:23:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
777
h
#ifndef WebSocketServer_AbstractPoseDetector_h #define WebSocketServer_AbstractPoseDetector_h #include <XnCppWrapper.h> #include "WebSocket/Server.h" #include "AbstractUserDetector.h" #include "Vector3D.hpp" class AbstractPoseDetector: public AbstractUserDetector { protected: int posingTime; //Poseの持続時間 bool posing; //Poseが継続しているか int lostTime; //PoseがLostしてからの持続時間。 std::string poseName; Server *server; std::string type_; std::string ver_; public: AbstractPoseDetector( Server *s, xn::Context &context); Vector3D getVector(XnSkeletonJoint joint1, XnSkeletonJoint joint2); void detectPose(); void lostPose(); virtual void detect()=0; }; #endif
[ "xxmogi@gmail.com" ]
xxmogi@gmail.com
f2ddf3e0a379517a78dd06ee5726a89fbbd64721
78b28019e10962bb62a09fa1305264bbc9a113e3
/common/vector/rmq/ppt.h
f4a5ddddeca699ae425fbd24b2512fe2463fc0e1
[ "MIT" ]
permissive
Loks-/competitions
49d253c398bc926bfecc78f7d468410702f984a0
26a1b15f30bb664a308edc4868dfd315eeca0e0b
refs/heads/master
2023-06-08T06:26:36.756563
2023-05-31T03:16:41
2023-05-31T03:16:41
135,969,969
5
2
null
null
null
null
UTF-8
C++
false
false
1,277
h
#pragma once #include "common/base.h" #include "common/numeric/bits/ulog2.h" #include "common/vector/rmq/position_value.h" #include <vector> namespace nvector { namespace rmq { // Precompute all intervals whose length is a power of two. // O(N log N) memory, O(N log N) preprocessing time, O(1) request time template <class TTValue> class PPT { public: using TValue = TTValue; using TPositionValue = PositionValue<TValue>; protected: std::vector<std::vector<TPositionValue>> vpv; public: PPT() {} PPT(const std::vector<TValue>& v) { Build(v); } void Build(const std::vector<TValue>& v) { size_t n = v.size(); size_t k = numeric::ULog2(uint64_t(n)); vpv.resize(k + 1); vpv[0].resize(n); for (size_t i = 0; i < n; ++i) vpv[0][i] = {i, v[i]}; for (unsigned k = 1; k < vpv.size(); ++k) { size_t p2k1 = (size_t(1) << (k - 1)), p2k = 2 * p2k1; vpv[k].resize(n + 1 - p2k); for (size_t i = 0; i < n + 1 - p2k; ++i) vpv[k][i] = Merge(vpv[k - 1][i], vpv[k - 1][i + p2k1]); } } TPositionValue Minimum(size_t b, size_t e) const { assert(b < e); unsigned k = numeric::ULog2(uint64_t(e - b)); return Merge(vpv[k][b], vpv[k][e - (size_t(1) << k)]); } }; } // namespace rmq } // namespace nvector
[ "alexeypoyarkov@gmail.com" ]
alexeypoyarkov@gmail.com
d907e7f9d1bca6015a076f6d2cc7df69c15664e2
888ff1ff4f76c61e0a2cff281f3fae2c9a4dcb7b
/C/C200/C230/C236/2.cpp
f50b68edeebfc4108b566785626f0aa1fd60f34e
[]
no_license
sanjusss/leetcode-cpp
59e243fa41cd5a1e59fc1f0c6ec13161fae9a85b
8bdf45a26f343b221caaf5be9d052c9819f29258
refs/heads/master
2023-08-18T01:02:47.798498
2023-08-15T00:30:51
2023-08-15T00:30:51
179,413,256
0
0
null
null
null
null
UTF-8
C++
false
false
556
cpp
/* * @Author: sanjusss * @Date: 2021-04-11 10:33:44 * @LastEditors: sanjusss * @LastEditTime: 2021-04-11 10:38:31 * @FilePath: \C\C200\C230\C236\2.cpp */ #include "leetcode.h" class Solution { public: int findTheWinner(int n, int k) { queue<int> q; for (int i = 1; i <= n; ++i) { q.push(i); } while (q.size() != 1) { for (int i = 1; i < k; ++i) { q.push(q.front()); q.pop(); } q.pop(); } return q.front(); } };
[ "sanjusss@qq.com" ]
sanjusss@qq.com
47ab4675b1423e9f90e6d25c8ab637b523aeacd6
9579b8861ff1c0455e885fcea144ffe8da5c86ed
/Phys350/GravSimVer2/GravSim/GravSim.cpp
d36d04923e8c6b793e0fbdf3ca0d4a269c1f8d00
[]
no_license
SidBala/NBodySimulator
dcf90191166bfdaf1c578a68f3444c2608402fbe
b126c2116858d7612d8538e4e25c90f3a925ec28
refs/heads/master
2016-08-05T03:06:17.311237
2015-03-15T17:08:48
2015-03-15T17:08:48
32,271,868
0
0
null
null
null
null
UTF-8
C++
false
false
2,799
cpp
// GravSim.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "GravSim.h" #include "GravSimDlg.h" #include <fcntl.h> #include <io.h> #ifdef _DEBUG #define new DEBUG_NEW #endif // CGravSimApp BEGIN_MESSAGE_MAP(CGravSimApp, CWinApp) ON_COMMAND(ID_HELP, &CWinApp::OnHelp) END_MESSAGE_MAP() // CGravSimApp construction CGravSimApp::CGravSimApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CGravSimApp object CGravSimApp theApp; // CGravSimApp initialization BOOL CGravSimApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); int hConHandle; long lStdHandle; CONSOLE_SCREEN_BUFFER_INFO coninfo; FILE *fp; // allocate a console for this app AllocConsole(); // set the screen buffer to be big enough to let us scroll text GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo); coninfo.dwSize.Y = 500; SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize); // redirect unbuffered STDOUT to the console lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "w" ); *stdout = *fp; setvbuf( stdout, NULL, _IONBF, 0 ); printf("Console Started"); AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("Local AppWizard-Generated Applications")); CGravSimDlg dlg; m_pMainWnd = &dlg; INT_PTR nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }
[ "sidbala@users.noreply.github.com" ]
sidbala@users.noreply.github.com
a097941cbc75eb376e71c02e1f7a831826426619
7b566c3c7324d87db9b5af6e935ba2d89bb4a826
/TriArray.h
ef5688c3c18f5776e2c22e5c0d2c6fb4f3d94589
[]
no_license
BlackEyedGhost/Travelling-Salesman
aec674d848581ed51f9a1097575b366ecaf12008
4c94f86f00a5f79a9e197d3a43be3c941379e5bc
refs/heads/master
2023-02-03T16:45:05.695620
2020-12-24T07:59:36
2020-12-24T07:59:36
324,052,827
2
0
null
null
null
null
UTF-8
C++
false
false
396
h
template <typename T> class TriArray { public: int length=0; int dim=0; T *items; TriArray(int i){ dim = i; length = i*(i-1)/2; items = new T[length]; } ~TriArray(){ delete items; } size_t index(size_t i, size_t j){ if(i>j){ size_t temp = i; i = j; j = temp; } return i*dim+j-(i+1)*(i+2)/2; } T& operator()(size_t i, size_t j){ return items[index(i,j)]; } };
[ "BlackEyedGhost@yahoo.com" ]
BlackEyedGhost@yahoo.com
70dd8025c013a601c5c6188e7c7d475c8311e422
576284f169ac0c803e76d3ef4b556cdeb91fa41b
/LeetCode/TwoSum.cpp
2c0e53cc331b8e3d6a8e05ab82752cfe9c8e2904
[]
no_license
ljw7630/LeetCode
1d97feb264a2ef1aa30d40204f0c1bb8ce544d3c
53e1de17f9642a120a884ded92a4c9dc59fdb392
refs/heads/master
2021-01-10T08:15:59.692779
2013-03-01T16:57:17
2013-03-01T16:57:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
840
cpp
#include <iostream> #include <vector> #include <algorithm> #include <set> #include <string> #include <map> #include <stack> #include "AlgorithmImpl.h" using namespace std; using namespace AlgorithmImpl; class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> result; for(int i=0;i<numbers.size();++i){ for(int j=0;j<i;++j){ if(numbers[j] + numbers[i] == 0){ result.push_back(j+1); result.push_back(i+1); return result; } } numbers[i] = numbers[i] - target; } return result; } }; int main(){ //int a[] = {150,24,79,50,88,345,3}; //vector<int> number = AlgorithmImpl::Utility::createVector(a,7); //vector<int> result = Solution().twoSum(number, 200); //AlgorithmImpl::Utility::printVector(result); cout << abs(INT_MIN) << endl; getchar(); return 0; }
[ "ljw7630@hotmail.com" ]
ljw7630@hotmail.com
6aaf8dc18ecb64bfc7ec0ace80419b98834eb11c
4fabc700eb31fe147ee0c1ca138411de3f71288c
/src/Stringifiable.cpp
131348e3821a7f670cde1605bd449223abdff12a
[ "Apache-2.0" ]
permissive
CachedNerds/Conversion
2ebbf5804f69dfd5749af4c4e4d92ab6aceace30
be4369348e87cbb27c6f19bd5bde9b1df76b17b3
refs/heads/master
2021-05-01T22:11:28.678566
2018-02-10T07:12:39
2018-02-10T07:12:39
120,988,894
0
0
null
null
null
null
UTF-8
C++
false
false
171
cpp
#include "Stringifiable.h" namespace toolbox::conversion { Stringifiable::operator std::string (void) const { return toString(); } } // namespace toolbox::conversion
[ "danieljpeck93@gmail.com" ]
danieljpeck93@gmail.com