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
9633a2dc30f1785905ea01c23d726c5c2e2dc9ce
27366788d85bcf10c1127a420ad690f202710ee0
/02_CoreFunctionality/03_MaskOperations/03_MaskOperations.cpp
5918e35c2a460a6be2896ce8eb1b2ff8553676f6
[]
no_license
paulobruno/LearningOpenCV
cf14c0c83bbc0bd3457068be028a2fcbbff1c8c1
3cddacfa1ba1924dc7d21613c920fb472fc2e813
refs/heads/master
2021-05-02T05:27:21.112915
2018-07-17T19:02:39
2018-07-17T19:02:39
120,920,751
0
0
null
null
null
null
UTF-8
C++
false
false
2,299
cpp
#include <opencv2/opencv.hpp> void sharpen(const cv::Mat& myImage, cv::Mat& result) { CV_Assert(CV_8U == myImage.depth()); const int nChannels = myImage.channels(); result.create(myImage.size(), myImage.type()); for (int j = 1; j < myImage.rows-1; ++j) { const uchar* previous = myImage.ptr<uchar>(j-1); const uchar* current = myImage.ptr<uchar>(j ); const uchar* next = myImage.ptr<uchar>(j+1); uchar* output = result.ptr<uchar>(j); for (int i = nChannels; i < nChannels*(myImage.cols-1); ++i) { *output++ = cv::saturate_cast<uchar>(5*current[i] - current[i-nChannels] - current[i+nChannels] - previous[i] - next[i]); } } result.row(0).setTo(cv::Scalar(0)); result.row(result.rows-1).setTo(cv::Scalar(0)); result.col(0).setTo(cv::Scalar(0)); result.col(result.cols-1).setTo(cv::Scalar(0)); } int main (int argc, char* argv[]) { cv::String filename("aerial-clouds-dawn.jpg"); cv::Mat src = cv::imread(filename, cv::IMREAD_COLOR); if (src.empty()) { std::cerr << "Can't open image [" << filename << "]" << std::endl; return -1; } cv::Mat dst; double t = (double) cv::getTickCount(); sharpen(src, dst); t = 1000.0 * ((double) cv::getTickCount() - t) / cv::getTickFrequency(); std::cout << "C version:" << std::endl << "\tTimes passed in milisseconds: " << t << " ms" << std::endl; cv::Mat kernel = (cv::Mat_<char>(3,3) << 0, -1, 0, -1, 5, -1, 0, -1, 0); t = (double) cv::getTickCount(); filter2D(src, dst, src.depth(), kernel); t = 1000.0 * ((double) cv::getTickCount() - t) / cv::getTickFrequency(); std::cout << "opencv filter 2D version:" << std::endl << "\tTimes passed in milisseconds: " << t << " ms" << std::endl; namedWindow(filename, cv::WINDOW_AUTOSIZE); namedWindow("Filtered", cv::WINDOW_AUTOSIZE); imshow(filename, src); imshow("Filtered", dst); cv::waitKey(0); return 0; }
[ "paulobruno@alu.ufc.br" ]
paulobruno@alu.ufc.br
63261a4fdcb411509e87d9b85c682dbc9b8226f9
54b37241d83de4de308f335d412e0ce9df392a78
/src-char-ox-step-0-6/CCA/Components/Solvers/MatrixUtil.h
e955e133e3ffec55c7d390d2bafcb1c8de531938
[ "MIT" ]
permissive
jholmen/Uintah-sc19
dac772fbbc7ab9b8b2bf1be02a08c9e2d8166d24
fae5ebe7821ec23709e97736f1378aa4aa01e645
refs/heads/master
2023-04-15T21:18:28.362715
2021-04-20T13:54:30
2021-04-20T13:54:30
359,625,839
2
0
null
null
null
null
UTF-8
C++
false
false
2,913
h
/* * The MIT License * * Copyright (c) 1997-2018 The University of Utah * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #ifndef Packages_Uintah_CCA_Components_Solvers_MatrixUtil_h #define Packages_Uintah_CCA_Components_Solvers_MatrixUtil_h #include <Core/Grid/Variables/Stencil7.h> #include <Core/Grid/Variables/Stencil4.h> #include <Core/Grid/Variables/CCVariable.h> #include <Core/Grid/Variables/NCVariable.h> #include <Core/Grid/Variables/SFCXVariable.h> #include <Core/Grid/Variables/SFCYVariable.h> #include <Core/Grid/Variables/SFCZVariable.h> namespace Uintah { class SFCXTypes { public: typedef constSFCXVariable<Stencil7> matrix_type; typedef constSFCXVariable<Stencil4> symmetric_matrix_type; typedef constSFCXVariable<double> const_type; typedef SFCXVariable<double> sol_type; }; class SFCYTypes { public: typedef constSFCYVariable<Stencil7> matrix_type; typedef constSFCYVariable<Stencil4> symmetric_matrix_type; typedef constSFCYVariable<double> const_type; typedef SFCYVariable<double> sol_type; }; class SFCZTypes { public: typedef constSFCZVariable<Stencil7> matrix_type; typedef constSFCZVariable<Stencil4> symmetric_matrix_type; typedef constSFCZVariable<double> const_type; typedef SFCZVariable<double> sol_type; }; class CCTypes { public: typedef constCCVariable<Stencil7> matrix_type; typedef constCCVariable<Stencil4> symmetric_matrix_type; typedef constCCVariable<double> const_type; typedef CCVariable<double> sol_type; }; class NCTypes { public: typedef constNCVariable<Stencil7> matrix_type; typedef constNCVariable<Stencil4> symmetric_matrix_type; typedef constNCVariable<double> const_type; typedef NCVariable<double> sol_type; }; } #endif // Packages_Uintah_CCA_Components_Solvers_MatrixUtil_h
[ "jholmen@sci.utah.edu" ]
jholmen@sci.utah.edu
9bc80453285d5ba6ba88ce40780ee5f7d44bb3eb
9f22a7234bfcb6608d4e4e7ea41164eaa75371ca
/Games Lab/Source/PCGTesting/PCGTestingGameModeBase.h
70ef654eea1b87b53861840ecb2fc0ec0b6fa704
[]
no_license
haigleonard/C-
bb177701b1582d5c41230724d56a28ac6ef9ca3a
1d98b45567fd725bfd2966164e2b84f36fec808a
refs/heads/master
2020-03-30T16:52:07.709270
2018-11-19T18:19:21
2018-11-19T18:19:21
151,431,164
0
0
null
null
null
null
UTF-8
C++
false
false
322
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/GameModeBase.h" #include "PCGTestingGameModeBase.generated.h" /** * */ UCLASS() class PCGTESTING_API APCGTestingGameModeBase : public AGameModeBase { GENERATED_BODY() };
[ "42865623+haigleonard@users.noreply.github.com" ]
42865623+haigleonard@users.noreply.github.com
cd01269ad68543ff9ff77fb3fa71960916d78ba6
35490e86c95e6a8389bb02407a3d3c19923a0c62
/lab03/main.cpp
a284d69cf0dfa95f353c28944793fabac9db38c1
[]
no_license
nelli-rud/k60gpu
6e80a61bb3f37cbf6e94b159d83136cbc6e58774
33aafa817d75aa206e87244085e4444b342096e5
refs/heads/main
2023-05-31T14:52:15.615561
2021-07-14T11:14:33
2021-07-14T11:14:33
380,240,330
0
0
null
null
null
null
UTF-8
C++
false
false
661
cpp
#include <mpi.h> #include <iostream> #include "utils.h" #include "cpuThreads.h" #include "gpu.h" using namespace std; int main (int argc, char* argv[]) { int rank, size, provided; mpi_init(argc, argv, MPI_THREAD_FUNNELED, provided, rank, size); MPI_Barrier(MPI_COMM_WORLD); double t1 = MPI_Wtime(); testThreads(rank); double t2 = MPI_Wtime(); double t = t1-t2; printf("Rank %d: Time of testThreads: %lf sec\n", rank, t); printGpuParameters("Node " + std::to_string(rank)); int res_gpu = gpu(5, 15); std::cerr<<"res_gpu = "<<res_gpu<<" (rank = "<<rank<<")"<<std::endl; MPI_Finalize(); return 0; }
[ "nelli-rud@yandex.ru" ]
nelli-rud@yandex.ru
748328ff07ab3f6b5a04780309b77e67e3a53c04
38b09cf15163fa77a7d70f0ac051a8286d51b921
/rdkafkacpp/test/TestConsumer.cpp
dc743f001c547217c5d67aeed74c8ea7a53d1831
[]
no_license
codingsf/zylib
688f1e01b44b0b516abad242285a1e389206d16e
d409675f0a5d9b6aab044231ad902fe8758e3b08
refs/heads/master
2020-03-22T03:34:20.305758
2018-06-22T09:26:52
2018-06-22T09:26:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,509
cpp
#include <iostream> #include <string> #include <cstdlib> #include <cstdio> #include <csignal> #include <cstring> #include "rdkafkacpp.h" static bool run = true; static bool exit_eof = false; static int eof_cnt = 0; static int partition_cnt = 0; static int verbosity = 1; static long msg_cnt = 0; static int64_t msg_bytes = 0; static void sigterm(int sig) { run = false; } class ExampleRebalanceCb : public RdKafka::RebalanceCb { private: static void part_list_print(const std::vector<RdKafka::TopicPartition*>&partitions) { for (unsigned int i = 0; i < partitions.size(); i++) std::cerr << partitions[i]->topic() << "[" << partitions[i]->partition() << "], "; std::cerr << "\n"; } public: void rebalance_cb(RdKafka::KafkaConsumer *consumer, RdKafka::ErrorCode err, std::vector<RdKafka::TopicPartition*> &partitions) { std::cerr << "RebalanceCb: " << RdKafka::err2str(err) << ": "; part_list_print(partitions); if (err == RdKafka::ERR__ASSIGN_PARTITIONS) { consumer->assign(partitions); partition_cnt = (int)partitions.size(); } else { consumer->unassign(); partition_cnt = 0; } eof_cnt = 0; } }; void msg_consume(RdKafka::Message* message, void* opaque) { switch (message->err()) { case RdKafka::ERR__TIMED_OUT: break; case RdKafka::ERR_NO_ERROR: /* Real message */ msg_cnt++; msg_bytes += message->len(); if (verbosity >= 3) std::cerr << "Read msg at offset " << message->offset() << std::endl; RdKafka::MessageTimestamp ts; ts = message->timestamp(); if (verbosity >= 2 && ts.type != RdKafka::MessageTimestamp::MSG_TIMESTAMP_NOT_AVAILABLE) { std::string tsname = "?"; if (ts.type == RdKafka::MessageTimestamp::MSG_TIMESTAMP_CREATE_TIME) tsname = "create time"; else if (ts.type == RdKafka::MessageTimestamp::MSG_TIMESTAMP_LOG_APPEND_TIME) tsname = "log append time"; std::cout << "Timestamp: " << tsname << " " << ts.timestamp << std::endl; } if (verbosity >= 2 && message->key()) { std::cout << "Key: " << *message->key() << std::endl; } if (verbosity >= 1) { //std::cout << (const char*)message->payload() << " offset " << message->offset() << "\n"; /* printf("%.*s\n", static_cast<int>(message->len()), static_cast<const char *>(message->payload())); */ } break; case RdKafka::ERR__PARTITION_EOF: /* Last message */ if (exit_eof && ++eof_cnt == partition_cnt) { std::cerr << "%% EOF reached for all " << partition_cnt << " partition(s)" << std::endl; run = false; } break; case RdKafka::ERR__UNKNOWN_TOPIC: case RdKafka::ERR__UNKNOWN_PARTITION: std::cerr << "Consume failed: " << message->errstr() << std::endl; run = false; break; default: /* Errors */ std::cerr << "Consume failed: " << message->errstr() << std::endl; run = false; } } class ExampleConsumeCb : public RdKafka::ConsumeCb { public: void consume_cb(RdKafka::Message &msg, void *opaque) { std::cout << "consumer cb\n"; msg_consume(&msg, opaque); } }; int main() { std::string brokers = "127.0.0.1:9092"; std::string errstr; std::string topic_str; std::string mode; std::string debug; /* * Create configuration objects */ RdKafka::Conf *conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL); RdKafka::Conf *tconf = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC); conf->set("group.id", "xxx", errstr); ExampleRebalanceCb ex_rebalance_cb; conf->set("rebalance_cb", &ex_rebalance_cb, errstr); std::vector<std::string> topics = { "tp.test" }; /* * Set configuration properties */ conf->set("metadata.broker.list", brokers, errstr); //conf->set("enable.auto.commit", "true", errstr); //tconf->set("auto.offset.reset", "end", errstr); std::cout << "tconf error : " << errstr << "\n"; ExampleConsumeCb ex_consume_cb; conf->set("consume_cb", &ex_consume_cb, errstr); //ExampleEventCb ex_event_cb; //conf->set("event_cb", &ex_event_cb, errstr); conf->set("default_topic_conf", tconf, errstr); delete tconf; signal(SIGINT, sigterm); signal(SIGTERM, sigterm); /* * Create consumer using accumulated global configuration. */ RdKafka::KafkaConsumer *consumer = RdKafka::KafkaConsumer::create(conf, errstr); if (!consumer) { std::cerr << "Failed to create consumer: " << errstr << std::endl; exit(1); } delete conf; std::cout << "% Created consumer " << consumer->name() << std::endl; auto* p = RdKafka::TopicPartition::create("tp.test2", 0); //RdKafka::Topic::PARTITION_UA //, RdKafka::Topic::OFFSET_END); auto err3 = consumer->assign({ p }); if (err3) { std::cout << "consumer assign error " << RdKafka::err2str(err3) << "\n"; } /* consumer->poll(100); p->set_offset(RdKafka::Topic::OFFSET_END); RdKafka::ErrorCode err2 = consumer->seek(*p, 5000); if (err2) { std::cout << "seek error " << RdKafka::err2str(err2) << "\n"; } delete p; */ /* RdKafka::ErrorCode err = consumer->subscribe(topics); if (err) { std::cerr << "Failed to subscribe to " << topics.size() << " topics: " << RdKafka::err2str(err) << std::endl; exit(1); } */ std::cout << "start consumer \n"; /* * Consume messages */ while (run) { RdKafka::Message *msg = consumer->consume(1000); msg_consume(msg, NULL); delete msg; } /* * Stop consumer */ consumer->close(); delete consumer; std::cerr << "% Consumed " << msg_cnt << " messages (" << msg_bytes << " bytes)" << std::endl; /* * Wait for RdKafka to decommission. * This is not strictly needed (with check outq_len() above), but * allows RdKafka to clean up all its resources before the application * exits so that memory profilers such as valgrind wont complain about * memory leaks. */ RdKafka::wait_destroyed(5000); return 0; }
[ "guangyuanchen001@163.com" ]
guangyuanchen001@163.com
b490fed905926e2d8e06a3efcdbe94370e2bd3c9
b87cc33dad2d25a774f081af72e0a8de6efe1cba
/P2/tmpl_2018-01_CP/RTChessBoardTexture.h
98dd1c8f17353e9bfa0f1aa22c994c41fe4e43f3
[]
no_license
pasu/AG_Assignment
2c3bd03a13703f7f7e561b907bcd3e83412742f5
d35f4552b529ba5b4a23bc74210cfcba70096b66
refs/heads/master
2021-10-11T17:55:54.786910
2019-01-28T17:59:07
2019-01-28T17:59:07
157,724,885
0
0
null
null
null
null
UTF-8
C++
false
false
419
h
#pragma once #include "RTTexture.h" class RTChessBoardTexture : public RTTexture { public: RTChessBoardTexture( const vec3 &color1, const vec3 &color2 ); ~RTChessBoardTexture(); const vec3 getTexel( float s, float t, float z, const vec2 &scale = vec2( 1, 1 ) ) const; private: vec3 color1; vec3 color2; inline float modulo( const float x ) const { return x - std::floor( x ); } };
[ "bjfubjfu@gmail.com" ]
bjfubjfu@gmail.com
37aa30ba9a0febec90a5fde7f9fbcdac264fdd67
94dcc118f9492896d6781e5a3f59867eddfbc78a
/llvm/lib/CodeGen/MachineFunction.cpp
7e9a25a5583b4e49aaacb63f12461092073a5275
[ "NCSA", "Apache-2.0" ]
permissive
vusec/safeinit
43fd500b5a832cce2bd87696988b64a718a5d764
8425bc49497684fe16e0063190dec8c3c58dc81a
refs/heads/master
2021-07-07T11:46:25.138899
2021-05-05T10:40:52
2021-05-05T10:40:52
76,794,423
22
5
null
null
null
null
UTF-8
C++
false
false
37,062
cpp
//===-- MachineFunction.cpp -----------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Collect native machine code information for a function. This allows // target-specific information about the generated code to be stored with each // function. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/MachineFunction.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/Analysis/ConstantFolding.h" #include "llvm/Analysis/EHPersonalities.h" #include "llvm/CodeGen/MachineConstantPool.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunctionInitializer.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineJumpTableInfo.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/PseudoSourceValue.h" #include "llvm/CodeGen/WinEHFuncInfo.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DebugInfo.h" #include "llvm/IR/Function.h" #include "llvm/IR/Module.h" #include "llvm/IR/ModuleSlotTracker.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/Support/Debug.h" #include "llvm/Support/GraphWriter.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetFrameLowering.h" #include "llvm/Target/TargetLowering.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetSubtargetInfo.h" using namespace llvm; #define DEBUG_TYPE "codegen" static cl::opt<unsigned> AlignAllFunctions("align-all-functions", cl::desc("Force the alignment of all functions."), cl::init(0), cl::Hidden); void MachineFunctionInitializer::anchor() {} void MachineFunctionProperties::print(raw_ostream &ROS, bool OnlySet) const { // Leave this function even in NDEBUG as an out-of-line anchor. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) for (BitVector::size_type i = 0; i < Properties.size(); ++i) { bool HasProperty = Properties[i]; if (OnlySet && !HasProperty) continue; switch(static_cast<Property>(i)) { case Property::IsSSA: ROS << (HasProperty ? "SSA, " : "Post SSA, "); break; case Property::TracksLiveness: ROS << (HasProperty ? "" : "not ") << "tracking liveness, "; break; case Property::AllVRegsAllocated: ROS << (HasProperty ? "AllVRegsAllocated" : "HasVRegs"); break; default: break; } } #endif } //===----------------------------------------------------------------------===// // MachineFunction implementation //===----------------------------------------------------------------------===// // Out-of-line virtual method. MachineFunctionInfo::~MachineFunctionInfo() {} void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) { MBB->getParent()->DeleteMachineBasicBlock(MBB); } static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI, const Function *Fn) { if (Fn->hasFnAttribute(Attribute::StackAlignment)) return Fn->getFnStackAlignment(); return STI->getFrameLowering()->getStackAlignment(); } MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM, unsigned FunctionNum, MachineModuleInfo &mmi) : Fn(F), Target(TM), STI(TM.getSubtargetImpl(*F)), Ctx(mmi.getContext()), MMI(mmi) { // Assume the function starts in SSA form with correct liveness. Properties.set(MachineFunctionProperties::Property::IsSSA); Properties.set(MachineFunctionProperties::Property::TracksLiveness); if (STI->getRegisterInfo()) RegInfo = new (Allocator) MachineRegisterInfo(this); else RegInfo = nullptr; MFInfo = nullptr; // We can realign the stack if the target supports it and the user hasn't // explicitly asked us not to. bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() && !F->hasFnAttribute("no-realign-stack"); FrameInfo = new (Allocator) MachineFrameInfo( getFnStackAlignment(STI, Fn), /*StackRealignable=*/CanRealignSP, /*ForceRealign=*/CanRealignSP && F->hasFnAttribute(Attribute::StackAlignment)); if (Fn->hasFnAttribute(Attribute::StackAlignment)) FrameInfo->ensureMaxAlignment(Fn->getFnStackAlignment()); ConstantPool = new (Allocator) MachineConstantPool(getDataLayout()); Alignment = STI->getTargetLowering()->getMinFunctionAlignment(); // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn. // FIXME: Use Function::optForSize(). if (!Fn->hasFnAttribute(Attribute::OptimizeForSize)) Alignment = std::max(Alignment, STI->getTargetLowering()->getPrefFunctionAlignment()); if (AlignAllFunctions) Alignment = AlignAllFunctions; FunctionNumber = FunctionNum; JumpTableInfo = nullptr; if (isFuncletEHPersonality(classifyEHPersonality( F->hasPersonalityFn() ? F->getPersonalityFn() : nullptr))) { WinEHInfo = new (Allocator) WinEHFuncInfo(); } assert(TM.isCompatibleDataLayout(getDataLayout()) && "Can't create a MachineFunction using a Module with a " "Target-incompatible DataLayout attached\n"); PSVManager = llvm::make_unique<PseudoSourceValueManager>(); } MachineFunction::~MachineFunction() { // Don't call destructors on MachineInstr and MachineOperand. All of their // memory comes from the BumpPtrAllocator which is about to be purged. // // Do call MachineBasicBlock destructors, it contains std::vectors. for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I)) I->Insts.clearAndLeakNodesUnsafely(); InstructionRecycler.clear(Allocator); OperandRecycler.clear(Allocator); BasicBlockRecycler.clear(Allocator); if (RegInfo) { RegInfo->~MachineRegisterInfo(); Allocator.Deallocate(RegInfo); } if (MFInfo) { MFInfo->~MachineFunctionInfo(); Allocator.Deallocate(MFInfo); } FrameInfo->~MachineFrameInfo(); Allocator.Deallocate(FrameInfo); ConstantPool->~MachineConstantPool(); Allocator.Deallocate(ConstantPool); if (JumpTableInfo) { JumpTableInfo->~MachineJumpTableInfo(); Allocator.Deallocate(JumpTableInfo); } if (WinEHInfo) { WinEHInfo->~WinEHFuncInfo(); Allocator.Deallocate(WinEHInfo); } } const DataLayout &MachineFunction::getDataLayout() const { return Fn->getParent()->getDataLayout(); } /// Get the JumpTableInfo for this function. /// If it does not already exist, allocate one. MachineJumpTableInfo *MachineFunction:: getOrCreateJumpTableInfo(unsigned EntryKind) { if (JumpTableInfo) return JumpTableInfo; JumpTableInfo = new (Allocator) MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind); return JumpTableInfo; } /// Should we be emitting segmented stack stuff for the function bool MachineFunction::shouldSplitStack() const { return getFunction()->hasFnAttribute("split-stack"); } /// This discards all of the MachineBasicBlock numbers and recomputes them. /// This guarantees that the MBB numbers are sequential, dense, and match the /// ordering of the blocks within the function. If a specific MachineBasicBlock /// is specified, only that block and those after it are renumbered. void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) { if (empty()) { MBBNumbering.clear(); return; } MachineFunction::iterator MBBI, E = end(); if (MBB == nullptr) MBBI = begin(); else MBBI = MBB->getIterator(); // Figure out the block number this should have. unsigned BlockNo = 0; if (MBBI != begin()) BlockNo = std::prev(MBBI)->getNumber() + 1; for (; MBBI != E; ++MBBI, ++BlockNo) { if (MBBI->getNumber() != (int)BlockNo) { // Remove use of the old number. if (MBBI->getNumber() != -1) { assert(MBBNumbering[MBBI->getNumber()] == &*MBBI && "MBB number mismatch!"); MBBNumbering[MBBI->getNumber()] = nullptr; } // If BlockNo is already taken, set that block's number to -1. if (MBBNumbering[BlockNo]) MBBNumbering[BlockNo]->setNumber(-1); MBBNumbering[BlockNo] = &*MBBI; MBBI->setNumber(BlockNo); } } // Okay, all the blocks are renumbered. If we have compactified the block // numbering, shrink MBBNumbering now. assert(BlockNo <= MBBNumbering.size() && "Mismatch!"); MBBNumbering.resize(BlockNo); } /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'. MachineInstr * MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID, DebugLoc DL, bool NoImp) { return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) MachineInstr(*this, MCID, DL, NoImp); } /// Create a new MachineInstr which is a copy of the 'Orig' instruction, /// identical in all ways except the instruction has no parent, prev, or next. MachineInstr * MachineFunction::CloneMachineInstr(const MachineInstr *Orig) { return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) MachineInstr(*this, *Orig); } /// Delete the given MachineInstr. /// /// This function also serves as the MachineInstr destructor - the real /// ~MachineInstr() destructor must be empty. void MachineFunction::DeleteMachineInstr(MachineInstr *MI) { // Strip it for parts. The operand array and the MI object itself are // independently recyclable. if (MI->Operands) deallocateOperandArray(MI->CapOperands, MI->Operands); // Don't call ~MachineInstr() which must be trivial anyway because // ~MachineFunction drops whole lists of MachineInstrs wihout calling their // destructors. InstructionRecycler.Deallocate(Allocator, MI); } /// Allocate a new MachineBasicBlock. Use this instead of /// `new MachineBasicBlock'. MachineBasicBlock * MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) { return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator)) MachineBasicBlock(*this, bb); } /// Delete the given MachineBasicBlock. void MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) { assert(MBB->getParent() == this && "MBB parent mismatch!"); MBB->~MachineBasicBlock(); BasicBlockRecycler.Deallocate(Allocator, MBB); } MachineMemOperand * MachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f, uint64_t s, unsigned base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges) { return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges); } MachineMemOperand * MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, int64_t Offset, uint64_t Size) { if (MMO->getValue()) return new (Allocator) MachineMemOperand(MachinePointerInfo(MMO->getValue(), MMO->getOffset()+Offset), MMO->getFlags(), Size, MMO->getBaseAlignment()); return new (Allocator) MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset()+Offset), MMO->getFlags(), Size, MMO->getBaseAlignment()); } MachineInstr::mmo_iterator MachineFunction::allocateMemRefsArray(unsigned long Num) { return Allocator.Allocate<MachineMemOperand *>(Num); } std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator> MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin, MachineInstr::mmo_iterator End) { // Count the number of load mem refs. unsigned Num = 0; for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) if ((*I)->isLoad()) ++Num; // Allocate a new array and populate it with the load information. MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num); unsigned Index = 0; for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) { if ((*I)->isLoad()) { if (!(*I)->isStore()) // Reuse the MMO. Result[Index] = *I; else { // Clone the MMO and unset the store flag. MachineMemOperand *JustLoad = getMachineMemOperand((*I)->getPointerInfo(), (*I)->getFlags() & ~MachineMemOperand::MOStore, (*I)->getSize(), (*I)->getBaseAlignment(), (*I)->getAAInfo()); Result[Index] = JustLoad; } ++Index; } } return std::make_pair(Result, Result + Num); } std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator> MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin, MachineInstr::mmo_iterator End) { // Count the number of load mem refs. unsigned Num = 0; for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) if ((*I)->isStore()) ++Num; // Allocate a new array and populate it with the store information. MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num); unsigned Index = 0; for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) { if ((*I)->isStore()) { if (!(*I)->isLoad()) // Reuse the MMO. Result[Index] = *I; else { // Clone the MMO and unset the load flag. MachineMemOperand *JustStore = getMachineMemOperand((*I)->getPointerInfo(), (*I)->getFlags() & ~MachineMemOperand::MOLoad, (*I)->getSize(), (*I)->getBaseAlignment(), (*I)->getAAInfo()); Result[Index] = JustStore; } ++Index; } } return std::make_pair(Result, Result + Num); } const char *MachineFunction::createExternalSymbolName(StringRef Name) { char *Dest = Allocator.Allocate<char>(Name.size() + 1); std::copy(Name.begin(), Name.end(), Dest); Dest[Name.size()] = 0; return Dest; } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD void MachineFunction::dump() const { print(dbgs()); } #endif StringRef MachineFunction::getName() const { assert(getFunction() && "No function!"); return getFunction()->getName(); } void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const { OS << "# Machine code for function " << getName() << ": "; OS << "Properties: <"; getProperties().print(OS); OS << ">\n"; // Print Frame Information FrameInfo->print(*this, OS); // Print JumpTable Information if (JumpTableInfo) JumpTableInfo->print(OS); // Print Constant Pool ConstantPool->print(OS); const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo(); if (RegInfo && !RegInfo->livein_empty()) { OS << "Function Live Ins: "; for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) { OS << PrintReg(I->first, TRI); if (I->second) OS << " in " << PrintReg(I->second, TRI); if (std::next(I) != E) OS << ", "; } OS << '\n'; } ModuleSlotTracker MST(getFunction()->getParent()); MST.incorporateFunction(*getFunction()); for (const auto &BB : *this) { OS << '\n'; BB.print(OS, MST, Indexes); } OS << "\n# End machine code for function " << getName() << ".\n\n"; } namespace llvm { template<> struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits { DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} static std::string getGraphName(const MachineFunction *F) { return ("CFG for '" + F->getName() + "' function").str(); } std::string getNodeLabel(const MachineBasicBlock *Node, const MachineFunction *Graph) { std::string OutStr; { raw_string_ostream OSS(OutStr); if (isSimple()) { OSS << "BB#" << Node->getNumber(); if (const BasicBlock *BB = Node->getBasicBlock()) OSS << ": " << BB->getName(); } else Node->print(OSS); } if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); // Process string output to make it nicer... for (unsigned i = 0; i != OutStr.length(); ++i) if (OutStr[i] == '\n') { // Left justify OutStr[i] = '\\'; OutStr.insert(OutStr.begin()+i+1, 'l'); } return OutStr; } }; } void MachineFunction::viewCFG() const { #ifndef NDEBUG ViewGraph(this, "mf" + getName()); #else errs() << "MachineFunction::viewCFG is only available in debug builds on " << "systems with Graphviz or gv!\n"; #endif // NDEBUG } void MachineFunction::viewCFGOnly() const { #ifndef NDEBUG ViewGraph(this, "mf" + getName(), true); #else errs() << "MachineFunction::viewCFGOnly is only available in debug builds on " << "systems with Graphviz or gv!\n"; #endif // NDEBUG } /// Add the specified physical register as a live-in value and /// create a corresponding virtual register for it. unsigned MachineFunction::addLiveIn(unsigned PReg, const TargetRegisterClass *RC) { MachineRegisterInfo &MRI = getRegInfo(); unsigned VReg = MRI.getLiveInVirtReg(PReg); if (VReg) { const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg); (void)VRegRC; // A physical register can be added several times. // Between two calls, the register class of the related virtual register // may have been constrained to match some operation constraints. // In that case, check that the current register class includes the // physical register and is a sub class of the specified RC. assert((VRegRC == RC || (VRegRC->contains(PReg) && RC->hasSubClassEq(VRegRC))) && "Register class mismatch!"); return VReg; } VReg = MRI.createVirtualRegister(RC); MRI.addLiveIn(PReg, VReg); return VReg; } /// Return the MCSymbol for the specified non-empty jump table. /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a /// normal 'L' label is returned. MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx, bool isLinkerPrivate) const { const DataLayout &DL = getDataLayout(); assert(JumpTableInfo && "No jump tables"); assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!"); const char *Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix() : DL.getPrivateGlobalPrefix(); SmallString<60> Name; raw_svector_ostream(Name) << Prefix << "JTI" << getFunctionNumber() << '_' << JTI; return Ctx.getOrCreateSymbol(Name); } /// Return a function-local symbol to represent the PIC base. MCSymbol *MachineFunction::getPICBaseSymbol() const { const DataLayout &DL = getDataLayout(); return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "$pb"); } //===----------------------------------------------------------------------===// // MachineFrameInfo implementation //===----------------------------------------------------------------------===// /// Make sure the function is at least Align bytes aligned. void MachineFrameInfo::ensureMaxAlignment(unsigned Align) { if (!StackRealignable) assert(Align <= StackAlignment && "For targets without stack realignment, Align is out of limit!"); if (MaxAlignment < Align) MaxAlignment = Align; } /// Clamp the alignment if requested and emit a warning. static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align, unsigned StackAlign) { if (!ShouldClamp || Align <= StackAlign) return Align; DEBUG(dbgs() << "Warning: requested alignment " << Align << " exceeds the stack alignment " << StackAlign << " when stack realignment is off" << '\n'); return StackAlign; } /// Create a new statically sized stack object, returning a nonnegative /// identifier to represent it. int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment, bool isSS, const AllocaInst *Alloca) { assert(Size != 0 && "Cannot allocate zero size stack objects!"); Alignment = clampStackAlignment(!StackRealignable, Alignment, StackAlignment); Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, Alloca, !isSS)); int Index = (int)Objects.size() - NumFixedObjects - 1; assert(Index >= 0 && "Bad frame index!"); ensureMaxAlignment(Alignment); return Index; } /// Create a new statically sized stack object that represents a spill slot, /// returning a nonnegative identifier to represent it. int MachineFrameInfo::CreateSpillStackObject(uint64_t Size, unsigned Alignment) { Alignment = clampStackAlignment(!StackRealignable, Alignment, StackAlignment); CreateStackObject(Size, Alignment, true); int Index = (int)Objects.size() - NumFixedObjects - 1; ensureMaxAlignment(Alignment); return Index; } /// Notify the MachineFrameInfo object that a variable sized object has been /// created. This must be created whenever a variable sized object is created, /// whether or not the index returned is actually used. int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment, const AllocaInst *Alloca) { HasVarSizedObjects = true; Alignment = clampStackAlignment(!StackRealignable, Alignment, StackAlignment); Objects.push_back(StackObject(0, Alignment, 0, false, false, Alloca, true)); ensureMaxAlignment(Alignment); return (int)Objects.size()-NumFixedObjects-1; } /// Create a new object at a fixed location on the stack. /// All fixed objects should be created before other objects are created for /// efficiency. By default, fixed objects are immutable. This returns an /// index with a negative value. int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset, bool Immutable, bool isAliased) { assert(Size != 0 && "Cannot allocate zero size fixed stack objects!"); // The alignment of the frame index can be determined from its offset from // the incoming frame position. If the frame object is at offset 32 and // the stack is guaranteed to be 16-byte aligned, then we know that the // object is 16-byte aligned. Note that unlike the non-fixed case, if the // stack needs realignment, we can't assume that the stack will in fact be // aligned. unsigned Align = MinAlign(SPOffset, ForcedRealign ? 1 : StackAlignment); Align = clampStackAlignment(!StackRealignable, Align, StackAlignment); Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable, /*isSS*/ false, /*Alloca*/ nullptr, isAliased)); return -++NumFixedObjects; } /// Create a spill slot at a fixed location on the stack. /// Returns an index with a negative value. int MachineFrameInfo::CreateFixedSpillStackObject(uint64_t Size, int64_t SPOffset) { unsigned Align = MinAlign(SPOffset, ForcedRealign ? 1 : StackAlignment); Align = clampStackAlignment(!StackRealignable, Align, StackAlignment); Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, /*Immutable*/ true, /*isSS*/ true, /*Alloca*/ nullptr, /*isAliased*/ false)); return -++NumFixedObjects; } BitVector MachineFrameInfo::getPristineRegs(const MachineFunction &MF) const { const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); BitVector BV(TRI->getNumRegs()); // Before CSI is calculated, no registers are considered pristine. They can be // freely used and PEI will make sure they are saved. if (!isCalleeSavedInfoValid()) return BV; for (const MCPhysReg *CSR = TRI->getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR) BV.set(*CSR); // Saved CSRs are not pristine. for (auto &I : getCalleeSavedInfo()) for (MCSubRegIterator S(I.getReg(), TRI, true); S.isValid(); ++S) BV.reset(*S); return BV; } unsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const { const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo(); unsigned MaxAlign = getMaxAlignment(); int Offset = 0; // This code is very, very similar to PEI::calculateFrameObjectOffsets(). // It really should be refactored to share code. Until then, changes // should keep in mind that there's tight coupling between the two. for (int i = getObjectIndexBegin(); i != 0; ++i) { int FixedOff = -getObjectOffset(i); if (FixedOff > Offset) Offset = FixedOff; } for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) { if (isDeadObjectIndex(i)) continue; Offset += getObjectSize(i); unsigned Align = getObjectAlignment(i); // Adjust to alignment boundary Offset = (Offset+Align-1)/Align*Align; MaxAlign = std::max(Align, MaxAlign); } if (adjustsStack() && TFI->hasReservedCallFrame(MF)) Offset += getMaxCallFrameSize(); // Round up the size to a multiple of the alignment. If the function has // any calls or alloca's, align to the target's StackAlignment value to // ensure that the callee's frame or the alloca data is suitably aligned; // otherwise, for leaf functions, align to the TransientStackAlignment // value. unsigned StackAlign; if (adjustsStack() || hasVarSizedObjects() || (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0)) StackAlign = TFI->getStackAlignment(); else StackAlign = TFI->getTransientStackAlignment(); // If the frame pointer is eliminated, all frame offsets will be relative to // SP not FP. Align to MaxAlign so this works. StackAlign = std::max(StackAlign, MaxAlign); unsigned AlignMask = StackAlign - 1; Offset = (Offset + AlignMask) & ~uint64_t(AlignMask); return (unsigned)Offset; } void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{ if (Objects.empty()) return; const TargetFrameLowering *FI = MF.getSubtarget().getFrameLowering(); int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0); OS << "Frame Objects:\n"; for (unsigned i = 0, e = Objects.size(); i != e; ++i) { const StackObject &SO = Objects[i]; OS << " fi#" << (int)(i-NumFixedObjects) << ": "; if (SO.Size == ~0ULL) { OS << "dead\n"; continue; } if (SO.Size == 0) OS << "variable sized"; else OS << "size=" << SO.Size; OS << ", align=" << SO.Alignment; if (i < NumFixedObjects) OS << ", fixed"; if (i < NumFixedObjects || SO.SPOffset != -1) { int64_t Off = SO.SPOffset - ValOffset; OS << ", at location [SP"; if (Off > 0) OS << "+" << Off; else if (Off < 0) OS << Off; OS << "]"; } OS << "\n"; } } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) void MachineFrameInfo::dump(const MachineFunction &MF) const { print(MF, dbgs()); } #endif //===----------------------------------------------------------------------===// // MachineJumpTableInfo implementation //===----------------------------------------------------------------------===// /// Return the size of each entry in the jump table. unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const { // The size of a jump table entry is 4 bytes unless the entry is just the // address of a block, in which case it is the pointer size. switch (getEntryKind()) { case MachineJumpTableInfo::EK_BlockAddress: return TD.getPointerSize(); case MachineJumpTableInfo::EK_GPRel64BlockAddress: return 8; case MachineJumpTableInfo::EK_GPRel32BlockAddress: case MachineJumpTableInfo::EK_LabelDifference32: case MachineJumpTableInfo::EK_Custom32: return 4; case MachineJumpTableInfo::EK_Inline: return 0; } llvm_unreachable("Unknown jump table encoding!"); } /// Return the alignment of each entry in the jump table. unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const { // The alignment of a jump table entry is the alignment of int32 unless the // entry is just the address of a block, in which case it is the pointer // alignment. switch (getEntryKind()) { case MachineJumpTableInfo::EK_BlockAddress: return TD.getPointerABIAlignment(); case MachineJumpTableInfo::EK_GPRel64BlockAddress: return TD.getABIIntegerTypeAlignment(64); case MachineJumpTableInfo::EK_GPRel32BlockAddress: case MachineJumpTableInfo::EK_LabelDifference32: case MachineJumpTableInfo::EK_Custom32: return TD.getABIIntegerTypeAlignment(32); case MachineJumpTableInfo::EK_Inline: return 1; } llvm_unreachable("Unknown jump table encoding!"); } /// Create a new jump table entry in the jump table info. unsigned MachineJumpTableInfo::createJumpTableIndex( const std::vector<MachineBasicBlock*> &DestBBs) { assert(!DestBBs.empty() && "Cannot create an empty jump table!"); JumpTables.push_back(MachineJumpTableEntry(DestBBs)); return JumpTables.size()-1; } /// If Old is the target of any jump tables, update the jump tables to branch /// to New instead. bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old, MachineBasicBlock *New) { assert(Old != New && "Not making a change?"); bool MadeChange = false; for (size_t i = 0, e = JumpTables.size(); i != e; ++i) ReplaceMBBInJumpTable(i, Old, New); return MadeChange; } /// If Old is a target of the jump tables, update the jump table to branch to /// New instead. bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx, MachineBasicBlock *Old, MachineBasicBlock *New) { assert(Old != New && "Not making a change?"); bool MadeChange = false; MachineJumpTableEntry &JTE = JumpTables[Idx]; for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j) if (JTE.MBBs[j] == Old) { JTE.MBBs[j] = New; MadeChange = true; } return MadeChange; } void MachineJumpTableInfo::print(raw_ostream &OS) const { if (JumpTables.empty()) return; OS << "Jump Tables:\n"; for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) { OS << " jt#" << i << ": "; for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j) OS << " BB#" << JumpTables[i].MBBs[j]->getNumber(); } OS << '\n'; } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); } #endif //===----------------------------------------------------------------------===// // MachineConstantPool implementation //===----------------------------------------------------------------------===// void MachineConstantPoolValue::anchor() { } Type *MachineConstantPoolEntry::getType() const { if (isMachineConstantPoolEntry()) return Val.MachineCPVal->getType(); return Val.ConstVal->getType(); } bool MachineConstantPoolEntry::needsRelocation() const { if (isMachineConstantPoolEntry()) return true; return Val.ConstVal->needsRelocation(); } SectionKind MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const { if (needsRelocation()) return SectionKind::getReadOnlyWithRel(); switch (DL->getTypeAllocSize(getType())) { case 4: return SectionKind::getMergeableConst4(); case 8: return SectionKind::getMergeableConst8(); case 16: return SectionKind::getMergeableConst16(); case 32: return SectionKind::getMergeableConst32(); default: return SectionKind::getReadOnly(); } } MachineConstantPool::~MachineConstantPool() { for (unsigned i = 0, e = Constants.size(); i != e; ++i) if (Constants[i].isMachineConstantPoolEntry()) delete Constants[i].Val.MachineCPVal; for (DenseSet<MachineConstantPoolValue*>::iterator I = MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end(); I != E; ++I) delete *I; } /// Test whether the given two constants can be allocated the same constant pool /// entry. static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B, const DataLayout &DL) { // Handle the trivial case quickly. if (A == B) return true; // If they have the same type but weren't the same constant, quickly // reject them. if (A->getType() == B->getType()) return false; // We can't handle structs or arrays. if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) || isa<StructType>(B->getType()) || isa<ArrayType>(B->getType())) return false; // For now, only support constants with the same size. uint64_t StoreSize = DL.getTypeStoreSize(A->getType()); if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128) return false; Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8); // Try constant folding a bitcast of both instructions to an integer. If we // get two identical ConstantInt's, then we are good to share them. We use // the constant folding APIs to do this so that we get the benefit of // DataLayout. if (isa<PointerType>(A->getType())) A = ConstantFoldCastOperand(Instruction::PtrToInt, const_cast<Constant *>(A), IntTy, DL); else if (A->getType() != IntTy) A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A), IntTy, DL); if (isa<PointerType>(B->getType())) B = ConstantFoldCastOperand(Instruction::PtrToInt, const_cast<Constant *>(B), IntTy, DL); else if (B->getType() != IntTy) B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B), IntTy, DL); return A == B; } /// Create a new entry in the constant pool or return an existing one. /// User must specify the log2 of the minimum required alignment for the object. unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C, unsigned Alignment) { assert(Alignment && "Alignment must be specified!"); if (Alignment > PoolAlignment) PoolAlignment = Alignment; // Check to see if we already have this constant. // // FIXME, this could be made much more efficient for large constant pools. for (unsigned i = 0, e = Constants.size(); i != e; ++i) if (!Constants[i].isMachineConstantPoolEntry() && CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) { if ((unsigned)Constants[i].getAlignment() < Alignment) Constants[i].Alignment = Alignment; return i; } Constants.push_back(MachineConstantPoolEntry(C, Alignment)); return Constants.size()-1; } unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V, unsigned Alignment) { assert(Alignment && "Alignment must be specified!"); if (Alignment > PoolAlignment) PoolAlignment = Alignment; // Check to see if we already have this constant. // // FIXME, this could be made much more efficient for large constant pools. int Idx = V->getExistingMachineCPValue(this, Alignment); if (Idx != -1) { MachineCPVsSharingEntries.insert(V); return (unsigned)Idx; } Constants.push_back(MachineConstantPoolEntry(V, Alignment)); return Constants.size()-1; } void MachineConstantPool::print(raw_ostream &OS) const { if (Constants.empty()) return; OS << "Constant Pool:\n"; for (unsigned i = 0, e = Constants.size(); i != e; ++i) { OS << " cp#" << i << ": "; if (Constants[i].isMachineConstantPoolEntry()) Constants[i].Val.MachineCPVal->print(OS); else Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false); OS << ", align=" << Constants[i].getAlignment(); OS << "\n"; } } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); } #endif
[ "fuzzie@fuzzie.org" ]
fuzzie@fuzzie.org
3558a2b01e849f7506203a031cae6ee32d6205cf
eee168a98d5e9e3d3a6c1e60d18a26985c799809
/BaseEngine/singleton/EnvironmentInfo.h
36c59e82097d754e66fbee0aecfd8d9c759eef2a
[]
no_license
yxinyi/ZEP
a3954ef248f744a45705c2e5ab5464b14770c8bb
5f41376bccfcb600cb990fd3c82bbf4599be6cb3
refs/heads/master
2022-09-30T16:49:51.529340
2020-06-06T17:46:14
2020-06-06T17:46:14
268,793,557
0
1
null
null
null
null
UTF-8
C++
false
false
366
h
#pragma once #include <cstdint> #include <iostream> #include "tool/SingletonTemplate.h" #include "entt.hpp" #include "include/zmq/cppzmq/zmq_addon.hpp" class EnvironmentInfo { public: const size_t m_frame = 60; const size_t m_shakehand_tm = 7; entt::registry m_registry; bool m_open = true; }; #define ENV Singleton<EnvironmentInfo>::getInstance()
[ "526924057@qq.com" ]
526924057@qq.com
8172ab1fa2ca1dc69fa2fcf96fe10909b93fff99
998a318796a237601e06616d94d671dedb66d810
/src/kaleidoscope/device.cpp
13f186d400417aac39a2201c2adcbd54b2acdb51
[]
no_license
ptierney/Kaleidoscope
f80e57c5e26a3e03d498855a4a4e956e9ff0ae30
19991163f2d63427caa3a43f3524f8d53f52b945
refs/heads/master
2021-01-22T23:53:39.659132
2010-08-22T02:55:56
2010-08-22T02:55:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,729
cpp
#include <time.h> #include <iostream> #include <QDockWidget> #include <QGraphicsView> #include <QGLWidget> #include <kaleidoscope/device.h> #include <kaleidoscope/settings.h> #include <kaleidoscope/room.h> #include <kaleidoscope/eventController.h> #include <kaleidoscope/camera.h> #include <kaleidoscope/spaceRenderer.h> #include <kaleidoscope/noticeWindow.h> #include <kaleidoscope/consoleWindow.h> #include <kaleidoscope/console.h> #include <kaleidoscope/scene2d.h> #include <kaleidoscope/view2d.h> #include <kaleidoscope/chatController.h> #include <kaleidoscope/user.h> #include <kaleidoscope/userNameInputBox.h> #include <kaleidoscope/userNameBox.h> #include <kaleidoscope/addUsernameBox.h> #include <kaleidoscope/outsideChatController.h> #include <grids/interface.h> #include <grids/objectController.h> #include <grids/utility.h> #include <grids/event.h> #include <kaleidoscope/otherUsersNode.h> #include <kaleidoscope/usersScene.h> #include <kaleidoscope/usersView.h> #include <kaleidoscope/usersWidget.h> #include <kaleidoscope/userView.h> namespace Kaleidoscope { Device::Device(QApplication* in_app, QMainWindow* m_win) : QObject(m_win) { main_window = m_win; app = in_app; main_camera = 0; connected = 0; debug_display_ = false; init(); } void Device::init() { qtime.start(); qsrand ( time(NULL) ); /* OK, let's try setting up an event loop like this. */ startTimer(100); /* NoticeWindow & ErrorWindow must be created before any Grids::Objects, * as all Grids::Objects require them to be created. */ createNoticeWindow(); createErrorWindow(); createConsole(); createUsersInfoWindow(); createScene(); /* Show the main window so we can read notices as the program connects. */ main_window->show(); setMyID( getGridsUtility()->getNewUUID() ); createObjects(); // Creates the protocol, connects to the server g_interface = new Grids::Interface(this, main_window); createUserInputWindow(); } void Device::createObjects(){ noticeWindow->addNotice(tr("Creating objects")); // Settings stores / loads the user data settings = new Settings(); user_ = new User(this, my_id_); chat_controller_ = new ChatController(this); chat_controller_->init(); outside_chat_controller_ = new OutsideChatController(this); outside_chat_controller_->init(); // Derived from QWidget, handles misc. key presses event_controller_ = new EventController(this); object_controller = new Grids::ObjectController(this, main_window); g_utility = new Grids::Utility(); // Make sure that the main window has focus //getScene()->main_view()->setFocus(Qt::NoFocusReason); } void Device::quit() { app->exit(0); } /* This is the main event loop. */ void Device::timerEvent(QTimerEvent* /*event*/) { if(connected == false && getInterface()->isConnected() == true) { connected = true; loadRoom(); } getInterface()->flushProtocol(); getInterface()->collectEvents(); } void Device::gridsConnectionEstablished() { loadRoom(); } Device::~Device() { /* Any Qt derived object is destroyed by Qt */ delete g_interface; delete g_utility; delete settings; } Grids::ObjectController* Device::getObjectController(){ return object_controller; } Grids::Interface* Device::getInterface(){ return g_interface; } Grids::Utility* Device::getGridsUtility(){ return g_utility; } Settings* Device::getSettings() { return settings; } EventController* Device::getEventController(){ return event_controller_; } EventController* Device::event_controller(){ return event_controller_; } NoticeWindow* Device::getNoticeWindow() { return noticeWindow; } NoticeWindow* Device::getErrorWindow() { return errorWindow; } Scene2D* Device::getScene() { return scene; } Camera* Device::getCamera() { return main_camera; } ChatController* Device::getChatController() { return chat_controller_; } ChatController* Device::chat_controller() { return chat_controller_; } OutsideChatController* Device::outside_chat_controller() { return outside_chat_controller_; } User* Device::user() { return user_; } UsersScene* Device::users_scene() { return users_scene_; } UsersView* Device::users_view() { return users_view_; } void Device::loadRoom(){ getInterface()->requestAllRooms(); } void Device::myRoomCreated(GridsID /*rm*/) { //getNoticeWindow()->addNotice(4, tr("Your room created")); //getNoticeWindow()->addNotice(4, tr("Requesting a camera from the server.")); /* Requests a new camera from the server. */ //requestCreateCamera(); } // The four main starting boxes: camera, notices, errors, console // Create a new camera, and if it belongs to us, register it as the main // camera. void Device::registerCamera(Grids::Value* val) { QDockWidget *dock = new QDockWidget(tr("Camera"), main_window); Camera* cam = new Camera(this, val, dock); dock->setWidget(cam); main_window->addDockWidget(Qt::LeftDockWidgetArea, dock); //main_window->setCentralWidget(cam); if(main_camera == 0) main_camera = cam; } void Device::createConsole() { QDockWidget *dock = new QDockWidget(tr("Console"), main_window); dock->setFloating(0); dock->resize(DEFAULT_SIDEBAR_WIDTH, DEFAULT_WINDOW_HEIGHT/2.f); console = new Console(this, dock); dock->setWidget(console->getConsoleWindow()); main_window->addDockWidget( Qt::RightDockWidgetArea, dock); if(!debug_display_) dock->close(); } void Device::createNoticeWindow() { QDockWidget *dock = new QDockWidget(tr("Notices"), main_window); dock->setFloating(0); dock->resize(DEFAULT_SIDEBAR_WIDTH, DEFAULT_WINDOW_HEIGHT/2.f); noticeWindow = new NoticeWindow(dock); dock->setWidget(noticeWindow); main_window->addDockWidget(Qt::RightDockWidgetArea, dock); if(!debug_display_) dock->close(); } void Device::createErrorWindow() { QDockWidget *dock = new QDockWidget(tr("Errors"), main_window); dock->setFloating(0); errorWindow = new NoticeWindow(dock); dock->setWidget(errorWindow); main_window->addDockWidget(Qt::RightDockWidgetArea, dock); if(!debug_display_) dock->close(); } void Device::createUsersInfoWindow() { QDockWidget *dock = new QDockWidget(tr("People in Chat"), main_window); dock->setFloating(0); dock->resize(DEFAULT_SIDEBAR_WIDTH, DEFAULT_WINDOW_HEIGHT/2.f); users_scene_ = new UsersScene(this, dock); users_scene_->init(); users_view_ = new UsersView(this, users_scene_); users_view_->init(); dock->setWidget(users_view_); //dock->setAllowedAreas(Qt::NoDockWidgetArea); main_window->addDockWidget(Qt::RightDockWidgetArea, dock); } void Device::createUserViewWindow(UserView* view){ QDockWidget *dock = new QDockWidget(tr(view->user()->name().c_str()), main_window); dock->setFloating(0); dock->resize(DEFAULT_SIDEBAR_WIDTH, DEFAULT_WINDOW_HEIGHT/2.f); dock->setWidget(view); //dock->setAllowedAreas(Qt::NoDockWidgetArea); main_window->addDockWidget(Qt::RightDockWidgetArea, dock); } void Device::createUserInputWindow(){ QDockWidget *dock = new QDockWidget(tr("Set Your Name"), main_window); dock->setFloating(1); UserNameBox* box = new UserNameBox(this, dock); dock->setWidget(box); dock->setAllowedAreas(Qt::NoDockWidgetArea); main_window->addDockWidget(Qt::LeftDockWidgetArea, dock); box->input_line()->setFocus(Qt::NoFocusReason); //box->setFocus(Qt::PopupFocusReason); } void Device::createAddUserWindow(){ QDockWidget *dock = new QDockWidget(tr("Add Account"), main_window); dock->setFloating(1); AddUsernameBox* box = new AddUsernameBox(this, dock); dock->setWidget(box); dock->setAllowedAreas(Qt::NoDockWidgetArea); main_window->addDockWidget(Qt::LeftDockWidgetArea, dock); } void Device::createColorPickWindow(){ QDockWidget *dock = new QDockWidget(tr("Set Color"), main_window); dock->setFloating(1); QColorDialog* color_pick = new QColorDialog(dock); dock->setWidget(color_pick); dock->setAllowedAreas(Qt::NoDockWidgetArea); main_window->addDockWidget(Qt::LeftDockWidgetArea, dock); connect(color_pick, SIGNAL(colorSelected(QColor)), user(), SLOT(set_color(QColor))); connect(color_pick, SIGNAL(colorSelected(QColor)), dock, SLOT(close())); connect(color_pick, SIGNAL(finished(int)), view2D, SLOT(giveFocus())); } void Device::createScene() { scene = new Scene2D(this, main_window); view2D = new View2D(this, scene); main_window->setCentralWidget(view2D); } void Device::registerNotice(QObject* object) { noticeWindow->connect(object, SIGNAL(notice(int, QString)), noticeWindow, SLOT(addNotice(int,QString))); } void Device::registerError(QObject* object) { errorWindow->connect(object, SIGNAL(error(int, QString)), errorWindow, SLOT(addNotice(int,QString))); } void Device::setMyRoom(GridsID new_room) { my_room = new_room; getInterface()->setMyRoom(new_room); } bool Device::myChild(GridsID test_id) { return test_id == getMyID(); } int Device::getTicks() { return qtime.elapsed(); } void Device::requestCreateCamera(){ Vec3D start_pos = Vec3D( 10.0f, 30.0f, 35.0f ); Vec3D start_rot = Vec3D( 1.0f, -1.0f, 0.0f ); Vec3D start_scl = Vec3D( 1.0f, 1.0f, 1.0f ); Grids::Value* cam_val = new Grids::Value(); (*cam_val)[ "type" ] = "Camera"; (*cam_val)[ "parent" ] = getMyID(); (*cam_val)[ "camera_type" ] = MAYA; (*cam_val)[ "rotate_speed" ] = .3f; (*cam_val)[ "translate_speed" ] = 0.001f; (*cam_val)[ "target" ][ 0u ] = -1.0f; (*cam_val)[ "target" ][ 1u ] = -1.0f; (*cam_val)[ "target" ][ 2u ] = -1.0f; (*cam_val)[ "up" ][ 0u ] = 0.0f; (*cam_val)[ "up" ][ 1u ] = 1.0f; (*cam_val)[ "up" ][ 2u ] = 0.0f; getInterface()->requestCreateObject( cam_val, start_pos, start_rot, start_scl ); delete cam_val; } ///////////////////////////////////// // Accessor Functions bool Device::getRunning() { return running; } void Device::setRunning( bool new_run ){ running = new_run; } GridsID Device::getMyID(){ return my_id_; } GridsID Device::my_id(){ return my_id_; } void Device::setMyID( GridsID temp_id ){ my_id_ = temp_id; //getNoticeWindow()->addNotice(4, tr("ID set to: ")+tr(temp_id.c_str())); } GridsID Device::getMyRoom() { return getInterface()->getMyRoom(); } } // end namespace Kaleidoscope
[ "patrick.l.tierney@gmail.com" ]
patrick.l.tierney@gmail.com
e5c9a4cd0a42d0c69412e27b0570df00fef4e6b5
ec860e036bb7b84f68c42a8567cf40e8cdbd292a
/Include_Files/maincpp.h
30039e9537e9d1083584a8d084f0fc579b76c965
[]
no_license
acharyasandeep/dharaharaRendering
e99e12c4cd3a90bb8f144d0f60a7d5cae6f5b404
888356266e745e671ebd3cb7d6276e839875b8a3
refs/heads/main
2023-07-09T06:42:32.721921
2021-08-13T04:39:11
2021-08-13T04:39:11
395,517,965
1
0
null
null
null
null
UTF-8
C++
false
false
3,062
h
#include <glad/glad.h> #include <GLFW/glfw3.h> #include "Shader.h" #include "Camera.h" #include "Model.h" #include "Light.h" #include <iostream> float skyboxVertices[] = { // positions -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f }; //skybox faces vector<std::string> faces { "skybox/right.jpg", "skybox/left.jpg", "skybox/top.jpg", "skybox/bottom.jpg", "skybox/front.jpg", "skybox/back.jpg" }; //groundPlane const float groundPlaneVertices[] = { // positions //texture coordinates -1, 0, -1, 0, 1, 1, 0, -1, 1, 1, 1, 0, 1, 1, 0, -1, 0, 1, 0, 0 }; const unsigned int groundPlaneIndices[] = { 0, 1, 2, 2, 3, 0 }; //lightCube float lightCubeVertices[] = { -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, }; // settings const unsigned int SCR_WIDTH = 3840; const unsigned int SCR_HEIGHT = 2400; // camera Camera camera(Transf::vec3(0.0f, 3.0f, 25.0f)); float lastX = SCR_WIDTH / 2.0f; float lastY = SCR_HEIGHT / 2.0f; bool firstMouse = true; // timing float deltaTime = 0.0f; float lastFrame = 0.0f; //lighting //Transf::vec3 lightPos(15.0f, 20.0f, 1.0f); // positions of the point lights Transf::vec3 pointLightPositions[] = { Transf::vec3(-5.0f, 2.0f, 0.2f), Transf::vec3(5.0f, 2.0f, -1.0f), Transf::vec3(15.0f, 20.0f, 1.0f), }; bool isDark = false; float strength;
[ "acharyas378@gmail.com" ]
acharyas378@gmail.com
9944669b002ec1a1a23866292239b98b3a682b71
0b8fb244628e152121a5a54e18eead7ab53bed39
/src/test/policyestimator_tests.cpp
7332dc538a66c346a8fa49819590ca3a47018b63
[ "MIT" ]
permissive
prapun77/advance
d95badcc771eba4297a63d28b6c2344b9769f20b
9cc883d5e596988856408ed1616145409653be85
refs/heads/master
2020-03-23T00:27:24.010425
2018-07-15T12:54:05
2018-07-15T12:54:05
140,864,391
0
0
null
null
null
null
UTF-8
C++
false
false
9,763
cpp
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "policy/fees.h" #include "txmempool.h" #include "uint256.h" #include "util.h" #include "test/test_advance.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(policyestimator_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(BlockPolicyEstimates) { CTxMemPool mpool(CFeeRate(1000)); TestMemPoolEntryHelper entry; CAmount basefee(2000); double basepri = 1e6; CAmount deltaFee(100); double deltaPri=5e5; std::vector<CAmount> feeV[2]; std::vector<double> priV[2]; // Populate vectors of increasing fees or priorities for (int j = 0; j < 10; j++) { //V[0] is for fee transactions feeV[0].push_back(basefee * (j+1)); priV[0].push_back(0); //V[1] is for priority transactions feeV[1].push_back(CAmount(0)); priV[1].push_back(basepri * pow(10, j+1)); } // Store the hashes of transactions that have been // added to the mempool by their associate fee/pri // txHashes[j] is populated with transactions either of // fee = basefee * (j+1) OR pri = 10^6 * 10^(j+1) std::vector<uint256> txHashes[10]; // Create a transaction template CScript garbage; for (unsigned int i = 0; i < 128; i++) garbage.push_back('X'); CMutableTransaction tx; std::list<CTransaction> dummyConflicted; tx.vin.resize(1); tx.vin[0].scriptSig = garbage; tx.vout.resize(1); tx.vout[0].nValue=0LL; CFeeRate baseRate(basefee, ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION)); // Create a fake block std::vector<CTransaction> block; int blocknum = 0; // Loop through 200 blocks // At a decay .998 and 4 fee transactions per block // This makes the tx count about 1.33 per bucket, above the 1 threshold while (blocknum < 200) { for (int j = 0; j < 10; j++) { // For each fee/pri multiple for (int k = 0; k < 5; k++) { // add 4 fee txs for every priority tx tx.vin[0].prevout.n = 10000*blocknum+100*j+k; // make transaction unique uint256 hash = tx.GetHash(); mpool.addUnchecked(hash, entry.Fee(feeV[k/4][j]).Time(GetTime()).Priority(priV[k/4][j]).Height(blocknum).FromTx(tx, &mpool)); txHashes[j].push_back(hash); } } //Create blocks where higher fee/pri txs are included more often for (int h = 0; h <= blocknum%10; h++) { // 10/10 blocks add highest fee/pri transactions // 9/10 blocks add 2nd highest and so on until ... // 1/10 blocks add lowest fee/pri transactions while (txHashes[9-h].size()) { CTransaction btx; if (mpool.lookup(txHashes[9-h].back(), btx)) block.push_back(btx); txHashes[9-h].pop_back(); } } mpool.removeForBlock(block, ++blocknum, dummyConflicted); block.clear(); if (blocknum == 30) { // At this point we should need to combine 5 buckets to get enough data points // So estimateFee(1,2,3) should fail and estimateFee(4) should return somewhere around // 8*baserate. estimateFee(4) %'s are 100,100,100,100,90 = average 98% BOOST_CHECK(mpool.estimateFee(1) == CFeeRate(0)); BOOST_CHECK(mpool.estimateFee(2) == CFeeRate(0)); BOOST_CHECK(mpool.estimateFee(3) == CFeeRate(0)); BOOST_CHECK(mpool.estimateFee(4).GetFeePerK() < 8*baseRate.GetFeePerK() + deltaFee); BOOST_CHECK(mpool.estimateFee(4).GetFeePerK() > 8*baseRate.GetFeePerK() - deltaFee); int answerFound; BOOST_CHECK(mpool.estimateSmartFee(1, &answerFound) == mpool.estimateFee(4) && answerFound == 4); BOOST_CHECK(mpool.estimateSmartFee(3, &answerFound) == mpool.estimateFee(4) && answerFound == 4); BOOST_CHECK(mpool.estimateSmartFee(4, &answerFound) == mpool.estimateFee(4) && answerFound == 4); BOOST_CHECK(mpool.estimateSmartFee(8, &answerFound) == mpool.estimateFee(8) && answerFound == 8); } } std::vector<CAmount> origFeeEst; std::vector<double> origPriEst; // Highest feerate is 10*baseRate and gets in all blocks, // second highest feerate is 9*baseRate and gets in 9/10 blocks = 90%, // third highest feerate is 8*base rate, and gets in 8/10 blocks = 80%, // so estimateFee(1) should return 10*baseRate. // Second highest feerate has 100% chance of being included by 2 blocks, // so estimateFee(2) should return 9*baseRate etc... for (int i = 1; i < 10;i++) { origFeeEst.push_back(mpool.estimateFee(i).GetFeePerK()); origPriEst.push_back(mpool.estimatePriority(i)); if (i > 1) { // Fee estimates should be monotonically decreasing BOOST_CHECK(origFeeEst[i-1] <= origFeeEst[i-2]); BOOST_CHECK(origPriEst[i-1] <= origPriEst[i-2]); } int mult = 11-i; BOOST_CHECK(origFeeEst[i-1] < mult*baseRate.GetFeePerK() + deltaFee); BOOST_CHECK(origFeeEst[i-1] > mult*baseRate.GetFeePerK() - deltaFee); BOOST_CHECK(origPriEst[i-1] < pow(10,mult) * basepri + deltaPri); BOOST_CHECK(origPriEst[i-1] > pow(10,mult) * basepri - deltaPri); } // Mine 50 more blocks with no transactions happening, estimates shouldn't change // We haven't decayed the moving average enough so we still have enough data points in every bucket while (blocknum < 250) mpool.removeForBlock(block, ++blocknum, dummyConflicted); for (int i = 1; i < 10;i++) { BOOST_CHECK(mpool.estimateFee(i).GetFeePerK() < origFeeEst[i-1] + deltaFee); BOOST_CHECK(mpool.estimateFee(i).GetFeePerK() > origFeeEst[i-1] - deltaFee); BOOST_CHECK(mpool.estimatePriority(i) < origPriEst[i-1] + deltaPri); BOOST_CHECK(mpool.estimatePriority(i) > origPriEst[i-1] - deltaPri); } // Mine 15 more blocks with lots of transactions happening and not getting mined // Estimates should go up while (blocknum < 265) { for (int j = 0; j < 10; j++) { // For each fee/pri multiple for (int k = 0; k < 5; k++) { // add 4 fee txs for every priority tx tx.vin[0].prevout.n = 10000*blocknum+100*j+k; uint256 hash = tx.GetHash(); mpool.addUnchecked(hash, entry.Fee(feeV[k/4][j]).Time(GetTime()).Priority(priV[k/4][j]).Height(blocknum).FromTx(tx, &mpool)); txHashes[j].push_back(hash); } } mpool.removeForBlock(block, ++blocknum, dummyConflicted); } int answerFound; for (int i = 1; i < 10;i++) { BOOST_CHECK(mpool.estimateFee(i) == CFeeRate(0) || mpool.estimateFee(i).GetFeePerK() > origFeeEst[i-1] - deltaFee); BOOST_CHECK(mpool.estimateSmartFee(i, &answerFound).GetFeePerK() > origFeeEst[answerFound-1] - deltaFee); BOOST_CHECK(mpool.estimatePriority(i) == -1 || mpool.estimatePriority(i) > origPriEst[i-1] - deltaPri); BOOST_CHECK(mpool.estimateSmartPriority(i, &answerFound) > origPriEst[answerFound-1] - deltaPri); } // Mine all those transactions // Estimates should still not be below original for (int j = 0; j < 10; j++) { while(txHashes[j].size()) { CTransaction btx; if (mpool.lookup(txHashes[j].back(), btx)) block.push_back(btx); txHashes[j].pop_back(); } } mpool.removeForBlock(block, 265, dummyConflicted); block.clear(); for (int i = 1; i < 10;i++) { BOOST_CHECK(mpool.estimateFee(i).GetFeePerK() > origFeeEst[i-1] - deltaFee); BOOST_CHECK(mpool.estimatePriority(i) > origPriEst[i-1] - deltaPri); } // Mine 200 more blocks where everything is mined every block // Estimates should be below original estimates while (blocknum < 465) { for (int j = 0; j < 10; j++) { // For each fee/pri multiple for (int k = 0; k < 5; k++) { // add 4 fee txs for every priority tx tx.vin[0].prevout.n = 10000*blocknum+100*j+k; uint256 hash = tx.GetHash(); mpool.addUnchecked(hash, entry.Fee(feeV[k/4][j]).Time(GetTime()).Priority(priV[k/4][j]).Height(blocknum).FromTx(tx, &mpool)); CTransaction btx; if (mpool.lookup(hash, btx)) block.push_back(btx); } } mpool.removeForBlock(block, ++blocknum, dummyConflicted); block.clear(); } for (int i = 1; i < 10; i++) { BOOST_CHECK(mpool.estimateFee(i).GetFeePerK() < origFeeEst[i-1] - deltaFee); BOOST_CHECK(mpool.estimatePriority(i) < origPriEst[i-1] - deltaPri); } // Test that if the mempool is limited, estimateSmartFee won't return a value below the mempool min fee // and that estimateSmartPriority returns essentially an infinite value mpool.addUnchecked(tx.GetHash(), entry.Fee(feeV[0][5]).Time(GetTime()).Priority(priV[1][5]).Height(blocknum).FromTx(tx, &mpool)); // evict that transaction which should set a mempool min fee of minRelayTxFee + feeV[0][5] mpool.TrimToSize(1); BOOST_CHECK(mpool.GetMinFee(1).GetFeePerK() > feeV[0][5]); for (int i = 1; i < 10; i++) { BOOST_CHECK(mpool.estimateSmartFee(i).GetFeePerK() >= mpool.estimateFee(i).GetFeePerK()); BOOST_CHECK(mpool.estimateSmartFee(i).GetFeePerK() >= mpool.GetMinFee(1).GetFeePerK()); BOOST_CHECK(mpool.estimateSmartPriority(i) == INF_PRIORITY); } } BOOST_AUTO_TEST_SUITE_END()
[ "getadvance@protonmail.ch" ]
getadvance@protonmail.ch
1bb8b4b2ed5d7e6d0aeca34b49e7628d229dacc3
e5e0d729f082999a9bec142611365b00f7bfc684
/tensorflow/core/profiler/tfprof_options.cc
e940a9911eff8857f0832e96988afa8c6f8fb5df
[ "Apache-2.0" ]
permissive
NVIDIA/tensorflow
ed6294098c7354dfc9f09631fc5ae22dbc278138
7cbba04a2ee16d21309eefad5be6585183a2d5a9
refs/heads/r1.15.5+nv23.03
2023-08-16T22:25:18.037979
2023-08-03T22:09:23
2023-08-03T22:09:23
263,748,045
763
117
Apache-2.0
2023-07-03T15:45:19
2020-05-13T21:34:32
C++
UTF-8
C++
false
false
8,762
cc
/* Copyright 2016 The TensorFlow Authors All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/profiler/tfprof_options.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/lib/strings/stringprintf.h" #include "tensorflow/core/profiler/tfprof_options.pb.h" namespace tensorflow { namespace tfprof { namespace { string KeyValueToStr(const std::map<string, string>& kv_map) { std::vector<string> kv_vec; kv_vec.reserve(kv_map.size()); for (const auto& pair : kv_map) { kv_vec.push_back(strings::StrCat(pair.first, "=", pair.second)); } return absl::StrJoin(kv_vec, ","); } } // namespace tensorflow::Status ParseOutput(const string& output_opt, string* output_type, std::map<string, string>* output_options) { // The default is to use stdout. if (output_opt.empty()) { *output_type = kOutput[1]; return tensorflow::Status::OK(); } std::set<string> output_types(kOutput, kOutput + sizeof(kOutput) / sizeof(*kOutput)); auto opt_split = output_opt.find(":"); std::vector<string> kv_split; if (opt_split == output_opt.npos) { if (output_types.find(output_opt) == output_types.end()) { return tensorflow::Status( tensorflow::error::INVALID_ARGUMENT, strings::Printf("E.g. Unknown output type: %s, Valid types: %s\n", output_opt.c_str(), absl::StrJoin(output_types, ",").c_str())); } *output_type = output_opt; } else { *output_type = output_opt.substr(0, opt_split); if (output_types.find(*output_type) == output_types.end()) { return tensorflow::Status( tensorflow::error::INVALID_ARGUMENT, strings::Printf("E.g. Unknown output type: %s, Valid types: %s\n", output_type->c_str(), absl::StrJoin(output_types, ",").c_str())); } kv_split = str_util::Split(output_opt.substr(opt_split + 1), ",", str_util::SkipEmpty()); } std::set<string> valid_options; std::set<string> required_options; if (*output_type == kOutput[0]) { valid_options.insert( kTimelineOpts, kTimelineOpts + sizeof(kTimelineOpts) / sizeof(*kTimelineOpts)); required_options.insert( kTimelineRequiredOpts, kTimelineRequiredOpts + sizeof(kTimelineRequiredOpts) / sizeof(*kTimelineRequiredOpts)); } else if (*output_type == kOutput[2]) { valid_options.insert(kFileOpts, kFileOpts + sizeof(kFileOpts) / sizeof(*kFileOpts)); required_options.insert(kFileRequiredOpts, kFileRequiredOpts + sizeof(kFileRequiredOpts) / sizeof(*kFileRequiredOpts)); } else if (*output_type == kOutput[3]) { valid_options.insert(kPprofOpts, kPprofOpts + sizeof(kPprofOpts) / sizeof(*kPprofOpts)); required_options.insert( kPprofRequiredOpts, kPprofRequiredOpts + sizeof(kPprofRequiredOpts) / sizeof(*kPprofRequiredOpts)); } for (const string& kv_str : kv_split) { const std::vector<string> kv = str_util::Split(kv_str, "=", str_util::SkipEmpty()); if (kv.size() < 2) { return tensorflow::Status( tensorflow::error::INVALID_ARGUMENT, "Visualize format: -output timeline:key=value,key=value,..."); } if (valid_options.find(kv[0]) == valid_options.end()) { return tensorflow::Status( tensorflow::error::INVALID_ARGUMENT, strings::Printf("Unrecognized options %s for output_type: %s\n", kv[0].c_str(), output_type->c_str())); } const std::vector<string> kv_without_key(kv.begin() + 1, kv.end()); (*output_options)[kv[0]] = absl::StrJoin(kv_without_key, "="); } for (const string& opt : required_options) { if (output_options->find(opt) == output_options->end()) { return tensorflow::Status( tensorflow::error::INVALID_ARGUMENT, strings::Printf("Missing required output_options for %s\n" "E.g. -output %s:%s=...\n", output_type->c_str(), output_type->c_str(), opt.c_str())); } } return tensorflow::Status::OK(); } tensorflow::Status Options::FromProtoStr(const string& opts_proto_str, Options* opts) { OptionsProto opts_pb; if (!opts_pb.ParseFromString(opts_proto_str)) { return tensorflow::Status( tensorflow::error::INTERNAL, strings::StrCat("Failed to parse option string from Python API: ", opts_proto_str)); } string output_type; std::map<string, string> output_options; tensorflow::Status s = ParseOutput(opts_pb.output(), &output_type, &output_options); if (!s.ok()) return s; if (!opts_pb.dump_to_file().empty()) { fprintf(stderr, "-dump_to_file option is deprecated. " "Please use -output file:outfile=<filename>\n"); fprintf(stderr, "-output %s is overwritten with -output file:outfile=%s\n", opts_pb.output().c_str(), opts_pb.dump_to_file().c_str()); output_type = kOutput[2]; output_options.clear(); output_options[kFileOpts[0]] = opts_pb.dump_to_file(); } *opts = Options( opts_pb.max_depth(), opts_pb.min_bytes(), opts_pb.min_peak_bytes(), opts_pb.min_residual_bytes(), opts_pb.min_output_bytes(), opts_pb.min_micros(), opts_pb.min_accelerator_micros(), opts_pb.min_cpu_micros(), opts_pb.min_params(), opts_pb.min_float_ops(), opts_pb.min_occurrence(), opts_pb.step(), opts_pb.order_by(), std::vector<string>(opts_pb.account_type_regexes().begin(), opts_pb.account_type_regexes().end()), std::vector<string>(opts_pb.start_name_regexes().begin(), opts_pb.start_name_regexes().end()), std::vector<string>(opts_pb.trim_name_regexes().begin(), opts_pb.trim_name_regexes().end()), std::vector<string>(opts_pb.show_name_regexes().begin(), opts_pb.show_name_regexes().end()), std::vector<string>(opts_pb.hide_name_regexes().begin(), opts_pb.hide_name_regexes().end()), opts_pb.account_displayed_op_only(), std::vector<string>(opts_pb.select().begin(), opts_pb.select().end()), output_type, output_options); return tensorflow::Status::OK(); } string Options::ToString() const { const string s = strings::Printf( "%-28s%d\n" "%-28s%lld\n" "%-28s%lld\n" "%-28s%lld\n" "%-28s%lld\n" "%-28s%lld\n" "%-28s%lld\n" "%-28s%lld\n" "%-28s%lld\n" "%-28s%lld\n" "%-28s%lld\n" "%-28s%lld\n" "%-28s%s\n" "%-28s%s\n" "%-28s%s\n" "%-28s%s\n" "%-28s%s\n" "%-28s%s\n" "%-28s%s\n" "%-28s%s\n" "%-28s%s:%s\n", kOptions[0], max_depth, kOptions[1], min_bytes, kOptions[2], min_peak_bytes, kOptions[3], min_residual_bytes, kOptions[4], min_output_bytes, kOptions[5], min_micros, kOptions[6], min_accelerator_micros, kOptions[7], min_cpu_micros, kOptions[8], min_params, kOptions[9], min_float_ops, kOptions[10], min_occurrence, kOptions[11], step, kOptions[12], order_by.c_str(), kOptions[13], absl::StrJoin(account_type_regexes, ",").c_str(), kOptions[14], absl::StrJoin(start_name_regexes, ",").c_str(), kOptions[15], absl::StrJoin(trim_name_regexes, ",").c_str(), kOptions[16], absl::StrJoin(show_name_regexes, ",").c_str(), kOptions[17], absl::StrJoin(hide_name_regexes, ",").c_str(), kOptions[18], (account_displayed_op_only ? "true" : "false"), kOptions[19], absl::StrJoin(select, ",").c_str(), kOptions[20], output_type.c_str(), KeyValueToStr(output_options).c_str()); return s; } } // namespace tfprof } // namespace tensorflow
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
1e230c63501d5452f70b80f0dc3b36caf14b54ea
b0a6f3cb09033d0dd31f0553eb5a0e2f79beeaad
/src/Renderer/Models/SimpleEnemyModel.cpp
083f1cb87e755f0926a1ad7d37df651587f50ef9
[]
no_license
youngkingtut/learning-opengl
46285dd0bc746f7525f4306a8191ab714c9e096c
745faabc03f8e66d1fff264a5bdeba41c19a2184
refs/heads/master
2022-11-15T17:21:00.398019
2020-06-22T16:57:37
2020-06-22T16:57:37
195,731,751
0
0
null
null
null
null
UTF-8
C++
false
false
1,650
cpp
#include "SimpleEnemyModel.h" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> void SimpleEnemyModel::loadStatic() { std::vector<glm::vec3> vertices; std::vector<GLuint> elements; loadFromFile("Resources/Models/simpleEnemy.obj", vertices, elements); elementBufferSize = elements.size(); glGenVertexArrays(1, &vertexArrayObject); glGenBuffers(1, &vertexBufferObject); glGenBuffers(1, &elementBufferObject); glBindVertexArray(vertexArrayObject); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBufferObject); glBufferData(GL_ELEMENT_ARRAY_BUFFER, elements.size() * sizeof(GLuint), &elements[0], GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr); glEnableVertexAttribArray(0); } void SimpleEnemyModel::draw(const SimpleEnemy &enemy, const GLuint& modelViewMatrixLocation, const GLuint& colorLocation) { glBindVertexArray(vertexArrayObject); glm::vec2 position = enemy.getPosition(); float angle = enemy.getAngle(); glm::mat4 modelViewMatrix = glm::translate(glm::mat4(), glm::vec3(position[0], position[1], 0.0F)) * glm::rotate(glm::mat4(), angle, glm::vec3(0.0F, 0.0F, 1.0F)); glUniformMatrix4fv(modelViewMatrixLocation, 1, GL_FALSE, glm::value_ptr(modelViewMatrix)); glUniform4f(colorLocation, color.r, color.g, color.b, color.a); glDrawElements(GL_TRIANGLES, elementBufferSize, GL_UNSIGNED_INT, nullptr); }
[ "tristanstorz@gmail.com" ]
tristanstorz@gmail.com
4f0afa9e39a4c76d448b44fa802da4402e3f5384
afed8585b5bd48a1ba8ebe063931a658592b1838
/include/webbie/http_exception.h
73738f5e821e7d0e1b644321ec3aae1d8a9d3ca5
[ "BSD-2-Clause" ]
permissive
phixcn/webbie
caade1c1a1376b37093591b962f4dfd914af0fce
3cdc939f28cd065cbea53c53469870603dd4c180
refs/heads/master
2022-01-21T19:18:54.203199
2019-07-24T13:18:40
2019-07-24T13:18:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,402
h
#ifndef webbie_webbie_exception_h #define webbie_webbie_exception_h #include "cppkit/ck_exception.h" #include "cppkit/ck_string_utils.h" namespace webbie { /// An internal exception type used to enter io error state. class webbie_io_exception : public cppkit::ck_exception { public: webbie_io_exception(); virtual ~webbie_io_exception() noexcept {} webbie_io_exception(const char* msg, ...); webbie_io_exception(const std::string& msg); }; /// General exception type for Webby. class webbie_exception_generic : public cppkit::ck_exception { public: webbie_exception_generic(); virtual ~webbie_exception_generic() noexcept {} webbie_exception_generic(const char* msg, ...); webbie_exception_generic(const std::string& msg); }; class webbie_exception : public webbie_exception_generic { public: webbie_exception( int statusCode ); virtual ~webbie_exception() noexcept {} webbie_exception( int statusCode, const char* msg, ... ); webbie_exception( int statusCode, const std::string& msg ); int get_status() const { return _statusCode; } private: int _statusCode; }; class webbie_400_exception : public webbie_exception { public: webbie_400_exception(); virtual ~webbie_400_exception() noexcept {} webbie_400_exception( const char* msg, ... ); webbie_400_exception( const std::string& msg ); }; class webbie_401_exception : public webbie_exception { public: webbie_401_exception(); virtual ~webbie_401_exception() noexcept {} webbie_401_exception( const char* msg, ... ); webbie_401_exception( const std::string& msg ); }; class webbie_403_exception : public webbie_exception { public: webbie_403_exception(); virtual ~webbie_403_exception() noexcept {} webbie_403_exception( const char* msg, ... ); webbie_403_exception( const std::string& msg ); }; class webbie_404_exception : public webbie_exception { public: webbie_404_exception(); virtual ~webbie_404_exception() noexcept {} webbie_404_exception( const char* msg, ... ); webbie_404_exception( const std::string& msg ); }; class webbie_415_exception : public webbie_exception { public: webbie_415_exception(); virtual ~webbie_415_exception() noexcept {} webbie_415_exception( const char* msg, ... ); webbie_415_exception( const std::string& msg ); }; class webbie_453_exception : public webbie_exception { public: webbie_453_exception(); virtual ~webbie_453_exception() noexcept{} webbie_453_exception( const char* msg, ... ); webbie_453_exception( const std::string& msg ); }; class webbie_500_exception : public webbie_exception { public: webbie_500_exception(); virtual ~webbie_500_exception() noexcept {} webbie_500_exception( const char* msg, ... ); webbie_500_exception( const std::string& msg ); }; class webbie_501_exception : public webbie_exception { public: webbie_501_exception(); virtual ~webbie_501_exception() noexcept {} webbie_501_exception( const char* msg, ... ); webbie_501_exception( const std::string& msg ); }; /// \brief Throws an exception corresponding to the given status code /// or a plain webbie_exception if there isn't one. void throw_webbie_exception( int statusCode, const char* msg, ... ); void throw_webbie_exception( int statusCode, const std::string& msg ); #define CATCH_TRANSLATE_HTTP_EXCEPTIONS(a) \ catch( webbie_400_exception& ex ) \ { \ CK_LOG_ERROR( "%s", ex.what() ); \ a.set_status_code( response_bad_request ); \ } \ catch( webbie_401_exception& ex ) \ { \ CK_LOG_ERROR( "%s", ex.what() ); \ response.set_status_code( response_unauthorized ); \ } \ catch( webbie_403_exception& ex ) \ { \ CK_LOG_ERROR( "%s", ex.what() ); \ response.set_status_code( response_forbidden ); \ } \ catch( webbie_404_exception& ex ) \ { \ CK_LOG_ERROR( "%s", ex.what() ); \ response.set_status_code( response_not_found ); \ } \ catch( webbie_500_exception& ex ) \ { \ CK_LOG_ERROR( "%s", ex.what() ); \ response.set_status_code( response_internal_server_error ); \ } \ catch( webbie_501_exception& ex ) \ { \ CK_LOG_ERROR( "%s", ex.what() ); \ response.set_status_code( response_not_implemented ); \ } } #endif
[ "tony@agrian.com" ]
tony@agrian.com
3fbb993534fb5a8c6fc7bfefdb5398c04db14c7f
78f6a66825077a196f66fa6dd6cdbfcb983a57e4
/Renderer/Renderer/Texture.h
a80f7e3a132eb820c814dada2b389278f5d13eca
[]
no_license
mattjoncas/opengl-engine
1b3ea95829339bcfab7e21875d8a74789ae12d47
a0a4d0359abd5eb934b8cc3bf728c328584d78e8
refs/heads/master
2016-09-06T18:13:37.250976
2015-04-21T04:00:35
2015-04-21T04:00:35
29,713,733
0
0
null
null
null
null
UTF-8
C++
false
false
245
h
#pragma once #include <gl/glew.h> #include <SFML/OpenGL.hpp> #include <string> namespace mor{ class Texture { public: Texture(); ~Texture(); void Init(GLuint _texture, std::string _file); GLuint texture; std::string file; }; }
[ "mattjoncas@users.noreply.github.com" ]
mattjoncas@users.noreply.github.com
c69aa08aeff76137f7f228683734395747f14e13
dcf205a47dc059219b7394d55d370ca0693c0757
/libs/vgc/ui/shortcut.h
881d4c9bd7db84e266b7144ccc319f4b78e8209a
[ "Apache-2.0" ]
permissive
vgc/vgc
1114a03ede4da5e97c11fde8f2d3b2bbac74e437
2b40d27f4c995c67031a808a7775dc77d9a244df
refs/heads/master
2023-09-01T02:10:28.818132
2023-08-31T13:37:40
2023-08-31T13:37:40
109,570,689
273
26
Apache-2.0
2023-09-14T09:56:49
2017-11-05T10:44:49
C++
UTF-8
C++
false
false
16,786
h
// Copyright 2021 The VGC Developers // See the COPYRIGHT file at the top-level directory of this distribution // and at https://github.com/vgc/vgc/blob/master/COPYRIGHT // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef VGC_UI_SHORTCUT_H #define VGC_UI_SHORTCUT_H #include <unordered_map> #include <unordered_set> #include <vgc/core/format.h> #include <vgc/core/object.h> #include <vgc/ui/api.h> #include <vgc/ui/key.h> #include <vgc/ui/modifierkey.h> #include <vgc/ui/mousebutton.h> namespace vgc::ui { /// \enum vgc::ui::ShortcutContext /// \brief Describes in what context a shortcut is active. /// /// This describes whether a shortcut is active application-wide, or only when /// the action is in the active window, or only when the action is owned by a /// widget that has the keyboard focus. /// enum class ShortcutContext : UInt8 { /// The shortcut is active application-wide. /// Application, /// The shortcut is active if the action is owned by a widget inside the /// active window. /// Window, /// The shortcut is active if the action is owned by a widget which has the /// keyboard focus. /// Widget }; VGC_UI_API VGC_DECLARE_ENUM(ShortcutContext) /// \enum vgc::ui::ShortcutType /// \brief Describes whether a shortcut is a mouse button press, a keyboard key press, etc. /// // TODO: // - DoubleClick? // - Activate on Press vs Release? // - Should the key/button be kept pressed during a drag action? // enum class ShortcutType : UInt8 { /// There is no shortcut. /// None, /// The shortcut is activated by pressing a keyboard key. /// Keyboard, /// The shortcut is activated by pressing a mouse button. /// Mouse }; VGC_UI_API VGC_DECLARE_ENUM(ShortcutType) /// \class vgc::ui::Shortcut /// \brief Represents a combination of keys that can trigger an action. /// /// A `Shortcut` is a combination of ModifiersKeys together with a `Key` or /// `MouseButton`. /// class VGC_UI_API Shortcut { public: /// Creates a shortcut of type `ShortcutType::None`. /// Shortcut() { } /// Creates a Shortcut with no modifier keys and key. /// Shortcut(Key key) { // intentional implicit constructor setKey(key); } /// Creates a Shortcut with the given modifier keys and key. /// Shortcut(ModifierKeys modifierKeys, Key key) { setModifierKeys(modifierKeys); setKey(key); } /// Creates a Shortcut with no given modifier keys and mouse button. /// Shortcut(MouseButton button) { // intentional implicit constructor setMouseButton(button); } /// Creates a Shortcut with the given modifier keys and mouse button. /// Shortcut(ModifierKeys modifierKeys, MouseButton button) { setModifierKeys(modifierKeys); setMouseButton(button); } /// Returns the type of this shortcut. /// ShortcutType type() const { return type_; } /// Returns the modifier keys of this shortcut. /// ModifierKeys modifierKeys() const { return modifierKeys_; } /// Sets the modifier keys of this shortcut. /// void setModifierKeys(ModifierKeys modifierKeys) { modifierKeys_ = modifierKeys; } /// Returns the key of this shortcut. /// Key key() const { return key_; } /// Sets the key of this shortcut. /// /// This changes the `type()` of this shortcut to `Keyboard` (unless the /// given `key` is `None`, in which case the `type()` becomes `None`). /// /// This also changes the `mouseButton()` to `None`. /// void setKey(Key key); /// Returns the mouse button of this shortcut. /// MouseButton mouseButton() const { return mouseButton_; } /// Sets the mouse button of this shortcut. /// /// This changes the `type()` of this shortcut to `Mouse` (unless the /// given `button` is `None`, in which case the `type()` becomes `None`). /// /// This also changes the `key()` to `None`. /// void setMouseButton(MouseButton button); /// Returns whether the shortcut is empty, that is, whether both `key()` /// and `mouseButton()` are `None`. /// bool isEmpty() const { return key() == Key::None && mouseButton() == MouseButton::None; } /// Returns whether the two shortcuts `s1` and `s2` are equal. /// friend constexpr bool operator==(const Shortcut& s1, const Shortcut& s2) { return s1.type_ == s2.type_ // && s1.modifierKeys_ == s2.modifierKeys_ // && s1.key_ == s2.key_ // && s1.mouseButton_ == s2.mouseButton_; } /// Returns whether the two shortcuts `s1` and `s2` are different. /// friend constexpr bool operator!=(const Shortcut& s1, const Shortcut& s2) { return !(s1 == s2); } private: ShortcutType type_ = ShortcutType::None; ModifierKeys modifierKeys_ = ModifierKey::None; Key key_ = Key::None; MouseButton mouseButton_ = MouseButton::None; }; namespace detail { std::string toString(const Shortcut& shortcut); } // namespace detail } // namespace vgc::ui template<> struct fmt::formatter<vgc::ui::Shortcut> : fmt::formatter<std::string_view> { template<typename FormatContext> auto format(const vgc::ui::Shortcut& shortcut, FormatContext& ctx) { std::string res = vgc::ui::detail::toString(shortcut); return fmt::formatter<std::string_view>::format(res, ctx); } }; template<> struct std::hash<vgc::ui::Shortcut> { std::size_t operator()(const vgc::ui::Shortcut& s) const noexcept { vgc::UInt64 x = s.modifierKeys().toUnderlying(); x <<= 32; x += vgc::core::toUnderlying(s.key()); return std::hash<vgc::UInt64>()(x); } }; namespace vgc::ui { VGC_DECLARE_OBJECT(ShortcutMap); using ShortcutArray = core::Array<Shortcut>; /// \class vgc::ui::ShortcutMap /// \brief Defines a mapping ("key bindings") between commands and shortcuts. /// /// A `ShortcutMap` defines a mapping (often called "key bindings") between /// `Command` objects and `Shortcut` objects. More precisely, it allows you to /// query, for any command (given by its command ID), what is the list of /// shortcuts that can be used to trigger the command. /// /// A shortcut map `m2` can "inherit" the shortcuts from another shortcut map /// `m1`. In this case, the shortcuts defined in `m1` are also available in /// `m2`. If shortcuts for a given command are explicitly defined in `m2`, then /// they override all the shortcuts defined in `m1`, and none of the shortcuts /// in `m1` for this command are available. /// class VGC_UI_API ShortcutMap : public core::Object { private: VGC_OBJECT(ShortcutMap, core::Object) protected: ShortcutMap(CreateKey, const ShortcutMap* inheritedMap); public: /// Creates a `ShortcutMap` object. If `inheritedMap` is not null, /// then the created `ShortcutMap` will inherit from this other map. /// static ShortcutMapPtr create(const ShortcutMap* inheritedMap = nullptr); /// Returns the shortcut map that this shortcut map inherits from, if /// any. /// /// For example, the "user" shortcut map typically inherits from the /// "default" shortcut map, which means that unless explicitly overriden, /// the shortcuts for a given command in the context of this map are the /// same as its shortcuts in the context of the other map. /// const ShortcutMap* inheritedMap() const { return inheritedMap_.getIfAlive(); } /// Returns whether this map contains the given command, ignoring /// inheritance. /// /// If this function returns `true`, you can use `get(commandId)` to /// get the corresponding shortcuts. /// /// If you want inheritance to be taken into account, use /// `contains(commandId)` instead. /// /// If `isSet(commandId)` returns `true`, then `contains(commandId)` also /// returns `true`. /// /// If `isSet(commandId)` returns `false`, then `contains(commandId)` may /// return either `false` or `true`, depending on the content of the /// inherited map, if any. /// /// \sa `get()`, `set()`, `contains()`. /// bool isSet(core::StringId commandId) const; /// Returns whether this map contains the given command, taking into /// account inheritance. /// /// If this function returns `true`, you can use `shortcut(commandId)` to /// get the corresponding shortcuts. /// /// If you want inheritance to be ignored, use `isSet(commandId)` instead. /// /// \sa `shortcuts()`, `isSet()`. /// bool contains(core::StringId commandId) const; /// Returns all the shortcuts bound to a given command, ignoring /// inheritance. /// /// If you want inheritance to be taken into account, use /// `shortcuts(commandId)` instead. /// /// \sa `set()`, `isSet()`, `shortcuts()`. /// const ShortcutArray& get(core::StringId commandId) const; /// Returns all the shortcuts bound to a given command, taking into account /// inheritance. /// /// If you want inheritance to be ignored, use `get(commandId)` instead. /// /// Note that if `isSet(commandId)` is `true`, then any shortcut defined in /// the inherited map are ignored: they are overriden by the shortcuts set /// in this map. /// /// Also note that if this function returns an empty array, this can either /// means that the command is not contained in the map, or that the command /// is explicitly mapped to "no shortcuts". /// /// \sa `get()`. /// const ShortcutArray& shortcuts(core::StringId commandId) const; /// Sets the shortcuts of the given command to be the given array of /// shortcuts. /// /// If this map inherits from another map, this means that all shortcuts /// assigned to the command in the other map are now inactive in the /// context of this map. /// /// After calling this function, `isSet(commandId)` returns `true` and both /// `get(commandId)` and `shortcuts(commandId)` return the given shortcuts. /// /// \sa `get()`, `isSet()`, `restore()`, `clear()`, `restore()`, `add()`, `remove()`. /// void set(core::StringId commandId, ShortcutArray shortcuts); /// This signal is emitted whenever some shortcuts have changed, whenever /// directly via `this->set()`, or indirectly via inheritance. /// VGC_SIGNAL(changed) /// Removes any previously `set()` shortcut on this map for the given /// command. /// /// If this map inherits from another map, this means that all shortcuts of /// the command in the context of this map are now the same than in the /// context of the other map. /// /// After calling this function, `isSet(commandId)` returns `false`, /// `get(commandId)` returns returns an empty array, and /// `shortcuts(commandId)` may or may not return an empty array depending /// on the content of the inherited map, if any. /// /// \sa `set()`. /// void restore(core::StringId commandId); /// Sets the shortcuts of the given command to be an empty array. /// /// This is equivalent to `set(commandId, {})`. /// /// If this map inherits from another map, this means that all shortcuts /// assigned to the command in the other map are now inactive in the /// context of this map. /// /// After calling this function, `isSet(commandId)` returns `true` and both /// `get(commandId)` and `shortcuts(commandId)` return an empty array. /// /// \sa `set()`. /// void clear(core::StringId commandId); /// Adds a shortcut for the given command. /// /// If this map inherits from another map, and the given command is not yet /// set in this map, then all shortcuts already bound to the command by /// inheritance are first copied into this map so that they are still /// active in the context of this map. /// /// After calling this function, `isSet(commandId)` returns `true` and /// `shortcuts(commandId)` returns the same array as it previously returned /// but with the given shortcut added. /// /// If the shortcut was already in `shortcuts(commandId)` then it is not /// added a second time (i.e., `shortcuts(commandId)` is unchanged), /// however this function may still have the side effect of changing /// `isSet(commandId)` from `false` to `true` /// /// \sa `set()`. /// void add(core::StringId commandId, const Shortcut& shortcut); /// Removes a shortcut for the given command. /// /// If this map inherits from another map, and the given command is not yet /// set in this map, then all shortcuts already bound to the command by /// inheritance are first copied into this map so that they are still /// active in the context of this map (except for the removed shortcut). /// /// After calling this function, `isSet(commandId)` return `true` and /// `shortcuts(commandId)` returns the same array as it previously returned /// but with the given shortcut removed. /// /// If the shortcut was not in `shortcuts(commandId)` then it is not /// removed (i.e., `shortcuts(commandId)` is unchanged), however this /// function may still have the side effect of changing `isSet(commandId)` /// from `false` to `true` /// /// \sa `set()`. /// void remove(core::StringId commandId, const Shortcut& shortcut); /// Returns the ID of all commands in this map. /// /// If `withInheritance` is `true` (the default), then inherited /// commands are also included. /// /// If `withInheritance` is `false`, then inherited /// commands are not included. /// core::Array<core::StringId> commands(bool withInheritance = true) const; // TODO: // searchByCommand(std::string_view pattern, bool withInheritance = true) // searchByShortcut(std::string_view pattern, bool withInheritance = true) private: ShortcutMapConstPtr inheritedMap_; std::unordered_map<core::StringId, ShortcutArray> shortcuts_; ShortcutArray noShortcuts_; // Same as commands(true) but appends the results to a set for performance void commands_(std::unordered_set<core::StringId>& out) const; }; /// Returns a global `ShortcutMap` object storing the default shortcuts. /// /// \relates `ShortcutMap` /// \relates `Shortcut` /// VGC_UI_API ShortcutMap* defaultShortcuts(); /// Returns all the default shortcuts bound to a given command. /// /// This is equivalent to `defaultShortcuts()->shortcuts(commandId)`. /// /// \relates `ShortcutMap` /// \relates `Shortcut` /// VGC_UI_API const ShortcutArray& defaultShortcuts(core::StringId commandId); /// Returns a global `ShortcutMap` object storing the user shortcuts. /// /// \relates `ShortcutMap` /// \relates `Shortcut` /// VGC_UI_API ShortcutMap* userShortcuts(); /// Returns all the user shortcuts bound to a given command. /// /// This is equivalent to `userShortcuts()->shortcuts(commandId)`. /// /// \relates `ShortcutMap` /// \relates `Shortcut` /// VGC_UI_API const ShortcutArray& userShortcuts(core::StringId commandId); class Command; namespace detail { struct VGC_UI_API ShortcutAdder { ShortcutAdder(ShortcutMap* map, core::StringId commandId, const Shortcut& shortcut); }; } // namespace detail } // namespace vgc::ui /// Adds a shortcut to the `defaultShortcuts()` for the given command. /// /// ```cpp /// VGC_UI_ADD_DEFAULT_SHORTCUT( /// save(), /// (vgc::ui::Key::S)) /// ``` /// /// ```cpp /// VGC_UI_ADD_DEFAULT_SHORTCUT( /// save(), /// (vgc::ui::ModifierKey::Ctrl, vgc::ui::Key::S)) /// ``` /// /// This can only be used in .cpp source files, not in header files. /// // clang-format off #define VGC_UI_ADD_DEFAULT_SHORTCUT(commandId, shortcut) \ static const ::vgc::ui::detail::ShortcutAdder VGC_PP_CAT(shortcutAdder_, __LINE__) \ (::vgc::ui::defaultShortcuts(), commandId, shortcut); // clang-format on #endif // VGC_UI_SHORTCUT_H
[ "noreply@github.com" ]
noreply@github.com
d693790bf0c2ae6195846611296ca0fda78f471c
0841c948188711d194835bb19cf0b4dae04a5695
/pushserver/pushtrack/sources/thelib/include/p2p/p2puser.h
627f69bf9a392745ff879bf062aff0364cdbc033
[]
no_license
gjhbus/sh_project
0cfd311b7c0e167e098bc4ec010822f1af2d0289
1d4d7df4e92cff93aba9d28226d3dbce71639ed6
refs/heads/master
2020-06-15T16:11:33.335499
2016-06-15T03:41:22
2016-06-15T03:41:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
380
h
#ifndef _P2PUSER_H_ #define _P2PUSER_H_ #include "common.h" #include "p2p/protocols/p2pprotocols.h" class P2PUser { public: P2PUser(); virtual ~P2PUser(); virtual bool Initialize() = 0; virtual std::string ToString(); P2PEndType endType_; uint32_t p2pID_; // low 12bit is udp port uint32_t proxyIP_; }; #endif // _P2PUSER_H_
[ "greatmiffa@gmail.com" ]
greatmiffa@gmail.com
37e24542b1eaf6404f337e1e4abff5c0670958d1
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Plugins/Messaging/UdpMessaging/Source/UdpMessaging/Private/Tests/UdpMessageTransportTest.cpp
b0dd94c814d574b8757b5227d3acd0590fdb211b
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C++
false
false
5,012
cpp
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "CoreMinimal.h" #include "Misc/Guid.h" #include "Misc/AutomationTest.h" #include "Interfaces/IPv4/IPv4Address.h" #include "Interfaces/IPv4/IPv4Endpoint.h" #include "IMessageContext.h" #include "IMessageTransportHandler.h" #include "Transport/UdpMessageTransport.h" #include "Tests/UdpMessagingTestTypes.h" IMPLEMENT_SIMPLE_AUTOMATION_TEST(FUdpMessageTransportTest, "System.Core.Messaging.Transports.Udp.UdpMessageTransport (takes ~2 minutes!)", EAutomationTestFlags::Disabled | EAutomationTestFlags::ApplicationContextMask | EAutomationTestFlags::EngineFilter) class FUdpMessageTransportTestState : public IMessageTransportHandler { public: FUdpMessageTransportTestState(FAutomationTestBase& InTest, const FIPv4Endpoint& UnicastEndpoint, const FIPv4Endpoint& MulticastEndpoint, uint8 MulticastTimeToLive) : NumReceivedMessages(0) , Test(InTest) { Transport = MakeShareable(new FUdpMessageTransport(UnicastEndpoint, MulticastEndpoint, MulticastTimeToLive)); } public: const TArray<FGuid>& GetDiscoveredNodes() const { return DiscoveredNodes; } const TArray<FGuid>& GetLostNodes() const { return LostNodes; } int32 GetNumReceivedMessages() const { return NumReceivedMessages; } bool Publish(const TSharedRef<IMessageContext, ESPMode::ThreadSafe>& Context) { return Transport->TransportMessage(Context, TArray<FGuid>()); } bool Start() { return Transport->StartTransport(*this); } void Stop() { Transport->StopTransport(); } public: //~ IMessageTransportHandler interface virtual void DiscoverTransportNode(const FGuid& NodeId) override { DiscoveredNodes.Add(NodeId); } virtual void ForgetTransportNode(const FGuid& NodeId) override { LostNodes.Add(NodeId); } virtual void ReceiveTransportMessage(const TSharedRef<IMessageContext, ESPMode::ThreadSafe>& Context, const FGuid& NodeId) override { FPlatformAtomics::InterlockedIncrement(&NumReceivedMessages); } private: TArray<FGuid> DiscoveredNodes; TArray<FGuid> LostNodes; int32 NumReceivedMessages; FAutomationTestBase& Test; TSharedPtr<IMessageTransport, ESPMode::ThreadSafe> Transport; }; bool FUdpMessageTransportTest::RunTest(const FString& Parameters) { const FIPv4Endpoint MulticastEndpoint(FIPv4Address(231, 0, 0, 1), 7777); const FIPv4Endpoint UnicastEndpoint = FIPv4Endpoint::Any; const uint8 MulticastTimeToLive = 0; const int32 NumTestMessages = 10000; const int32 MessageSize = 1280; // create transports FUdpMessageTransportTestState Transport1(*this, UnicastEndpoint, MulticastEndpoint, MulticastTimeToLive); const auto& DiscoveredNodes1 = Transport1.GetDiscoveredNodes(); FUdpMessageTransportTestState Transport2(*this, UnicastEndpoint, MulticastEndpoint, MulticastTimeToLive); const auto& DiscoveredNodes2 = Transport2.GetDiscoveredNodes(); // test transport node discovery Transport1.Start(); FPlatformProcess::Sleep(3.0f); TestTrue(TEXT("A single message transport must not discover any remote nodes"), DiscoveredNodes1.Num() == 0); Transport2.Start(); FPlatformProcess::Sleep(3.0f); if (DiscoveredNodes1.Num() == 0) { AddError(TEXT("The first transport did not discover any nodes")); return false; } if (DiscoveredNodes2.Num() == 0) { AddError(TEXT("The second transport did not discover any nodes")); return false; } TestTrue(TEXT("The first transport must discover exactly one node"), DiscoveredNodes1.Num() == 1); TestTrue(TEXT("The second transport must discover exactly one node"), DiscoveredNodes2.Num() == 1); TestTrue(TEXT("The discovered node IDs must be valid"), DiscoveredNodes1[0].IsValid() && DiscoveredNodes2[0].IsValid()); TestTrue(TEXT("The discovered node IDs must be unique"), DiscoveredNodes1[0] != DiscoveredNodes2[0]); if (HasAnyErrors()) { return false; } // stress test message sending FDateTime StartTime = FDateTime::UtcNow(); for (int32 Count = 0; Count < NumTestMessages; ++Count) { FUdpMockMessage* Message = new FUdpMockMessage(MessageSize); TSharedRef<IMessageContext, ESPMode::ThreadSafe> Context = MakeShareable(new FUdpMockMessageContext(Message)); Transport1.Publish(Context); } AddInfo(FString::Printf(TEXT("Sent %i messages in %s"), NumTestMessages, *(FDateTime::UtcNow() - StartTime).ToString())); while ((Transport2.GetNumReceivedMessages() < NumTestMessages) && ((FDateTime::UtcNow() - StartTime) < FTimespan::FromSeconds(120.0))) { FPlatformProcess::Sleep(0.0f); } AddInfo(FString::Printf(TEXT("Received %i messages in %s"), Transport2.GetNumReceivedMessages(), *(FDateTime::UtcNow() - StartTime).ToString())); TestTrue(TEXT("All sent messages must have been received"), Transport2.GetNumReceivedMessages() == NumTestMessages); return true; } void EmptyLinkFunctionForStaticInitializationUdpMessageTransportTest() { // This function exists to prevent the object file containing this test from being excluded by the linker, because it has no publicly referenced symbols. }
[ "tungnt.rec@gmail.com" ]
tungnt.rec@gmail.com
0e6c756f3f01b8d92611e98a57c14eb0d4f6f0dc
67bb57c136a7eceeff0544929782564967181eea
/CombineFileTogether/Neighbourhood.h
12a1f7aca61e3cf20942ec77422c869263a6baad
[]
no_license
WimpPgK/multiscale_modelling
aacfd615faab9e5a850c181b986b5596117ec146
966c5db2a83ca895f94af13b798fb63ca15c62b7
refs/heads/master
2020-04-05T07:13:19.753806
2020-01-16T01:27:02
2020-01-16T01:27:02
156,667,409
0
0
null
null
null
null
UTF-8
C++
false
false
512
h
#ifndef NEIGHBOURHOOD_H #define NEIGHBOURHOOD_H #include "Id.h" #include "Grain.h" #include "iostream" #include "Moore.h" #include "FurtherMoore.h" #include "NearestMoore.h" class Neighbourhood { public: Id** pom; Neighbourhood(); Id* getBestNeighbour(int, int, int, Grain*** ); Id* mostFrequentValue_NaiveAlgorithm(Id**, int, int); virtual ~Neighbourhood(); protected: private: void mostFrequentValue_NaiveAlgorithm(); }; #endif // NEIGHBOURHOOD_H
[ "potencjalny.m@gmail.com" ]
potencjalny.m@gmail.com
849ac73ff4a29e23070e621d4f244cce1e9b9467
ba48953d15005103d2b992ffc759a99a0c7ebf75
/Engine/Objects/ObjectFactory.cpp
9abe08932f485902a8f3764c1a96582b50afbaa7
[]
no_license
JordanLim-exe/GAT150
e878487d965939a072702910d7b4932a87fec70a
a16357ee597e06f693d6c5c6846c4c5e37504961
refs/heads/master
2022-12-13T13:46:27.628598
2020-09-02T00:56:32
2020-09-02T00:56:32
284,754,626
0
0
null
null
null
null
UTF-8
C++
false
false
938
cpp
#include "pch.h" #include "ObjectFactory.h" #include "Components/PhysicsComponent.h" #include "Components/SpriteComponent.h" #include "Components/SpriteAnimationComponent.h" #include "Components/RigidBodyComponent.h" #include "Components/AudioComponent.h" void nc::ObjectFactoryImpl::Initialize() { nc::ObjectFactory::Instance().Register("GameObject", new nc::Creator<GameObject, Object>); nc::ObjectFactory::Instance().Register("PhysicsComponent", new nc::Creator<PhysicsComponent, Object>); nc::ObjectFactory::Instance().Register("SpriteComponent", new nc::Creator<SpriteComponent, Object>); nc::ObjectFactory::Instance().Register("SpriteAnimationComponent", new nc::Creator<SpriteAnimationComponent, Object>); nc::ObjectFactory::Instance().Register("RigidBodyComponent", new nc::Creator<RigidBodyComponent, Object>); nc::ObjectFactory::Instance().Register("AudioComponent", new nc::Creator<AudioComponent, Object>); }
[ "JLim@student.neumont.edu" ]
JLim@student.neumont.edu
813a76eec9b52ed2daad0542977ae779816e5a41
ba0c73964b9f2db826cf80a150bdb027dbe49f0b
/libs/hmtslam/include/mrpt/hmtslam/CHMHMapNode.h
b216f8d55a4316876907072218c39eaa1d56e7b2
[ "BSD-3-Clause" ]
permissive
awesomeleo/mrpt
5e3ab477aa534f82e7e2917a8db43ff0734a0bfb
1e2c20c5493992e1425a887a9bfcaa76ab04447c
refs/heads/master
2021-01-15T10:52:23.650102
2014-08-27T16:38:38
2014-08-27T16:38:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,316
h
/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2014, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #ifndef CHMHMapNode_H #define CHMHMapNode_H #include <mrpt/utils/safe_pointers.h> #include <mrpt/slam/CSensoryFrame.h> #include <mrpt/hmtslam/HMT_SLAM_common.h> #include <mrpt/utils/CSerializable.h> #include <mrpt/utils/CMHPropertiesValuesList.h> #include <mrpt/utils/CTypeSelector.h> #include <map> namespace mrpt { namespace hmtslam { using namespace mrpt::slam; class HMTSLAM_IMPEXP CHierarchicalMHMap; class HMTSLAM_IMPEXP CHMHMapArc; DEFINE_SERIALIZABLE_PRE_CUSTOM_BASE_LINKAGE( CHMHMapNode,mrpt::utils::CSerializable, HMTSLAM_IMPEXP ) /** A class for representing a node in a hierarchical, multi-hypothesis map. * The node itself will be considered only if some given hypothesisID matchs its own ID. * \note Create objects by invoking the class factory "::Create" * * \sa CHierarchicalMHMap,CHMHMapArc * \ingroup mrpt_hmtslam_grp */ class HMTSLAM_IMPEXP CHMHMapNode : public mrpt::utils::CSerializable { friend class HMTSLAM_IMPEXP CHierarchicalMHMap; friend class HMTSLAM_IMPEXP CHierarchicalMHMapPartition; friend class HMTSLAM_IMPEXP CHMHMapArc; // This must be added to any CSerializable derived class: DEFINE_SERIALIZABLE( CHMHMapNode ) public: /** The type of the IDs of nodes. */ typedef mrpt::utils::TNodeID TNodeID; /** The hypothesis IDs under which this node exists. */ THypothesisIDSet m_hypotheses; protected: /** An unique identifier for the node: it is randomly generated at construction or read from stream when loaded. */ TNodeID m_ID; /** The list of all arcs from/to this node: */ TArcList m_arcs; /** Event handler for arc destruction: It should be only called for arcs from/to this node, altought other case must be handled without effects. * \note At *addition we use a smart pointer to assure all the implied guys use the same smrt. pnt., but at destructors the objects don't know anything but "this", thus the usage of plain pointers. */ void onArcDestruction(CHMHMapArc *arc); /** Event handler for arc addition: It should be only called for arcs from/to this node, altought other cases have no effects. */ void onArcAddition(CHMHMapArcPtr &arc); /** The hierarchical graph in which this object is into. */ safe_ptr<CHierarchicalMHMap> m_parent; private: /** Private constructor (see ::Create class factory) */ CHMHMapNode( CHierarchicalMHMap *parent = NULL, const THypothesisIDSet &hyps = THypothesisIDSet() ); public: /** Class factory */ static CHMHMapNodePtr Create( CHierarchicalMHMap *parent = NULL, const THypothesisIDSet &hyps = THypothesisIDSet() ); /** Destructor */ virtual ~CHMHMapNode(); /** The annotations of the node, see the general description of the class for possible properties and values. */ utils::CMHPropertiesValuesList m_annotations; /** The type of the node, the possibilities are: * - Place * - Area * - TopologicalMap * - Object */ utils::CTypeSelector m_nodeType; /** Reads the ID of the node (read-only property) */ TNodeID getID() const; /** The label of the node, only for display it to the user. */ std::string m_label; /** Returns the level of this node in the hierarchy of arcs "arcType_Belongs", where level=0 is the ground level, 1=its parents, etc. */ unsigned int getLevelInTheHierarchy(); /** Returns the number of arcs starting from/ending into this node. */ unsigned int getRelatedArcsCount(); /** Returns a list with the arcs from/to this node. */ void getArcs( TArcList &out ) const { out = m_arcs; } /** Returns a list with the arcs from/to this node existing in a given hypothesis ID. */ void getArcs( TArcList &out, const THypothesisID &hyp_id ) const; /** Returns a list with the arcs from/to this node existing in a given hypothesis ID and of a given type. */ void getArcs( TArcList &out, const char *arcType, const THypothesisID &hyp_id ) const; /** Check whether an arc exists towards the given area */ bool isNeighbor(const TNodeID &otherArea, const THypothesisID &hyp_id ) const; }; // End of class def. /** A map between node IDs and nodes (used in HMT-SLAM). * \sa CHMTSLAM */ typedef std::map<CHMHMapNode::TNodeID,CHMHMapNodePtr> TNodeList; typedef list_searchable<CHMHMapNode::TNodeID> TNodeIDList; typedef std::set<CHMHMapNode::TNodeID> TNodeIDSet; typedef std::pair<CHMHMapNode::TNodeID,CHMHMapNode::TNodeID> TPairNodeIDs; } // End of namespace } // End of namespace #endif
[ "joseluisblancoc@gmail.com" ]
joseluisblancoc@gmail.com
444b1c0c62ba1bbf93f86448d4d911cc9f14ef87
5dc78435c7f2e9422dd8bde8db9c9439a6e8a43a
/includes/helper.hpp
2e7cde3c2f64a4a490b325ece3d5b0bddd757fa6
[]
no_license
LucasCampos/LatticeGasCUDA
aa74b0b5511a34895716b89b33faea57c72a99f0
f51c5210f421ca965f9a736d24aba75344c1dcce
refs/heads/master
2021-01-10T16:54:21.924115
2013-03-05T13:08:26
2013-03-05T13:08:26
8,384,941
1
0
null
null
null
null
UTF-8
C++
false
false
1,875
hpp
#ifndef HELPER_HPP #define HELPER_HPP #include <GL/glew.h> #include <GL/glfw.h> #include <cuda_gl_interop.h> #include <cstdio> #define HANDLE_ERROR( err ) (HandleError( err, __FILE__, __LINE__ )) inline int ConvertSMVer2Cores(int major, int minor) { // Defines for GPU Architecture types (using the SM version to determine the # of cores per SM typedef struct { int SM; // 0xMm (hexidecimal notation), M = SM Major version, and m = SM minor version int Cores; } sSMtoCores; sSMtoCores nGpuArchCoresPerSM[] = { { 0x10, 8 }, { 0x11, 8 }, { 0x12, 8 }, { 0x13, 8 }, { 0x20, 32 }, { 0x21, 48 }, { -1, -1 } }; int index = 0; while (nGpuArchCoresPerSM[index].SM != -1) { if (nGpuArchCoresPerSM[index].SM == ((major << 4) + minor) ) { return nGpuArchCoresPerSM[index].Cores; } index++; } std::cout << "MapSMtoCores undefined SMversion" << major << "." << minor <<std::endl; return -1; } static void HandleError( cudaError_t err, const char *file, int line ) { if (err != cudaSuccess) { printf( "%s in %s at line %d\n", cudaGetErrorString( err ), file, line ); exit( EXIT_FAILURE ); } } GLuint createVBO(const void* data, int dataSize, GLenum target, GLenum usage) { GLuint id = 0; // 0 is reserved, glGenBuffersARB() will return non-zero id if success glGenBuffers(1, &id); // create a vbo glBindBuffer(target, id); // activate vbo id to use glBufferData(target, dataSize, data, usage); // upload data to video card // check data size in VBO is same as input array, if not return 0 and delete VBO int bufferSize = 0; glGetBufferParameteriv(target, GL_BUFFER_SIZE, &bufferSize); if(dataSize != bufferSize) { glDeleteBuffers(1, &id); id = 0; std::cout << "[createVBO()] Data size is mismatch with input array\n"; } return id; // return VBO id } #endif
[ "lqcc@df.ufpe.br" ]
lqcc@df.ufpe.br
29b5adf61dd917d0f0b267069cec59d1fd236826
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/extensions/browser/api/declarative_net_request/ruleset_checksum.cc
ea3e7717add470c826b1e76b7f24ea6511361973
[ "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
493
cc
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/browser/api/declarative_net_request/ruleset_checksum.h" namespace extensions { namespace declarative_net_request { RulesetChecksum::RulesetChecksum(RulesetID ruleset_id, int checksum) : ruleset_id(ruleset_id), checksum(checksum) {} } // namespace declarative_net_request } // namespace extensions
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
9b1db2a528f7d7f23b727b6a3898b069d28d60e2
6dbe15afeef125057e7d331606e3be9c5d510e5c
/Game/Monster/cGiantEyes.h
a757e5d96a91aefc0ab14aaf273fd4afa3e03f92
[]
no_license
adwel94/2D_PROJECT_SERVER
428ef32ae233eb25f84c2fd07d6a7139e30be5f3
426ae3d5b90f61b3053177c3b8c427bec2ebbee8
refs/heads/master
2022-11-29T19:33:43.485282
2020-08-19T08:45:22
2020-08-19T08:45:22
257,766,749
1
0
null
null
null
null
UHC
C++
false
false
674
h
#pragma once #ifndef _GIANT_EYES_H_ #define _GIANT_EYES_H_ #include "Monster.h" namespace GAME { namespace Monster { //자이언트(이블) 아이 - 근거리 몬스터 class cGiantEyes : public cMonster { int mStopFrame; public: cGiantEyes(Utilities::CODE _code, float _left, float _right, float _x, float _y, Map::cDungeon* _dungeon); // cMonster을(를) 통해 상속됨 //1프레임당 실행되는 함수 void Update() override; int Type() { return CODE::MOB::GIANT_EYES; } bool AroundCheck(); bool AttackCheck(); // cMonster을(를) 통해 상속됨 virtual void SendState() override; }; } } #endif // !_GIANT_EYES_H_
[ "hun4159@naver.com" ]
hun4159@naver.com
e92a1da95a16f56a14a6bfa27c4f6d093cd45aa3
3e53a2242d0447b537c0fdda6671319a690b4df2
/src/ProfileDialog.cpp
04e4f6f7ce0d96c164b1bee83d7ee0e4c43713b4
[]
no_license
emsr/PMRS
2bbfe6c433f9edc454e18b056bfe0bd2b1963f01
e3b8d806c56f721cbdcd16c4fb5f0be668b68151
refs/heads/master
2021-04-30T05:29:04.214350
2018-02-15T02:43:02
2018-02-15T02:43:02
121,416,858
2
1
null
null
null
null
UTF-8
C++
false
false
262
cpp
#include "ProfileDialog.h" /// /// @brief /// ProfileDialog::ProfileDialog( QWidget * parent ) : QDialog( parent ) { setupUi( this ); return; } /// /// @brief /// void ProfileDialog::accept( void ) { QDialog::accept(); return; }
[ "3dw4rd@verizon.net" ]
3dw4rd@verizon.net
9960d1668355b9ec25201c2f0a234eefef78dae3
5771ef829d7bd8d8e5531f8ea7f7437762b1ff0e
/sinuca/util/Vetor.cpp
d4779d055d52ce8d050bc1426e148b7fcb0c28a3
[]
no_license
democrito88/sinuca
31591039436fb458a7306db7df11c0cf12c0ef15
ec46fc93db16a309ccd16a844aa1b2c6c78afee6
refs/heads/master
2020-09-22T14:28:44.943441
2019-12-01T22:21:16
2019-12-01T22:21:16
225,239,489
0
0
null
null
null
null
UTF-8
C++
false
false
508
cpp
#include "Vetor.h" Vetor::Vetor() { this->x = 0; this->y = 0; } Vetor::Vetor(float x, float y) { this->x = x; this->y = y; } float Vetor::getModulo() { float quadrado = pow(this->x, 2) + pow(this->y, 2); float res = sqrtf(quadrado); return res; } Vetor Vetor::getVetUnitario() { float tam = getModulo(); if(tam == 0.0f) tam = 1.0f; return Vetor(this->x/tam, this->y/tam); } void Vetor::operator = (Vetor v) { this->x = v.x; this->y = v.y; }
[ "Rodrigo@LAPTOP-C9BAQJPG" ]
Rodrigo@LAPTOP-C9BAQJPG
5acd29c36f1327f9d7b080a350bb0f1e1f33ae7c
af0ecafb5428bd556d49575da2a72f6f80d3d14b
/CodeJamCrawler/dataset/08_12364_50.cpp
010aa0e8b77f8645aa59b75abc1112f4cde16e4f
[]
no_license
gbrlas/AVSP
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
e259090bf282694676b2568023745f9ffb6d73fd
refs/heads/master
2021-06-16T22:25:41.585830
2017-06-09T06:32:01
2017-06-09T06:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
656
cpp
#include<iostream> #include<string> #include<map> using namespace std; string name[110]; map<string,int> mm; char ss[120]; string a; int main() { int n,m,T,i,j,P = 1; scanf("%d",&T); while(T--){ scanf("%d",&n); getchar(); for(i =1; i <= n; i ++){ gets(ss); name[i] = ss; } scanf("%d",&m); getchar(); int nnum = 0; int cc = 0; for(i =0; i < m ; i ++){ gets(ss); a = ss; if(mm[a] == 0){ mm[a] ++; cc ++; } if(cc == n){ cc = 1; nnum ++; mm.clear(); mm[a] ++; } } printf("Case #%d: %d\n",P++,nnum); mm.clear(); } return 0; }
[ "nikola.mrzljak@fer.hr" ]
nikola.mrzljak@fer.hr
875a038ef22a082b85cc9026b030bf46a4b70d3a
e597738a4e1898fbbdd5a6ef19750c3ba3dec0e3
/Source.cpp
d4803adca90fe4afccf42b08e187b3b75db2f40e
[]
no_license
BOHDAN1329/lab_02
60b4e7996eb83ffbbfbc819d8e37487a082e6d07
7a5caf0e8cac4c9c0f41a7f2865ce004b31f5651
refs/heads/master
2023-08-15T10:28:41.912071
2021-09-23T21:54:23
2021-09-23T21:54:23
409,735,964
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
668
cpp
//Lab_02.tpp // < Паньків Богдан > // Лабораторна робота №2.1 // Лінійні Прорграми // Варіант 17 # include <iostream> # include <cmath> using namespace std; int main() { double m; // віхдний параметр //double z1; // результат обчислення першого виразу double z2; // результат обчислення другого виразу cout << "m = "; cin >> m; //z1 = (sqrt((3 * m + 2) * (3 * m + 2) - 24 * m)) / (3 * sqrt(m) - 2. / sqrt(m)); z2 = sqrt(m); //cout << "z1 = " << z1 << endl; cout << "z2 = " << z2 << endl; cin.get(); return 0; }
[ "bpankiv011@gmail.com" ]
bpankiv011@gmail.com
00cc29963d2879878b15131177aff1b6a83529d4
a9d952738359e0c7b4bc7ac818dded34736ad3aa
/Lattice.h
4f2352aec48a773474a1a9af416f0c74fe4117fb
[ "BSD-3-Clause" ]
permissive
bedrin/crelax
5fc38158e3cb6e75a27f33f63fd4eb8a8aa7ff68
7a37728c6397d4d254cb0796c4a12db11663bde0
refs/heads/master
2022-06-30T07:12:03.113923
2022-06-09T21:21:35
2022-06-09T21:21:35
27,145,223
6
0
null
null
null
null
UTF-8
C++
false
false
817
h
// Lattice.h: interface for the Lattice class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_LATTICE_H__F791D765_7274_4695_9F7E_E199FA5A8452__INCLUDED_) #define AFX_LATTICE_H__F791D765_7274_4695_9F7E_E199FA5A8452__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <deque> #include <algorithm> #include "AtomPair.h" class Lattice { public: void calculateAtomNeighbours(const double maximumDistance); std::deque<Atom*> atoms; double a0; Lattice() {}; virtual ~Lattice(); long getNumberOfMoveableAtoms(); long getNumberOfAtoms(); /*std::deque<AtomPair> getMoveableNeighbourAtoms(const double maximumDistance); void sortAtomsMoveableFirst();*/ }; #endif // !defined(AFX_LATTICE_H__F791D765_7274_4695_9F7E_E199FA5A8452__INCLUDED_)
[ "Dmitry.Bedrin@gmail.com" ]
Dmitry.Bedrin@gmail.com
9fa1d3f2183fcd678f092bfa15b7dc954f55b97e
a2fa5eac0bdb44f12c1772112b472157f22ed08a
/wordtree.cpp
fb116eab69633eac6b574a8f7b64ed34eca7c11c
[]
no_license
karim-benlghalia/Project6-Words-do-grow-on-Trees
3300808baeea99fec900ddba54d0be0093ea421c
080b150e566acb0ac6fa460e5f891426767d77e7
refs/heads/master
2023-03-29T00:48:04.507660
2021-03-23T19:12:20
2021-03-23T19:12:20
350,590,586
0
0
null
null
null
null
UTF-8
C++
false
false
1,912
cpp
#include"wordtree.h" #include<iostream> #include <fstream> #include <string> #include <vector> using namespace std; void WordTree::add(std::ifstream&inp){ char c; string word = ""; while (inp.peek() != EOF){ inp.get(c); if (isalpha(c) || c == '\''){ c = (tolower(c)); word = word + c; } else { if (!word.empty()){ Insert(root, word); word = ""; } } } } void WordTree::Insert(WordNode*& nodeptr, string item) { if (nodeptr == nullptr){ nodeptr = new WordNode(item); return; } else { if (nodeptr->word == item){ nodeptr->WordTracker += 1; return; } else if (item < nodeptr->word) Insert(nodeptr->left, item); else Insert(nodeptr->right, item); } } void WordTree::PrintTree(WordNode* nodeptr, std::ostream&out) { if (nodeptr == nullptr) return; //in order (left - Current - Right) PrintTree(nodeptr->left, out); out << nodeptr->word << " " << nodeptr->WordTracker << endl; PrintTree(nodeptr->right, out); } int WordTree::CountNodes() const{ return sizeOfNodes(root); } int WordTree::sizeOfNodes(WordNode* nodeptr) const{ if (nodeptr == nullptr) return 0; else return 1 + sizeOfNodes(nodeptr->left) + sizeOfNodes(nodeptr->right);// pre-order (Current - Left - Right) } int WordTree::countTotal() const{ return NumberWord(root); } int WordTree::NumberWord(WordNode* nodeptr) const{ if (nodeptr == nullptr) return 0; else return NumberWord(nodeptr->left) + (nodeptr->WordTracker) + NumberWord(nodeptr->right); } WordTree::~WordTree(){ deleteNodes(root); } void WordTree::deleteNodes(WordNode*nodeptr){ if (nodeptr != nullptr){ deleteNodes(nodeptr->left); deleteNodes(nodeptr->right); // post-order (Left-Right-Current) delete nodeptr; } } ostream& operator<<(ostream& os, WordTree& WT){ WT.printS(os); return os; } void WordTree::printS(std::ostream&out){ PrintTree(root, out); }
[ "k.benlghalia@gmail.com" ]
k.benlghalia@gmail.com
ddcaff0dc530128c6e671b0954de710c43cc73f8
028cbe18b4e5c347f664c592cbc7f56729b74060
/v2/admin-gui/src/docroot/jbi/inc/clusterTypeFilter.inc
732180db76a61b7c8f609eff2ba54762aa0f315c
[]
no_license
dmatej/Glassfish-SVN-Patched
8d355ff753b23a9a1bd9d7475fa4b2cfd3b40f9e
269e29ba90db6d9c38271f7acd2affcacf2416f1
refs/heads/master
2021-05-28T12:55:06.267463
2014-11-11T04:21:44
2014-11-11T04:21:44
23,610,469
1
0
null
null
null
null
UTF-8
C++
false
false
1,992
inc
<!-- DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. The contents of this file are subject to the terms of either the GNU General Public License Version 2 only ("GPL") or the Common Development and Distribution License("CDDL") (collectively, the "License"). You may not use this file except in compliance with the License. You can obtain a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific language governing permissions and limitations under the License. When distributing the software, include this License Header Notice in each file and include the License file at glassfish/bootstrap/legal/LICENSE.txt. Sun designates this particular file as subject to the "Classpath" exception as provided by Sun in the GPL Version 2 section of the License file that accompanied this code. If applicable, add the following below the License Header, with the fields enclosed by brackets [] replaced by your own identifying information: "Portions Copyrighted [year] [name of copyright owner]" Contributor(s): If you wish your version of this file to be governed by only the CDDL or only the GPL Version 2, indicate your decision by adding "[Contributor] elects to include this software in this distribution under the [CDDL or GPL Version 2] license." If you don't indicate a single choice of license, a recipient has the option to distribute your version of this file under either the CDDL, the GPL Version 2 or to extend the choice of license to its licensees as provided above. However, if you add GPL Version 2 code and therefore, elected the GPL Version 2 license, then the option applies only if the new code is made subject to such option by the copyright holder. --> <!-- jbi/inc/clusterTypeFilter.inc --> <!-- deprecated: replaced by: (1) jbi/cluster/inc/clusterTypeFilter.inc -->
[ "kohsuke@6f3ba3e3-413c-0410-a8aa-90bee3ab43b5" ]
kohsuke@6f3ba3e3-413c-0410-a8aa-90bee3ab43b5
dfd435736b827f7f596d000143c9dab152ac8ed8
27b44958010a68bca9b116c9bc5948d297395b3c
/FishingJoy/Classes/FishingEntityLayer.h
8ad954922d8752d842cffac01c1a758cf5747c5c
[]
no_license
sky94520/FishingJoy
a356db1beb3abc99c78de7b64532abc457c4e436
4e4f837d7aeb825456adc4b08c7499186632679b
refs/heads/master
2022-01-24T22:20:35.329527
2019-07-21T02:08:49
2019-07-21T02:08:49
198,001,655
0
0
null
null
null
null
UTF-8
C++
false
false
936
h
#ifndef __FishingEntityLayer_H__ #define __FishingEntityLayer_H__ #include<list> #include "SDL_Engine/SDL_Engine.h" using namespace SDL; using namespace std; class Fish; class FishingNet; class FishingEntity; class FishingEntityLayerDelegate { public: virtual ~FishingEntityLayerDelegate(){} virtual void fireEnd()=0; }; class FishingEntityLayer:public Layer { private: list<FishingEntity*> m_fishingEntitys; FishingEntityLayerDelegate*m_pDelegate; public: FishingEntityLayer(); ~FishingEntityLayer(); CREATE_FUNC(FishingEntityLayer); bool init(); void update(float dt); void setDelegate(FishingEntityLayerDelegate*pDelegate); //添加FishingNet void addFishingNet(int lv,const Point&pos,float rotation); //添加激光 void addLaser(const Point&pos,float rotation); //添加珍珠弹 void addPearl(const Point&pos,float rotation); //添加迷雾 void addFog(Fish*fish,const Point&pos,float rotation); }; #endif
[ "541052067@qq.com" ]
541052067@qq.com
bbc44c64100600eb8a630b7dc8a03216942529d7
4576badf950ed9adafdfc1960aedb62a157f5cd8
/AV7/AV7Z4.cpp
73003fa61857d253ae722324d952e1a267b02585
[]
no_license
zayim/ProgrammingIntro
e5ed63b0c5bd12e57d4b28c03ff6df341b2085b2
5d3002e8e9049c60bde2fac3d7a0c89850befd0f
refs/heads/master
2020-04-05T23:25:04.631754
2016-09-20T22:29:13
2016-09-20T22:29:13
68,758,527
0
0
null
null
null
null
UTF-8
C++
false
false
405
cpp
#include <iostream> using namespace std; int main() { int a[100],b[100],n,phi=0,i,j; cout << "Unesi n: "; cin >> n; cout << "Unesi niz: "; for (i=0; i<n; i++) { cin >> a[i]; phi=2; for (j=2; j<a[i]; j++) if (!(a[i]%j)) phi++; b[i]=phi; } cout << "Novi niz: "; for (i=0; i<n; i++) cout << b[i] << " "; return 0; }
[ "zayim92@gmail.com" ]
zayim92@gmail.com
cf9ead4449e2dae2b5d0ce948ee2e8a6998533a2
8fb8419bec69c7e1feb7b99220e5c8fafe7c38b9
/paddle/fluid/pybind/op_function_generator.cc
62f1de35ae602b7c800a88de323e22d812bfeb4f
[ "Apache-2.0" ]
permissive
yongqiangma/Paddle
625fba02e9bc91da1db5d318285d68a86dfa67bd
fd3c6146804f9055c36622ed8b9f5f4f6ad6a058
refs/heads/develop
2021-05-19T04:41:16.862433
2020-04-28T03:10:32
2020-04-28T03:10:32
251,531,234
0
0
Apache-2.0
2020-04-28T03:14:48
2020-03-31T07:30:47
C++
UTF-8
C++
false
false
10,298
cc
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <algorithm> #include <fstream> #include <iostream> #include <string> #include "paddle/fluid/framework/op_info.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/framework/operator.h" #include "paddle/fluid/framework/variable.h" #include "paddle/fluid/pybind/pybind.h" #include "paddle/fluid/string/string_helper.h" std::map<std::string, std::set<std::string>> op_ins_map = { {"layer_norm", {"X", "Scale", "Bias"}}, {"gru_unit", {"Input", "HiddenPrev", "Weight", "Bias"}}, {"label_smooth", {"X", "PriorDist"}}, {"assign", {"X"}}, }; std::map<std::string, std::set<std::string>> op_passing_out_map = { {"sgd", {"ParamOut"}}, {"adam", {"ParamOut", "Moment1Out", "Moment2Out", "Beta1PowOut", "Beta2PowOut"}}, {"momentum", {"ParamOut", "VelocityOut"}}, {"batch_norm", {"MeanOut", "VarianceOut"}}, {"accuracy", {"Correct", "Total"}}, {"fill_constant", {"Out"}}, {"matmul", {"Out"}}}; // clang-format off const char* OUT_INITIALIZER_TEMPLATE = R"({"%s", {std::shared_ptr<imperative::VarBase>(new imperative::VarBase(tracer->GenerateUniqueName()))}})"; const char* OUT_DUPLICABLE_INITIALIZER_TEMPLATE = R"({"%s", ConstructDuplicableOutput(%s)})"; const char* INPUT_INITIALIZER_TEMPLATE = R"({"%s", {%s}})"; const char* INPUT_LIST_INITIALIZER_TEMPLATE = R"({"%s", %s})"; const char* INPUT_INITIALIZER_TEMPLATE_WITH_NULL = R"( if (%s != nullptr) { ins["%s"] = {%s}; } )"; const char* INPUT_INITIALIZER_TEMPLATE_WITH_NULL_LIST = R"( if (%s != nullptr) { ins["%s"] = %s; } )"; // if inputs is list, no need {} const char* ARG_OUT_NUM = R"(%sNum)"; const char* ARG_OUT_NUM_TYPE = R"(size_t )"; const char* VAR_TYPE = R"(std::shared_ptr<imperative::VarBase>)"; const char* VAR_LIST_TYPE = R"(std::vector<std::shared_ptr<imperative::VarBase>>)"; const char* ARG_TEMPLATE = R"(const %s& %s)"; const char* RETURN_TUPLE_TYPE = R"(std::tuple<%s>)"; const char* RETURN_TYPE = R"(%s)"; const char* RETURN_TUPLE_TEMPLATE = R"(std::make_tuple(%s))"; const char* RETURN_LIST_TEMPLATE = R"(outs["%s"])"; const char* RETURN_TEMPLATE = R"(outs["%s"][0])"; const char* FUNCTION_ARGS = R"(%s, const py::args& args)"; const char* FUNCTION_ARGS_NO_INPUT = R"(const py::args& args)"; const char* OP_FUNCTION_TEMPLATE = R"( %s %s(%s) { framework::AttributeMap attrs; ConstructAttrMapFromPyArgs(&attrs, args); { py::gil_scoped_release release; auto tracer = imperative::GetCurrentTracer(); imperative::NameVarBaseMap outs = %s; imperative::NameVarBaseMap ins = %s; %s tracer->TraceOp("%s", ins, outs, attrs); return %s; } })"; const char* PYBIND_ITEM_TEMPLATE = R"( %s.def("%s", &%s);)"; // clang-format on static inline bool FindInputInSpecialization(const std::string& op_type, const std::string& in_name) { return op_ins_map[op_type].count(in_name); } static inline bool FindOutoutInSpecialization(const std::string& op_type, const std::string& out_name) { return op_passing_out_map[op_type].count(out_name); } static std::tuple<std::vector<std::string>, std::vector<std::string>> GenerateOpFunctions(const std::string& module_name) { auto& op_info_map = paddle::framework::OpInfoMap::Instance().map(); std::vector<std::string> op_function_list, bind_function_list; auto& all_kernels = paddle::framework::OperatorWithKernel::AllOpKernels(); for (auto& pair : op_info_map) { auto& op_info = pair.second; auto op_proto = op_info.proto_; if (op_proto == nullptr) { continue; } auto& op_type = op_proto->type(); // Skip ooerator which is not inherit form OperatorWithKernel, like while, // since only OperatorWithKernel can run in dygraph mode. if (!all_kernels.count(op_type)) { continue; } std::string input_args = ""; std::string ins_initializer = "{"; std::string ins_initializer_with_null = ""; std::string py_arg = ""; for (auto& input : op_proto->inputs()) { auto& in_name = input.name(); // skip those dispensable inputs, like ResidualData in conv2d if (input.dispensable() && !FindInputInSpecialization(op_type, in_name)) { continue; } const auto in_type = input.duplicable() ? VAR_LIST_TYPE : VAR_TYPE; auto input_arg = paddle::string::Sprintf(ARG_TEMPLATE, in_type, in_name); input_args += input_arg; input_args += ","; if (input.dispensable()) { const auto in_template = input.duplicable() ? INPUT_INITIALIZER_TEMPLATE_WITH_NULL_LIST : INPUT_INITIALIZER_TEMPLATE_WITH_NULL; ins_initializer_with_null += paddle::string::Sprintf(in_template, in_name, in_name, in_name); } else { const auto in_template = input.duplicable() ? INPUT_LIST_INITIALIZER_TEMPLATE : INPUT_INITIALIZER_TEMPLATE; ins_initializer += paddle::string::Sprintf(in_template, in_name, in_name); ins_initializer += ","; } } if (ins_initializer.back() == ',') { ins_initializer.pop_back(); } ins_initializer += "}"; if (input_args.back() == ',') { input_args.pop_back(); } // Generate outs initializer std::string outs_initializer = "{"; std::string return_type = ""; std::string return_str = ""; int outs_num = 0; for (auto& output : op_proto->outputs()) { if (output.dispensable()) { continue; } const auto out_type = output.duplicable() ? VAR_LIST_TYPE : VAR_TYPE; const auto return_template = output.duplicable() ? RETURN_LIST_TEMPLATE : RETURN_TEMPLATE; auto& out_name = output.name(); std::string out_initializer_str; if (FindOutoutInSpecialization(op_type, out_name)) { if (input_args != "") { input_args += ","; } input_args += out_type; input_args += out_name; const auto out_template = output.duplicable() ? INPUT_LIST_INITIALIZER_TEMPLATE : INPUT_INITIALIZER_TEMPLATE; out_initializer_str += paddle::string::Sprintf(out_template, out_name, out_name); } else { // There are few Operators that have duplicable output, like `Out` in // split op. We need to specify the number of variables for the // duplicable output, as the argument OutNum; if (output.duplicable()) { if (input_args != "") { input_args += ","; } auto out_num_str = paddle::string::Sprintf(ARG_OUT_NUM, out_name); input_args += ARG_OUT_NUM_TYPE; input_args += out_num_str; out_initializer_str = paddle::string::Sprintf( OUT_DUPLICABLE_INITIALIZER_TEMPLATE, out_name, out_num_str); } else { out_initializer_str = paddle::string::Sprintf(OUT_INITIALIZER_TEMPLATE, out_name); } } return_type += out_type; return_type += ","; return_str += paddle::string::Sprintf(return_template, out_name); return_str += ","; outs_num += 1; outs_initializer += out_initializer_str; outs_initializer += ","; } if (outs_initializer.back() == ',') { outs_initializer.pop_back(); return_type.pop_back(); return_str.pop_back(); } outs_initializer += "}"; if (outs_num == 0) { return_type = "void"; } if (outs_num > 1) { return_str = paddle::string::Sprintf(RETURN_TUPLE_TEMPLATE, return_str); return_type = paddle::string::Sprintf(RETURN_TUPLE_TYPE, return_type); } std::string function_args = ""; if (input_args == "") { function_args = paddle::string::Sprintf(FUNCTION_ARGS_NO_INPUT, input_args); } else { function_args = paddle::string::Sprintf(FUNCTION_ARGS, input_args); } std::string func_name = "imperative_" + op_type; // generate op funtcion body auto op_function_str = paddle::string::Sprintf( OP_FUNCTION_TEMPLATE, return_type, func_name, function_args, outs_initializer, ins_initializer, ins_initializer_with_null, op_type, return_str); // generate pybind item auto bind_function_str = paddle::string::Sprintf( PYBIND_ITEM_TEMPLATE, module_name, op_type, func_name); op_function_list.emplace_back(std::move(op_function_str)); bind_function_list.emplace_back(std::move(bind_function_str)); } return std::make_tuple(op_function_list, bind_function_list); } int main(int argc, char* argv[]) { if (argc != 2) { std::cerr << "argc must be 2" << std::endl; return -1; } std::vector<std::string> headers{"\"paddle/fluid/imperative/tracer.h\""}; std::ofstream out(argv[1], std::ios::out); out << "#pragma once\n\n"; for (auto& header : headers) { out << "#include " + header + "\n"; } auto op_funcs = GenerateOpFunctions("m"); out << "namespace py = pybind11;" << "\n"; out << "namespace paddle {\n" << "namespace pybind {\n"; out << paddle::string::join_strings(std::get<0>(op_funcs), '\n'); out << "\n\n"; out << "inline void BindOpFunctions(pybind11::module *module) {\n" << " auto m = module->def_submodule(\"ops\");\n\n"; out << paddle::string::join_strings(std::get<1>(op_funcs), '\n'); out << "\n"; out << "}\n\n" << "} // namespace pybind\n" << "} // namespace paddle\n"; out.close(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
34794c80fc47338e2e71759738d98c3e1b34973f
286a3b61feec58c992ceda8f1ce28b8e4db5caf5
/vsci/tp5/src/douglas_peuker.cpp
e4ddf9b2318a839b04f3a981e6212157d593e475
[]
no_license
confiture/M2
970865ab3a52c5c65a84637f987dc27d6485542d
e95ca27c1eccd36337348ff042b8db144c08f0d5
refs/heads/master
2021-01-22T07:32:37.900029
2017-11-06T13:07:58
2017-11-06T13:07:58
1,020,201
1
0
null
null
null
null
ISO-8859-1
C++
false
false
7,607
cpp
/////////////////////////////////////////////////////////////////// // TP - Simplification de lignes polygonale par l'algorithme // de Douglas-Peuker // Squelette de programme C++ // compilation : g++ douglas_peuker.cpp -o douglas_peuker // exécution : ./douglas_peuker /////////////////////////////////////////////////////////////////// #include<cstdio> #include<cmath> #include<list> #include<iostream> #include<cstdlib> #include<cstring> #include <limits> #include <fstream> #ifndef ABS #define ABS(x) ((x)<0 ? -(x) : (x)) #endif #ifndef MIN #define MIN(x,y) ((x)<(y) ? (x) : (y)) #endif #ifndef MAX #define MAX(x,y) ((x)>(y) ? (x) : (y)) #endif using namespace std; /////////////////////////////////////////////////////////////////// // DEFINITION DES STRUCTURES DE DONNEES /////////////////////////////////////////////////////////////////// // type Point2 : point du plan struct Point2 { double x,y; // constructeurs Point2() { x=y=0.0; } Point2(double x0, double y0) { x=x0; y=y0; } }; typedef list<Point2> lPoints; double dist(Point2 p1,Point2 p2){ return sqrt((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y)); } /** *Exécute l'algorithme de Douglas-Parker pour la distance d sur la liste de points lpts. *Lorsque la procédure est lancée, deb doit pointer sur le premier élément de la liste, *et fin doit pointer sur le dernier élément de la liste et non sur lpts.end(). */ void douglas(double d,std::list<Point2> & lpts,std::list<Point2>::iterator deb,std::list<Point2>::iterator fin){ if(deb!=fin){ double a,b,h,l,s,dj; dj=0; std::list<Point2>::iterator it=deb; std::list<Point2>::iterator ptLoin=deb; it++; if(it!=fin){ while(it!=fin){ a=dist((*deb),(*it)); b=dist((*fin),(*it)); l=dist((*deb),(*fin)); s=(a*a-b*b+l*l)/(2*l); if(0<=s && s<=l){ h=sqrt(a*a-s*s); } else if(s<0){ h=a; } else{ h=b; } if(h>dj){ dj=h; ptLoin=it; } it++; } if(dj<d){ it=deb; it++; lpts.erase(it,fin); } else{ douglas(d,lpts,deb,ptLoin); douglas(d,lpts,ptLoin,fin); } } } } /////////////////////////////////////////////////////////////////// // ROUTINES D'ENTREE-SORTIE SOUS FORME DE FICHIER /////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////// // création d'un fichier image à partir d'une polyline P // (polygone ouvert ou fermé) // Entrée : nom_f = nom du fichier // P = liste des points de la polyline // echelle = réel > 0 // si d est le diamètre de la liste de points P // (d = plus grande distance entre deux points de P) // alors la taille du fichier image sera de d*echelle/1200 pouces // ou bien environ d*echelle/480 cm // couleur = entier entre 0 et 7 (cf. couleurs prédéfinies ci-dessous) // format_image = "eps", "jpeg" ou "gif" #define XFIG_COLOR_BLACK 0 #define XFIG_COLOR_BLUE 1 #define XFIG_COLOR_GREEN 2 #define XFIG_COLOR_CYAN 3 #define XFIG_COLOR_RED 4 #define XFIG_COLOR_MAGENTA 5 #define XFIG_COLOR_YELLOW 6 #define XFIG_COLOR_WHITE 7 // écriture d'un objet de type polyline dans un fichier au format XFIG // Entrée : f = identificateur de fichier // P = liste de points de la polyline // echelle = facteur de zoom (réel > 0) // couleur = entier entre 0 et 7 void XFIG_polyline(FILE *f, lPoints P, double echelle, int couleur) { // nombre de points de la polyline int n=P.size(); // écriture de l'instruction XFIG correspondante fprintf(f, "2 1 0 1 %d 7 50 -1 -1 0.000 0 0 -1 0 0 %d\n", couleur, n); for (lPoints::iterator i=P.begin(); i!=P.end(); i++) fprintf(f, " %d %d\n", (int)(i->x*echelle), -(int)(i->y*echelle)); } // écriture d'un fichier au format XFIG avec un objet de type polyline // Entrée : f = identificateur de fichier // P = liste de points de la polyline // echelle = facteur de zoom (réel > 0) // couleur = entier entre 0 et 7 void ecrire_polyline_XFIG(const char *nom_f, lPoints P, double echelle, int couleur) { // ouverture du fichier FILE *f = fopen(nom_f, "w"); // entete du fichier XFIG fprintf(f, "#FIG 3.2\n"); fprintf(f, "Landscape\n"); fprintf(f, "Center\n"); fprintf(f, "Metric\n"); fprintf(f, "A4 \n"); fprintf(f, "100.00\n"); fprintf(f, "Single\n"); fprintf(f, "-2\n"); fprintf(f, "1200 2\n"); // écriture de la polyline P dans le fichier f XFIG_polyline(f, P, echelle, couleur); // fermeture du fichier fclose(f); } // création d'un fichier image au format eps, jpeg ou gif // représentant une polyline P // Entrée : f = identificateur de fichier // P = liste de points de la polyline // echelle = facteur de zoom (réel > 0) // couleur = entier entre 0 et 7 // format = chaine de caractère "eps", "jpeg" ou "gif" void image_polyline(const char *nom_f, lPoints P, double echelle, int couleur, const char *format_image) { char nom_f_XFIG[1000], commande[1000]; sprintf(nom_f_XFIG, "%s.fig", nom_f); ecrire_polyline_XFIG(nom_f_XFIG, P, echelle, couleur); if (strcmp(format_image,"eps")==0) sprintf(commande, "fig2dev -L eps %s %s", nom_f_XFIG, nom_f); else if (strcmp(format_image,"jpeg")==0) sprintf(commande, "fig2dev -L jpeg -q 90 %s %s", nom_f_XFIG, nom_f); else if (strcmp(format_image,"gif")==0) sprintf(commande, "fig2dev -L gif %s %s", nom_f_XFIG, nom_f); else sprintf(commande, "echo \"Format inconnu\""); system(commande); sprintf(commande, "rm -f %s", nom_f_XFIG); system(commande); } /////////////////////////////////////////////////////////////////// // lecture d'une polyline dans un fichier texte // contenant une liste de points 2D // Entrée : nom_f = nom du fichier de points // un point par ligne : 2 valeurs réelles par ligne // La routine renvoie la liste de points lue. lPoints lire_polyline(const char *nom_f) { FILE *f = fopen(nom_f, "r"); lPoints L; if (f != (FILE *)NULL) { while (true) { double x,y; int res = fscanf(f, "%lf %lf", &x, &y); if (res != 2) break; Point2 P; P.x = x; P.y = y; L.push_back(P); } fclose(f); } return L; } /////////////////////////////////////////////////////////////////// // ROUTINE PRINCIPALE /////////////////////////////////////////////////////////////////// int main(int argc, char *argv[]) { // lecture du fichier France.data et création des fichiers image // en différents formats // choisir l'échelle en fonction des données // Pour le TP, les différents jeux de donnée sont des polylines // dont les dimensions sont d'environ 2000 // -> choisir une échelle entre 2 et 4 pour les fichiers images int d=atoi(argv[1]); lPoints L = lire_polyline(argv[2]); std::list<Point2>::iterator deb=L.begin(); std::list<Point2>::iterator fin=L.end();fin--; std::string compressS(argv[3]); compressS+=".txt"; std::ofstream compres(compressS.c_str(),std::ios::out); double tailleInit=L.size(); douglas(d,L,deb,fin); double tailleFin=L.size(); compres<<"taille initiale "<<tailleInit<<std::endl; compres<<"taille finale "<<tailleFin<<std::endl; compres<<"compression "<<tailleInit/tailleFin<<std::endl; compres.close(); // while(deb!=L.end()){ // std::cout<<"x "<<deb->x<<std::endl; // } ecrire_polyline_XFIG(argv[3],L, 2,7); // image_polyline(argv[3], L, 2.0, XFIG_COLOR_BLACK, "eps"); // image_polyline(argv[3], L, 4.0, XFIG_COLOR_BLACK, "jpeg"); image_polyline(argv[3], L, 4.0, XFIG_COLOR_BLACK, "gif"); return 0; }
[ "tzmoreno@gmail.com" ]
tzmoreno@gmail.com
5662f590cc5b20811ce9c05d7de65047f579fdd0
0789f6fa0348be668d7d212e8d9b17caaf52e803
/13.1(First Try)/Classic.cpp
a983c30ab9c2c1e1d4837cdfd297a9b9c8e1fb81
[]
no_license
JOhnBroker/Study_Cplusplus
db7b91a928afe7a94be1d96dafb04a775c77fcc4
5d627dabac453ce2c46eac04f4a36fafd61cd209
refs/heads/master
2021-09-08T18:21:04.130125
2021-08-28T08:04:09
2021-08-28T08:04:09
197,779,161
0
0
null
null
null
null
UTF-8
C++
false
false
458
cpp
#include "Classic.h" Classic::Classic(std::string s1, char const * s2, char const * s3, int n, double x) :Cd((char *)s2,(char *)s3,n,x) { describe=s1; } Classic::Classic(std::string s1, Cd & cd) :Cd(cd) { describe=s1; } void Classic::Report() const { Cd::Report(); std::cout<<"describe:"<<describe<<std::endl; } Classic & Classic::operator =(Classic & classic){ Cd::operator=(classic); describe=classic.describe; return *this; }
[ "38775739JOhnBreaker@users.noreply.github.com" ]
38775739JOhnBreaker@users.noreply.github.com
0c394a50d10852e8dd0a97c3d417ae69b79b7860
7fe70dd5b9f9c3b914589b8adf252ad3c092384c
/c++_basic_functions/image_filtering/FiltreMoyenne.cpp
b6ae1534c9ca7b5524f00c8ca17c11490dcc3992
[]
no_license
amahtani/cpp_utilitaries
a32a3eced7b07a2c54c9de9b9bcd3e0712a04379
1f1db3a8457e1917fc66e814cbe3793ed4df7279
refs/heads/master
2023-03-27T23:19:09.504992
2021-03-20T22:30:18
2021-03-20T22:30:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,053
cpp
/******************************** TP numéro 1 de c++ : Ankur MAHTANI & Bastien PESAMOSCA - Exercice 2 ********************************/ #include <iostream> #include "Image.hpp" #include "Filtre.hpp" #include "FiltreAddition.hpp" #include <fstream> #include <stdexcept> #include <string> #include <cassert> #include <stdlib.h> #include "FiltreMoyenne.hpp" // Methodes de la classe FiltreMoyenne FiltreMoyenne::FiltreMoyenne(int taille_filtre) { nom = "Filtre Moyenne"; n = taille_filtre; } void FiltreMoyenne::apply(Image& i) const { int lim = n/2; //n = taille du filtre int somme = 0; for(int j= lim ; j<= i.get_h() - lim; j++) { for(int k= lim ; k<= i.get_w() - lim; k++) { // pour chaque pixel on va regarder ses voisins for(int l= j-lim ; l<= j+lim ; l++ ) { for(int m= k-lim ; m<= k+lim ; m++) { somme = somme + i.get(l,m); //on fait la somme de chaque pixels voisins } } i.set(j,k,somme/(n*n)); //on remplace la valeur du pixel courant par la moyenne de tous ses voisins somme = 0 ; } } }
[ "ankur.mahtani@railenium.eu" ]
ankur.mahtani@railenium.eu
9f1c2db3f39349d0914416977dcada67a8e5d225
7c112951d0785e3fcc7191137ddc0d39c854759c
/MOG/MOG_ControllerPackageMergeEditor.h
c91b09d8a19a020a866dfda074fed48cadef999e
[]
no_license
MOGwareSupport/MOG
1003f575eea09a13309ecbad698cdb71a16f2fb8
cd768ad570d99c7f2b959a082f8f4976ec628b4a
refs/heads/master
2020-09-07T17:21:01.373903
2019-11-14T03:40:29
2019-11-14T03:40:29
220,857,805
0
0
null
null
null
null
UTF-8
C++
false
false
873
h
//-------------------------------------------------------------------------------- // MOG_ControllerPackageMergeEditor.h // // //-------------------------------------------------------------------------------- #ifndef __MOG_CONTROLLERPACKAGEMERGEEDITOR_H__ #define __MOG_CONTROLLERPACKAGEMERGEEDITOR_H__ #include "MOG_ControllerPackageMergeLocal.h" namespace MOG { namespace CONTROLLER { namespace CONTROLLERPACKAGE { public __gc class MOG_ControllerPackageMergeEditor : public MOG_ControllerPackageMergeLocal { public: MOG_ControllerPackageMergeEditor(); protected: // Package Merge Process Routines PackageList *ExecutePackageMergeTasks(PackageList *packageMergeTasks); bool DetectLocalAssetsToMerge(); PackageList* DetectAffectedPackageFiles(MOG_PackageMerge_PackageFileInfo* packageFileInfo); }; } } } #endif // __MOG_CONTROLLERPACKAGEMERGEEDITOR_H__
[ "support@mogware.com" ]
support@mogware.com
5d44c5aadb85007a9d25aff90098297b9a6dc815
b36f508871ed75d57e1477f2d7a523f5390b35c3
/Palindrome.cpp
e37b08d12ba58236842ea600b04b8c4c776a4693
[]
no_license
DolphyFluffy/BME122
d2e4f9ad7da62ee2b0f3624561bd8e6c758fa607
f1d722d09566782168ee6b5e3c8cbbb12401eee2
refs/heads/master
2021-03-13T22:06:38.712475
2020-03-12T01:24:03
2020-03-12T01:24:03
246,716,107
0
0
null
null
null
null
UTF-8
C++
false
false
579
cpp
#include <iostream> using namespace std; bool is_palindrome(string my_str/*, int index*/) { //base case: empty string //base case: one letter //use substring if(my_str.size() <= 1) return true; //general case: more than one letter else { //compare the first and last elements //move towards the middle //example: acb bool is_valid = my_str[0] == my_str[my_str.size() - 1]; return is_valid && is_palindrome(my_str.substr(1, my_str.size() - 2)); } } int main() { } //substrings take everythign betweent eh first value, to the last value in parentheses
[ "r38leung@uwaterloo.ca" ]
r38leung@uwaterloo.ca
adb54e95c33aac0fb31fccd02a0fcd5ab62a8b6f
74a12315360ce16ebc112d248638e14f4d569505
/problems_001-050/euler_9.cpp
11f1d2ad778b4b6f6314c92f954a08e64e2d986e
[ "Apache-2.0" ]
permissive
sedihub/project_euler
2c0d18bc21777f86d2134c466eec67960e20fc3c
2d7d40ee67a1e0402aa68e78a5f7d7cf18221db5
refs/heads/master
2023-02-19T15:10:52.430978
2021-01-23T22:53:58
2021-01-23T22:53:58
297,150,524
0
0
null
null
null
null
UTF-8
C++
false
false
1,206
cpp
/* PROBLEM: Pythagorean triple: a ^ 2 + b ^ 2 = c ^ 2 There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find it! SOLUTION: We could use brute force search. A more efficient solution can be constructed using Euclid's formula: a = m ^ 2 - n ^ 2 b = 2 * m * n c = m ^ 2 + n ^ 2 Given a Pythagorean triplet, {a, b, c} and k != 1, we can generate a new tripet: (k * a) ^ 2 + (k * b)^2 = (k * c)^2 Using this representation, we have: 1000 = k * 2 * m * (m + n) ---> 500 = k * m * (m + n) = 2^2 * 5^3 Since n < m, the only possible combination is: k = 1, m = 20, and n = 5 ANSWER: 375 * 200 * 425 = 31875000 **/ #include <iostream> int main() { int m, n, k; m = 20; n = 5; k = 1; // int a, b, c; a = m * m - n * n; b = 2 * m * n; c = m * m + n * n; std::cout << "\ta = " << a << std::endl; std::cout << "\tb = " << b << std::endl; std::cout << "\tc = " << c << std::endl; std::cout << "\ta + b + c = " << (a + b + c) << std::endl; std::cout << "\ta^2 + b^2 - c^2 = " << (a*a + b*b - c*c) << std::endl; std::cout << "a x b x c = " << (a * b * c) << std::endl; return 0; }
[ "luciferous@protonmail.com" ]
luciferous@protonmail.com
b739c2d327f4079446f89a11b2f4422b17e850bb
11ef4bbb8086ba3b9678a2037d0c28baaf8c010e
/Source Code/server/binaries/chromium/gen/chrome/browser/ui/webui/reset_password/reset_password.mojom-test-utils.cc
54048c2589d7a53c2c15a7ec02187000bef5c25f
[]
no_license
lineCode/wasmview.github.io
8f845ec6ba8a1ec85272d734efc80d2416a6e15b
eac4c69ea1cf0e9af9da5a500219236470541f9b
refs/heads/master
2020-09-22T21:05:53.766548
2019-08-24T05:34:04
2019-08-24T05:34:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,217
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-private-field" #elif defined(_MSC_VER) #pragma warning(push) #pragma warning(disable:4056) #pragma warning(disable:4065) #pragma warning(disable:4756) #endif #include "chrome/browser/ui/webui/reset_password/reset_password.mojom-test-utils.h" #include <utility> #include "base/bind.h" #include "base/run_loop.h" #ifndef CHROME_BROWSER_UI_WEBUI_RESET_PASSWORD_RESET_PASSWORD_MOJOM_JUMBO_H_ #define CHROME_BROWSER_UI_WEBUI_RESET_PASSWORD_RESET_PASSWORD_MOJOM_JUMBO_H_ #endif namespace mojom { void ResetPasswordHandlerInterceptorForTesting::HandlePasswordReset() { GetForwardingInterface()->HandlePasswordReset(); } ResetPasswordHandlerAsyncWaiter::ResetPasswordHandlerAsyncWaiter( ResetPasswordHandler* proxy) : proxy_(proxy) {} ResetPasswordHandlerAsyncWaiter::~ResetPasswordHandlerAsyncWaiter() = default; } // namespace mojom #if defined(__clang__) #pragma clang diagnostic pop #elif defined(_MSC_VER) #pragma warning(pop) #endif
[ "wasmview@gmail.com" ]
wasmview@gmail.com
39294c7ef7f91ea593760f45bb3dd9b61ccbf2b2
1bf608591a2997688507be72e8a0ced77e5a2ecb
/src/unity/toolkits/object_detection/one_shot_object_detection/util/superposition.hpp
b7239bee99aa04783842476001879da742fc47bb
[ "BSD-3-Clause" ]
permissive
jolinlaw/turicreate
422e419db342ca2a0bfbacb9f362af3a6fa820c0
6b2057dc29533da225d18138e93cc15680eea85d
refs/heads/master
2020-05-23T22:25:53.020602
2019-05-16T06:31:22
2019-05-16T06:31:22
186,970,341
0
0
BSD-3-Clause
2019-05-16T18:45:48
2019-05-16T06:58:38
C++
UTF-8
C++
false
false
795
hpp
/* Copyright © 2019 Apple Inc. All rights reserved. * * Use of this source code is governed by a BSD-3-clause license that can * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause */ #include <boost/gil/gil_all.hpp> #include <image/image_type.hpp> #include <unity/lib/gl_sframe.hpp> #include <unity/toolkits/object_detection/one_shot_object_detection/util/parameter_sampler.hpp> namespace turi { namespace one_shot_object_detection { namespace data_augmentation { flex_image create_synthetic_image(const boost::gil::rgb8_image_t::view_t &background_view, ParameterSampler &parameter_sampler, const flex_image &object); } // data_augmentation } // one_shot_object_detection } // turi
[ "noreply@github.com" ]
noreply@github.com
5518851ebad0a1348d62df99371d42f5e57a6ac6
b426140399b97b915c42db1aebc2ed0b5fb922f8
/tp02_polymorphism/src/config.h
bb15dce76f6c29f17b6010168e00105dea0647cc
[]
no_license
ctrlMarcio/FEUP-AEDA
d096e2f5cacb4d2b6037a6cddeed9d4cc229acc9
9b2c5ed93ce364cace7af17232549a67b6bd2c21
refs/heads/master
2020-08-03T18:55:22.468693
2019-12-18T00:21:43
2019-12-18T00:21:43
211,852,689
1
0
null
null
null
null
UTF-8
C++
false
false
941
h
#include <string> #define recent (year > recentYear) using namespace std; namespace config { const string taxableFuel = "gasoline"; const int recentYear = 1995; float calcTax(const string &fuelType, int displacement, int year) { float tax; if (fuelType == taxableFuel) { if (displacement <= 1000) tax = recent ? 14.56 : 8.10; else if (displacement <= 1300) tax = recent ? 29.06 : 14.56; else if (displacement <= 1750) tax = recent ? 45.15 : 22.65; else if (displacement <= 2600) tax = recent ? 113.98 : 54.89; else if (displacement <= 3500) tax = recent ? 181.17 : 87.13; else tax = recent ? 320.89 : 148.37; } else { if (displacement <= 1500) tax = recent ? 14.56 : 8.10; else if (displacement <= 2000) tax = recent ? 29.06 : 14.56; else if (displacement <= 3000) tax = recent ? 45.15 : 22.65; else tax = recent ? 113.98 : 54.89; } return tax; } }
[ "up201909936@fe.up.pt" ]
up201909936@fe.up.pt
2c596ea189293d2d049a37b690d73b6a754ffce8
933ab95ba832cb1c87c79975def979eea162f6eb
/7/src/jointPointCloud.cpp
bf29b5fb5874fdc987bb132116fae2b2e139299a
[]
no_license
ou525/rgbd-slam-learn
6cc284926ffeb7c884a8748e1dd9e17d1572fec8
c9babb46419dd4f5851fef9228046299bcd8ba3b
refs/heads/master
2020-12-31T07:41:33.768387
2017-04-07T13:59:57
2017-04-07T13:59:57
86,540,945
0
1
null
null
null
null
UTF-8
C++
false
false
2,875
cpp
#include <iostream> #include "slamBase.h" #include <opencv2/core/eigen.hpp> #include <pcl/common/transforms.h> //#include <pcl/visualization/cloud_viewer.h> #include <pcl/visualization/cloud_viewer.h> //Eigen ! #include <Eigen/Core> #include <Eigen/Geometry> using namespace std; int main( int argc, char** argv ) { //本节要拼合data中的两对图像 ParameterReader pd; //声明两个帧,FRAME结构见inlcude/slamBase.h FRAME frame1, frame2; //读取图像 frame1.rgb = cv::imread( "./data/rgb1.png" ); frame1.depth = cv::imread( "./data/depth1.png", -1 ); frame2.rgb = cv::imread( "./data/rgb2.png" ); frame2.depth = cv::imread( "./data/depth2.png", -1 ); //提取特征并计算描述子 cout << "extracting features" << endl; string detector = pd.getData( "detector" ); computeKeyPointsAndDesp( frame1, detector ); computeKeyPointsAndDesp( frame2, detector ); cout << frame2.kp.size() << frame1.kp.size() << endl; //相机内参 CAMERA_INTRINSIC_PARAMETERS camera; camera.fx = atof( pd.getData( "camera.fx" ).c_str()); camera.fy = atof( pd.getData( "camera.fy" ).c_str()); camera.cx = atof( pd.getData( "camera.cx" ).c_str()); camera.cy = atof( pd.getData( "camera.cy" ).c_str()); camera.factor = atof( pd.getData( "camera.factor" ).c_str()); cout << "sloving pnp" << endl; //求解pnp RESULT_OF_PNP result = estimateMotion( frame1, frame2, camera ); cout << result.rvec << endl << result.tvec << endl; //处理result //将旋转向量转化为旋转矩阵 cv::Mat R; cv::Rodrigues( result.rvec, R ); Eigen::Matrix3d r; cv::cv2eigen( R, r ); //将平移向量和旋转矩阵转换成变换矩阵 Eigen::Isometry3d T = Eigen::Isometry3d::Identity(); Eigen::AngleAxisd angle(r); cout << "translation" << endl; //Eigen::Translation<double,3> trans(result.tvec.at<double>(0,0), result.tvec.at<double>(0,1), result.tvec.at<double>(0,2)); T = angle; T(0,3) = result.tvec.at<double>(0,0); T(1,3) = result.tvec.at<double>(0,1); T(2,3) = result.tvec.at<double>(0,2); cout << T.matrix() << endl; //转换点云 cout << "converting img to clouds" << endl; PointCloud::Ptr cloud1 = image2PointCloud( frame1.rgb, frame1.depth, camera ); PointCloud::Ptr cloud2 = image2PointCloud( frame2.rgb, frame2.depth, camera ); //合并点云 cout << "combining clouds" << endl; PointCloud::Ptr output ( new PointCloud() ); pcl::transformPointCloud( *cloud1, *output, T.matrix() ); *output += *cloud2; pcl::io::savePCDFile( "data/result.pcd", *output ); cout << "Final result saved." << endl; pcl::visualization::CloudViewer viewer( "viewer" ); viewer.showCloud( output ); while( !viewer.wasStopped() ) { } return 0; }
[ "sheng.ou@helang.com" ]
sheng.ou@helang.com
4ed618102a99953dab96646958c936fbfbcbd1fd
bacf4c1512abc63c8a95bae1c12820308b602626
/src/gryltools++/stringtools.hpp
49f88b6247cf7fa23eb8fd36b7dd91653b206060
[]
no_license
hakeris1010/libGrylTools
0c8207818f4063207e52f9219e2cb8e2fb184479
b0c1f12c077070fba0b1273cdb186c02ca14817f
refs/heads/master
2021-09-04T10:21:26.533682
2018-01-17T23:48:06
2018-01-17T23:48:06
108,826,429
0
0
null
null
null
null
UTF-8
C++
false
false
1,022
hpp
#ifndef STRINGTOOLS_HPP_INCLUDED #define STRINGTOOLS_HPP_INCLUDED #include <string> namespace gtools{ class StringTools{ private: StringTools() = delete; StringTools(const StringTools&) = delete; StringTools(StringTools&&) = delete; StringTools& operator=(const StringTools&) = delete; StringTools& operator=(StringTools&&) = delete; public: const static int HEX_0X = 1; const static int HEX_LEADING_ZERO = 2; const static int HEX_CAPS = 4; static void escapeSpecials( std::string& str, bool escapeExtendeds = false ); static bool getEscapeSequence( char c, std::string& escapeBuff, bool escapeExtended ); static bool isEscapable( char c, bool escapeExtended = true ); static void getHexValue( const char* arr, size_t size, std::string& str, int flg=HEX_0X | HEX_LEADING_ZERO ); static std::string getHexValue( const char* arr, size_t size, int flg=HEX_0X | HEX_LEADING_ZERO ); }; } #endif // STRINGTOOLS_HPP_INCLUDED
[ "hakeris1010@gmail.com" ]
hakeris1010@gmail.com
47f10a449bb46c3bef2e51eceb49ac34d8315b21
0ef08c6e5c0e59255c6d8fd208627306476f9cad
/csgocheat/SDK/SDK Headers/CPred.h
93667395a7412071561e68a9d4d1f6b01ae18531
[]
no_license
ZeusDaGod/Ichigo-Bankai
299f795585ca86f93597b4a9ad772b8edfa3a88b
10394ec6aa87091b5edbee738cd6bfbe2efb38f5
refs/heads/master
2021-04-15T03:36:07.854461
2018-03-25T09:50:12
2018-03-25T09:50:12
126,683,330
6
0
null
null
null
null
UTF-8
C++
false
false
5,891
h
#pragma once #include "../../stdafx.h" #define MAX_SPLITSCREEN_PLAYERS 1 class IMoveHelper; class CMoveData { public: bool m_bFirstRunOfFunctions : 1; bool m_bGameCodeMovedPlayer : 1; bool m_bNoAirControl : 1; HANDLE m_nPlayerHandle; // edict index on server, client entity handle on client int m_nImpulseCommand; // Impulse command issued. Vector m_vecViewAngles; // Command view angles (local space) Vector m_vecAbsViewAngles; // Command view angles (world space) int m_nButtons; // Attack buttons. int m_nOldButtons; // From host_client->oldbuttons; float m_flForwardMove; float m_flSideMove; float m_flUpMove; float m_flMaxSpeed; float m_flClientMaxSpeed; // Variables from the player edict (sv_player) or entvars on the client. // These are copied in here before calling and copied out after calling. Vector m_vecVelocity; // edict::velocity // Current movement direction. Vector m_vecAngles; // edict::angles Vector m_vecOldAngles; // Output only float m_outStepHeight; // how much you climbed this move Vector m_outWishVel; // This is where you tried Vector m_outJumpVel; // This is your jump velocity // Movement constraints (radius 0 means no constraint) Vector m_vecConstraintCenter; float m_flConstraintRadius; float m_flConstraintWidth; float m_flConstraintSpeedFactor; bool m_bConstraintPastRadius; ///< If no, do no constraining past Radius. If yes, cap them to SpeedFactor past radius void SetAbsOrigin( const Vector& vec ); const Vector& GetAbsOrigin() const; private: Vector m_vecAbsOrigin; // edict::origin }; class CPrediction { // Construction public: virtual ~CPrediction( void ) = 0;// virtual void Init( void ) = 0;// virtual void Shutdown( void ) = 0;// // Implement IPrediction public: virtual void Update ( int startframe, // World update ( un-modded ) most recently received bool validframe, // Is frame data valid int incoming_acknowledged, // Last command acknowledged to have been run by server (un-modded) int outgoing_command // Last command (most recent) sent to server (un-modded) );// virtual void PreEntityPacketReceived( int commands_acknowledged, int current_world_update_packet );// virtual void PostEntityPacketReceived( void );//5 virtual void PostNetworkDataReceived( int commands_acknowledged );// virtual void OnReceivedUncompressedPacket( void );// // The engine needs to be able to access a few predicted values virtual void GetViewOrigin( Vector& org );// virtual void SetViewOrigin( Vector& org );// virtual void GetViewAngles( Vector& ang );//10 virtual void SetViewAngles( Vector& ang );// virtual void GetLocalViewAngles( Vector& ang );// virtual void SetLocalViewAngles( Vector& ang );// virtual bool InPrediction( void ) const;//14 virtual bool IsFirstTimePredicted( void ) const;// virtual int GetLastAcknowledgedCommandNumber( void ) const;// #if !defined( NO_ENTITY_PREDICTION ) virtual int GetIncomingPacketNumber( void ) const;// #endif /*float GetIdealPitch( int nSlot ) const { if ( nSlot == -1 ) { Assert( 0 ); return 0.0f; } return m_Split[ nSlot ].m_flIdealPitch; }*/ virtual void CheckMovingGround( CBaseEntity* player, double frametime );// virtual void RunCommand( CBaseEntity* player, CInput::CUserCmd* ucmd, IMoveHelper* moveHelper );// virtual void SetupMove( CBaseEntity* player, CInput::CUserCmd* ucmd, IMoveHelper* pHelper, CMoveData* move );//20 virtual void FinishMove( CBaseEntity* player, CInput::CUserCmd* ucmd, CMoveData* move );// virtual void SetIdealPitch( int nSlot, CBaseEntity* player, const Vector& origin, const Vector& angles, const Vector& viewheight );// virtual void CheckError( int nSlot, CBaseEntity* player, int commands_acknowledged );// // Called before and after any movement processing /*void StartCommand( C_BasePlayer *player, CUserCmd *cmd ); void FinishCommand( C_BasePlayer *player ); // Helpers to call pre and post think for player, and to call think if a think function is set void RunPreThink( C_BasePlayer *player ); void RunThink (C_BasePlayer *ent, double frametime ); void RunPostThink( C_BasePlayer *player );*/ public: virtual void _Update ( int nSlot, bool received_new_world_update, bool validframe, // Is frame data valid int incoming_acknowledged, // Last command acknowledged to have been run by server (un-modded) int outgoing_command // Last command (most recent) sent to server (un-modded) ); // Actually does the prediction work, returns false if an error occurred bool PerformPrediction( int nSlot, CBaseEntity* localPlayer, bool received_new_world_update, int incoming_acknowledged, int outgoing_command ); void ShiftIntermediateDataForward( int nSlot, int slots_to_remove, int previous_last_slot ); void RestoreEntityToPredictedFrame( int nSlot, int predicted_frame ); int ComputeFirstCommandToExecute( int nSlot, bool received_new_world_update, int incoming_acknowledged, int outgoing_command ); void DumpEntity( CBaseEntity* ent, int commands_acknowledged ); void ShutdownPredictables( void ); void ReinitPredictables( void ); void RemoveStalePredictedEntities( int nSlot, int last_command_packet ); void RestoreOriginalEntityState( int nSlot ); void RunSimulation( int current_command, float curtime, CInput::CUserCmd* cmd, CBaseEntity* localPlayer ); void Untouch( int nSlot ); void StorePredictionResults( int nSlot, int predicted_frame ); bool ShouldDumpEntity( CBaseEntity* ent ); void SmoothViewOnMovingPlatform( CBaseEntity* pPlayer, Vector& offset ); void ResetSimulationTick(); void ShowPredictionListEntry( int listRow, int showlist, CBaseEntity* ent, int& totalsize, int& totalsize_intermediate ); void FinishPredictionList( int listRow, int showlist, int totalsize, int totalsize_intermediate ); void CheckPredictConvar(); #if !defined( NO_ENTITY_PREDICTION ) #endif };
[ "37769185+ZeusDaGod@users.noreply.github.com" ]
37769185+ZeusDaGod@users.noreply.github.com
1bd39773c4ab2996763220fa5aef5609553c372a
010279e2ba272d09e9d2c4e903722e5faba2cf7a
/contrib/libs/zeromq/sources/src/plain_client.cpp
04be39f344b635886cf5ad861252ab0b5325b071
[ "GPL-3.0-only", "LGPL-3.0-only", "LicenseRef-scancode-zeromq-exception-lgpl-3.0", "Apache-2.0" ]
permissive
catboost/catboost
854c1a1f439a96f1ae6b48e16644be20aa04dba2
f5042e35b945aded77b23470ead62d7eacefde92
refs/heads/master
2023-09-01T12:14:14.174108
2023-09-01T10:01:01
2023-09-01T10:22:12
97,556,265
8,012
1,425
Apache-2.0
2023-09-11T03:32:32
2017-07-18T05:29:04
Python
UTF-8
C++
false
false
6,415
cpp
/* Copyright (c) 2007-2015 Contributors as noted in the AUTHORS file This file is part of libzmq, the ZeroMQ core engine in C++. libzmq is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. As a special exception, the Contributors give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you must extend this exception to your version of the library. libzmq is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "platform.hpp" #ifdef ZMQ_HAVE_WINDOWS #include "windows.hpp" #endif #include <string> #include "msg.hpp" #include "err.hpp" #include "plain_client.hpp" zmq::plain_client_t::plain_client_t (const options_t &options_) : mechanism_t (options_), state (sending_hello) { } zmq::plain_client_t::~plain_client_t () { } int zmq::plain_client_t::next_handshake_command (msg_t *msg_) { int rc = 0; switch (state) { case sending_hello: rc = produce_hello (msg_); if (rc == 0) state = waiting_for_welcome; break; case sending_initiate: rc = produce_initiate (msg_); if (rc == 0) state = waiting_for_ready; break; default: errno = EAGAIN; rc = -1; } return rc; } int zmq::plain_client_t::process_handshake_command (msg_t *msg_) { const unsigned char *cmd_data = static_cast <unsigned char *> (msg_->data ()); const size_t data_size = msg_->size (); int rc = 0; if (data_size >= 8 && !memcmp (cmd_data, "\7WELCOME", 8)) rc = process_welcome (cmd_data, data_size); else if (data_size >= 6 && !memcmp (cmd_data, "\5READY", 6)) rc = process_ready (cmd_data, data_size); else if (data_size >= 6 && !memcmp (cmd_data, "\5ERROR", 6)) rc = process_error (cmd_data, data_size); else { // Temporary support for security debugging puts ("PLAIN I: invalid handshake command"); errno = EPROTO; rc = -1; } if (rc == 0) { rc = msg_->close (); errno_assert (rc == 0); rc = msg_->init (); errno_assert (rc == 0); } return rc; } zmq::mechanism_t::status_t zmq::plain_client_t::status () const { if (state == ready) return mechanism_t::ready; else if (state == error_command_received) return mechanism_t::error; else return mechanism_t::handshaking; } int zmq::plain_client_t::produce_hello (msg_t *msg_) const { const std::string username = options.plain_username; zmq_assert (username.length () < 256); const std::string password = options.plain_password; zmq_assert (password.length () < 256); const size_t command_size = 6 + 1 + username.length () + 1 + password.length (); const int rc = msg_->init_size (command_size); errno_assert (rc == 0); unsigned char *ptr = static_cast <unsigned char *> (msg_->data ()); memcpy (ptr, "\x05HELLO", 6); ptr += 6; *ptr++ = static_cast <unsigned char> (username.length ()); memcpy (ptr, username.c_str (), username.length ()); ptr += username.length (); *ptr++ = static_cast <unsigned char> (password.length ()); memcpy (ptr, password.c_str (), password.length ()); ptr += password.length (); return 0; } int zmq::plain_client_t::process_welcome ( const unsigned char *cmd_data, size_t data_size) { if (state != waiting_for_welcome) { errno = EPROTO; return -1; } if (data_size != 8) { errno = EPROTO; return -1; } state = sending_initiate; return 0; } int zmq::plain_client_t::produce_initiate (msg_t *msg_) const { unsigned char * const command_buffer = (unsigned char *) malloc (512); alloc_assert (command_buffer); unsigned char *ptr = command_buffer; // Add mechanism string memcpy (ptr, "\x08INITIATE", 9); ptr += 9; // Add socket type property const char *socket_type = socket_type_string (options.type); ptr += add_property (ptr, "Socket-Type", socket_type, strlen (socket_type)); // Add identity property if (options.type == ZMQ_REQ || options.type == ZMQ_DEALER || options.type == ZMQ_ROUTER) ptr += add_property ( ptr, "Identity", options.identity, options.identity_size); const size_t command_size = ptr - command_buffer; const int rc = msg_->init_size (command_size); errno_assert (rc == 0); memcpy (msg_->data (), command_buffer, command_size); free (command_buffer); return 0; } int zmq::plain_client_t::process_ready ( const unsigned char *cmd_data, size_t data_size) { if (state != waiting_for_ready) { errno = EPROTO; return -1; } const int rc = parse_metadata (cmd_data + 6, data_size - 6); if (rc == 0) state = ready; return rc; } int zmq::plain_client_t::process_error ( const unsigned char *cmd_data, size_t data_size) { if (state != waiting_for_welcome && state != waiting_for_ready) { errno = EPROTO; return -1; } if (data_size < 7) { errno = EPROTO; return -1; } const size_t error_reason_len = static_cast <size_t> (cmd_data [6]); if (error_reason_len > data_size - 7) { errno = EPROTO; return -1; } state = error_command_received; return 0; }
[ "akhropov@yandex-team.com" ]
akhropov@yandex-team.com
4e2e7b1657f55403c1158ed27dc849ca3930b72c
ca72686ff29bfa25c440449bc672fceb927326a3
/algorithms_2/MergeSort/MergeSort.cpp
365580e21a7ae60a620ef5dff885f1a72c1759d1
[ "MIT" ]
permissive
runt1m33rr0r/cpp-stuff
1ea05acac3a320330a4e9be33538044dd03c589b
0a98d8d618a8226e7e2a63b262ef8fe3ec43e185
refs/heads/master
2021-06-22T05:24:38.831066
2019-06-01T08:00:53
2019-06-01T08:00:53
109,747,935
0
0
null
null
null
null
UTF-8
C++
false
false
1,295
cpp
#include <iostream> using namespace std; void PrintData(int arr[], int len) { for (size_t i = 0; i < len; i++) { cout << arr[i] << " "; } cout << endl; } void Merge(int arr[], int arrCopy[], int leftStart, int leftEnd, int rightStart, int rightEnd) { int leftIdx = leftStart; int rightIdx = rightStart; int copyIdx = leftStart; while (leftIdx <= leftEnd && rightIdx <= rightEnd) { if (arr[rightIdx] < arr[leftIdx]) { arrCopy[copyIdx] = arr[rightIdx]; rightIdx++; } else { arrCopy[copyIdx] = arr[leftIdx]; leftIdx++; } copyIdx++; } for (size_t i = rightIdx; i <= rightEnd; i++) { arrCopy[copyIdx] = arr[i]; copyIdx++; } for (size_t i = leftIdx; i <= leftEnd; i++) { arrCopy[copyIdx] = arr[i]; copyIdx++; } for (size_t i = leftStart; i <= rightEnd; i++) { arr[i] = arrCopy[i]; } } void MergeSort(int arr[], int arrCopy[], int len, int left, int right) { if (left < right) { int mid = (left + right) / 2; MergeSort(arr, arrCopy, len, left, mid); MergeSort(arr, arrCopy, len, mid + 1, right); Merge(arr, arrCopy, left, mid, mid + 1, right); } } int main() { const int len = 5; int arr[len] = { 5, 4, 3, 2, 1 }; int arrCopy[len] = { 0 }; MergeSort(arr, arrCopy, len, 0, len - 1); PrintData(arr, len); return 0; }
[ "19938633+runt1m33rr0r@users.noreply.github.com" ]
19938633+runt1m33rr0r@users.noreply.github.com
72d52fe5783540ea7038a96ddbd077e400b7b3e0
4c6cdd7e10077c4b1b059b702f611b13757ee0a4
/Detect_Cycle_unDirected.cpp
529b48958704e9ad6c6aaaa6d78a4961f120e3e2
[]
no_license
belwariars/Graphs
5b99497419d897cebd48663a3e4c2a4095b73110
6e3ead1edbe6aa111a6afcf927d55d099f591cc9
refs/heads/master
2021-01-11T11:52:54.653396
2017-01-09T12:31:25
2017-01-09T12:31:25
76,710,207
0
0
null
null
null
null
UTF-8
C++
false
false
1,338
cpp
#include <bits/stdc++.h> using namespace std; int isCycleUtil(vector<list<int>> adjlist, int visited[], int pos, int parent) { visited[pos] = true; list<int>:: iterator it; for(it=adjlist[pos].begin(); it!=adjlist[pos].end(); it++) { if(!visited[*it]) { if(isCycleUtil(adjlist, visited, *it, pos)) return 1; } else { if((*it)!= parent) { return 1; } } } return 0; } int isCycle(vector<list<int>> adjlist, int v) { int visited[v+1]; int i; for(i=0; i<=v; i++) { visited[i] = 0; } for(i=0; i<=v; i++) { if(!visited[i]) { if(isCycleUtil(adjlist, visited, i, -1)) { return 1; } } } return 0; } int main() { int e,v; printf("Enter no. of vertices: \n"); scanf("%d", &v); printf("Enter no. of Edges: \n"); scanf("%d", &e); int i; int v1, v2; vector<list<int>> adjlist(v+1); for(i=0; i<e; i++) { printf("Enter v1 & v2: \n"); scanf("%d %d", &v1, &v2); adjlist[v1].push_back(v2); adjlist[v2].push_back(v1); } list<int>:: iterator it; for(i=0; i<=v; i++) { printf("adjlist[%d]", i); for(it=adjlist[i].begin(); it!=adjlist[i].end(); it++) { printf("->%d", *it); } printf("\n"); } if(isCycle(adjlist, v)) { printf("Cycle EXISTS!!\n"); } else { printf("Cycle DOESN'T EXISTS\n"); } return 0; }
[ "noreply@github.com" ]
noreply@github.com
332d96b5fbd989ae9a2bb91f4e6da211e35a13a7
e3cf0c00d2bb2f3853cbf551ac0c5265eb097316
/RecycleRushRobot/src/Commands/FixPrefs.cpp
f8f070711953cf983b7f18034ef2d679033a84ec
[]
no_license
FRC-Team-4143/RecycleRush2015
222b4fa3d264f01a32d09952d7cd177789582b7e
c4fde5f1a19a277cb7cf93172d39fa86b379688e
refs/heads/master
2020-04-10T00:06:13.668338
2015-04-25T02:37:33
2015-04-25T02:37:33
30,273,379
0
0
null
null
null
null
UTF-8
C++
false
false
1,820
cpp
#include "Commands/FixPrefs.h" #include "../Constants.h" #include "../Robot.h" #include <WPILib.h> // ========================================================================== FixPrefs::FixPrefs() : Command("Show Prefs") { SetRunWhenDisabled(true); } // ========================================================================== // Called just before this Command runs the first time void FixPrefs::Initialize() { std::cout << "FixPrefs::Initialize" << std::endl; // List all preferences auto prefs = Preferences::GetInstance(); prefs->Remove("testDouble"); prefs->Remove("TestFloat"); prefs->Remove("testLong"); prefs->Remove("testString"); prefs->Remove("test"); prefs->Remove("RL-Pos"); prefs->Remove("RR-Pos"); prefs->Save(); std::cout << "NAME: " << Constants::FL_POS_NAME << std::endl; //prefs->PutDouble(Constants::FL_POS_NAME, 0.0); //prefs->PutDouble(Constants::FR_POS_NAME, 0.0); //prefs->PutDouble(Constants::RL_POS_NAME, 0.0); //prefs->PutDouble(Constants::RR_POS_NAME, 0.0); prefs->Save(); } // ========================================================================== // Called repeatedly when this Command is scheduled to run void FixPrefs::Execute() { } // ========================================================================== // Make this return true when this Command no longer needs to run Execute. bool FixPrefs::IsFinished() { return true; } // ========================================================================== // Called once after IsFinished returns true void FixPrefs::End() { } // ========================================================================== // Called when another command which requires this subsystem is scheduled to run void FixPrefs::Interrupted() { } // ==========================================================================
[ "pike@mtco.com" ]
pike@mtco.com
98d729cf52c1c86823f5328edfbd9540d7823a9b
d798bed49a523108fe38205380dcc26925bbfed0
/trie/include/wordsearch_solver/trie/trie.tpp
abf5a0c697bc50977487bce6dc32a1efc9185c7a
[ "MIT" ]
permissive
Arghnews/wordsearch_solver
f6a06dae18176888ed20aaf5e49ae6c4670f35db
cf25db64ca3d1facd9191aad075654f124f0d580
refs/heads/main
2023-08-05T10:46:29.732929
2021-09-20T21:47:24
2021-09-20T21:47:24
395,403,517
0
0
null
null
null
null
UTF-8
C++
false
false
1,688
tpp
#ifndef TRIE_TPP #define TRIE_TPP #include "wordsearch_solver/trie/node.hpp" #include "wordsearch_solver/trie/trie.hpp" #include "wordsearch_solver/utility/utility.hpp" #include <range/v3/algorithm/sort.hpp> #include <range/v3/view/enumerate.hpp> #include <range/v3/view/subrange.hpp> #include <range/v3/view/unique.hpp> #include <cstddef> #include <iterator> #include <string> #include <string_view> #include <vector> namespace trie { // FIXME: this would use ranges::subrange as we don't need to alloc. However // this won't compile due to std::tuple_element on incomplete class (on gcc with // -fconcepts at least) so leaving like this for now. template <class Iterator1, class Iterator2> Trie::Trie(Iterator1 first, const Iterator2 last) : Trie(std::vector<std::string>(first, last)) {} /** The constructor that actually does the work */ template <class Strings> Trie::Trie(Strings&& strings_in) : root_{}, size_{}, cache_{} { for (const auto& word : ranges::views::unique(strings_in)) { if (this->insert(word).second) { ++size_; } } } template <class OutputIterator> void Trie::contains_further(const std::string_view stem, const std::string_view suffixes, OutputIterator contains_further_it) const { const auto* node = this->search(stem); if (!node) { return; } for (const auto [i, c] : ranges::views::enumerate(suffixes)) { const std::string_view suffix = {&c, 1}; const auto contains = detail::contains(*node, suffix); const auto further = detail::further(*node, suffix); *contains_further_it++ = {contains, further}; } } } // namespace trie #endif // TRIE_TPP
[ "arghnews@hotmail.co.uk" ]
arghnews@hotmail.co.uk
8ddce93a50f1e62ab362e45c8eda937c701900ba
90fbd5033dd9fbb73e5612770bb50457e1ce2d75
/game/tic_tac_toe.cc
9234def6cc3fea3e00ce1eeba1429fdaf4a4bd51
[]
no_license
longjianquan/mcts
5806c3cc01774bef3079e1c58de0e2267980c4e4
6d315a07fe32b3591a7545d1ca4baec94258b1c9
refs/heads/master
2023-03-21T06:42:13.470977
2018-06-14T11:37:56
2018-06-14T11:37:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,031
cc
#include "game/tic_tac_toe.hh" #include <algorithm> #include <iterator> namespace game { using State = TicTacToeState; using Action = TicTacToeAction; namespace { State::CellState check_for_match(const State &state, int start, int stride) { if (state.board[start] == state.board[start + stride] && state.board[start] == state.board[start + 2 * stride] && state.board[start] != State::EMPTY) { return state.board[start]; } return State::EMPTY; } EndCondition check_game_state(const State &state, const State::CellState &current_player) { std::vector<State::CellState> results; // Check rows and columns for (int i = 0; i < 3; i++) { // Check ith row results.push_back(check_for_match(state, 3*i, 1)); // Check ith columns results.push_back(check_for_match(state, i, 3)); } // Check the diagonals results.push_back(check_for_match(state, 0, 4)); results.push_back(check_for_match(state, 2, 2)); // Check to see if there are any wins const auto iter = std::find_if_not(results.begin(), results.end(), [](const State::CellState &state) { return state == State::EMPTY; }); // Finally check to see if the board is full const auto first_empty_iter = std::find_if_not( std::begin(state.board), std::end(state.board), [](const State::CellState &state) { return state == State::EMPTY; }); const bool has_empty = first_empty_iter != std::end(state.board); if (iter == results.end()) { return has_empty ? EndCondition::ONGOING : EndCondition::DRAW; } return *iter == current_player ? EndCondition::WIN : EndCondition::LOSS; } } // namespace Step<State> step_game(const State &state, const Action &action) { Step<State> step; // Check if the action is valid. If it is not, return the // same state, otherwise apply the action const bool is_valid_action = state.board[action.position] == State::EMPTY; const bool is_game_over = check_game_state(state, state.current_player) != ONGOING; step.new_state = state; if (is_valid_action && !is_game_over) { step.new_state.board[action.position] = state.current_player; } // Check the win conditions step.end_condition = check_game_state(state, state.current_player); // Set the next player if (is_valid_action && step.end_condition == ONGOING) { step.new_state.current_player = state.current_player == State::X ? State::O : State::X; } else { step.new_state.current_player = state.current_player; } return step; } std::set<TicTacToeAction> available_actions(const TicTacToeState &state) { std::set<TicTacToeAction> out = {}; for (int pos = 0; pos < State::NUM_POSITIONS; pos++) { if (state.board[pos] == TicTacToeState::EMPTY) { out.insert({pos}); } } return out; } int current_player(const TicTacToeState &state) { return state.current_player; } game::GameOps<TicTacToeState, TicTacToeAction> get_tic_tac_toe_ops() { return { .step_game = step_game, .available_actions = available_actions, .current_player = current_player, }; } } // namespace game
[ "fuentes.erick@gmail.com" ]
fuentes.erick@gmail.com
fb9beb690328d9f2b6423090cb1c39beb23dd586
cbbcfcb52e48025cb6c83fbdbfa28119b90efbd2
/lastpractice/longgraph/CHEFGAME.cpp
0656b014edd0515e882055913b9075f6bd98ec3e
[]
no_license
dmehrab06/Time_wasters
c1198b9f2f24e06bfb2199253c74a874696947a8
a158f87fb09d880dd19582dce55861512e951f8a
refs/heads/master
2022-04-02T10:57:05.105651
2019-12-05T20:33:25
2019-12-05T20:33:25
104,850,524
0
1
null
null
null
null
UTF-8
C++
false
false
3,460
cpp
/*-------property of the half blood prince-----*/ #include <bits/stdc++.h> #include <dirent.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/detail/standard_policies.hpp> #define MIN(X,Y) X<Y?X:Y #define MAX(X,Y) X>Y?X:Y #define ISNUM(a) ('0'<=(a) && (a)<='9') #define ISCAP(a) ('A'<=(a) && (a)<='Z') #define ISSML(a) ('a'<=(a) && (a)<='z') #define ISALP(a) (ISCAP(a) || ISSML(a)) #define MXX 100000000000000 #define MNN -MXX #define ISVALID(X,Y,N,M) ((X)>=1 && (X)<=(N) && (Y)>=1 && (Y)<=(M)) #define LLI long long int #define VI vector<int> #define VLLI vector<long long int> #define MII map<int,int> #define SI set<int> #define PB push_back #define MSI map<string,int> #define PII pair<int,int> #define PLLI pair<LLI,LLI> #define PDD pair<double,double> #define FREP(i,I,N) for(int (i)=(int)(I);(i)<=(int)(N);(i)++) #define eps 0.0000000001 #define RFREP(i,N,I) for(int (i)=(int)(N);(i)>=(int)(I);(i)--) #define SORTV(VEC) sort(VEC.begin(),VEC.end()) #define SORTVCMP(VEC,cmp) sort(VEC.begin(),VEC.end(),cmp) #define REVV(VEC) reverse(VEC.begin(),VEC.end()) #define INRANGED(val,l,r) (((l)<(val) || fabs((val)-(l))<eps) && ((val)<(r) || fabs((val)-(r))<eps)) #define INRANGEI(val,l,r) ((val)>=(l) && (val)<=(r)) #define MSET(a,b) memset(a,b,sizeof(a)) #define MDD 747474747 using namespace std; using namespace __gnu_pbds; #define MAXV 6675 //int dx[]={1,0,-1,0};int dy[]={0,1,0,-1}; //4 Direction //int dx[]={1,1,0,-1,-1,-1,0,1};int dy[]={0,1,1,1,0,-1,-1,-1};//8 direction //int dx[]={2,1,-1,-2,-2,-1,1,2};int dy[]={1,2,2,1,-1,-2,-2,-1};//Knight Direction //int dx[]={2,1,-1,-2,-1,1};int dy[]={0,1,1,0,-1,-1}; //Hexagonal Direction //typedef tree < int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update > ordered_set; vector<VI>points; LLI key[MAXV]; int mstSet[MAXV]; LLI getdis(int src, int des){ VI u = points[src]; VI v = points[des]; LLI d = 0; FREP(i,0,u.size()-1){ LLI du = u[i]; LLI dv = v[i]; d = d +((du-dv)*(du-dv)); } return d; } void init(int v){ points.clear();MSET(mstSet,0); VI line; FREP(i,1,v+4)points.PB(line); FREP(i,1,v+4)key[i]=0; } int mxKey(int V) { // Initialize min value LLI mx = 0; int mx_index; FREP(v,1,V){ //cout<<v<<" "<<key[v]<<"\n"; if ((!mstSet[v]) && (key[v] > mx)){ mx = key[v]; mx_index = v; //cout<<mx<<" "<<mx_index<<"\n"; } } return mx_index; } LLI primMST(int V){ key[1] = 1; // The MST will have V vertices LLI s = 1; FREP(cnt,1,V){ int u = mxKey(V); //cout<<"mxu "<<u<<"\n"; LLI val = key[u]%MDD; //cout<<val<<"\n"; s = s*val; s%=MDD; //cout<<"s now "<<s<<"\n"; mstSet[u] =1; FREP(v,1,V){ if(!mstSet[v]){ LLI dis = getdis(u,v); //calculates euler distance //cout<<"from "<<u<<" to "<<v<<" "<<dis<<"\n"; if(dis>key[v]){ key[v]=dis; } } } } return s; } int main(){ int t; scanf("%d",&t); while(t--){ int n,d; scanf("%d %d",&n,&d); init(n); FREP(i,1,n){ FREP(k,1,d){ int v; scanf("%d",&v); points[i].PB(v); } } LLI ans = primMST(n); printf("%lld\n",ans); } }
[ "1205112.zm@ugrad.cse.buet.ac.bd" ]
1205112.zm@ugrad.cse.buet.ac.bd
a4da789d78ae7a442bd3f3c75abb8cbe851fdbf8
5fdca34122c2f2c6aa3bea8a587c9b6f1a4dbe0f
/PWGGA/PHOSTasks/PHOS_LHC16_pp/AliPP13MesonSelectionMC.cxx
c6be2551c8fbed72d1fe96159ab00421ee21e6af
[]
permissive
ALICEHLT/AliPhysics
df9be958613fbec367de23d07900bdfaa1bd8c2b
ac60d90f9a9c28b789c842979573a34485966b8f
refs/heads/dev
2021-01-23T02:06:10.419609
2018-05-14T19:20:25
2018-05-14T19:20:25
85,963,503
0
7
BSD-3-Clause
2018-02-21T12:27:23
2017-03-23T15:06:08
C++
UTF-8
C++
false
false
8,464
cxx
// #include "iterator" // --- Custom header files --- #include "AliPP13MesonSelectionMC.h" // --- ROOT system --- #include <TParticle.h> #include <TProfile.h> #include <TSystem.h> #include <TFile.h> #include <TTree.h> #include <TKey.h> #include <TH2F.h> // --- AliRoot header files --- #include <AliLog.h> #include <AliVCluster.h> #include <AliAnalysisManager.h> #include <iostream> using namespace std; ClassImp(AliPP13MesonSelectionMC); //________________________________________________________________ void AliPP13MesonSelectionMC::ConsiderPair(const AliVCluster * c1, const AliVCluster * c2, const EventFlags & eflags) { TLorentzVector p1 = ClusterMomentum(c1, eflags); TLorentzVector p2 = ClusterMomentum(c2, eflags); TLorentzVector psum = p1 + p2; // Pair cuts can be applied here if (psum.M2() < 0) return; Int_t sm1, sm2, x1, z1, x2, z2; if ((sm1 = CheckClusterGetSM(c1, x1, z1)) < 0) return; // To be sure that everything is Ok if ((sm2 = CheckClusterGetSM(c2, x2, z2)) < 0) return; // To be sure that everything is Ok Double_t ma12 = psum.M(); Double_t pt12 = psum.Pt(); fInvMass[eflags.isMixing]->Fill(ma12, pt12); if (eflags.isMixing) return; Int_t label1 = c1->GetLabelAt(0) ; Int_t label2 = c2->GetLabelAt(0) ; AliAODMCParticle * mother1 = GetParent(label1, eflags.fMcParticles); AliAODMCParticle * mother2 = GetParent(label2, eflags.fMcParticles); if (!mother1 || !mother2) return; if (mother1 != mother2) return; if (mother1->GetPdgCode() != kPi0) return; // Check if the selected \pi^{0} is primary // Bool_t primary = IsPrimary(mother1); if (primary) fPrimaryPi0[kReconstructed]->FillS(ma12, pt12); else fSecondaryPi0[kReconstructed]->FillS(ma12, pt12); // Looking at the source of pi0 Int_t source_label = mother1->GetMother(); // It's not decay pi0 if (source_label == -1) return; AliAODMCParticle * hadron = dynamic_cast<AliAODMCParticle *> (eflags.fMcParticles->At(source_label)); if (!hadron) return; Int_t hcode = hadron->GetPdgCode(); if (primary) { fPrimaryPi0[kReconstructed]->Fill(hcode, ma12, pt12); return; } if (!IsPrimary(hadron)) { fSecondaryPi0[kReconstructed]->Fill(hcode, ma12, pt12); return; } fFeedDownPi0[kReconstructed]->FillAll(hcode, ma12, pt12); } //________________________________________________________________ void AliPP13MesonSelectionMC::InitSelectionHistograms() { Int_t nM = 750; Double_t mMin = 0.0; Double_t mMax = 1.5; Int_t nPt = 400; Double_t ptMin = 0; Double_t ptMax = 20; for (Int_t i = 0; i < 2; ++i) { fInvMass[i] = new TH2F(Form("h%sMassPt", i == 0 ? "" : "Mix") , "(M,p_{T})_{#gamma#gamma}, N_{cell}>2; M_{#gamma#gamma}, GeV; p_{T}, GeV/c", nM, mMin, mMax, nPt, ptMin, ptMax); fListOfHistos->Add(fInvMass[i]); } Float_t ptbins[] = {0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0, 11.0, 12.0, 13.0, 15.0, 20.0}; Int_t ptsize = sizeof(ptbins) / sizeof(Float_t); // Sources of neutral pions, as a histogram for (Int_t i = 0; i < 2; ++i) { Int_t sstart = -10000; Int_t sstop = 10000 + 1; Int_t sbins = sstop - sstart; const char * s = (i == 0) ? "secondary" : "primary"; fPi0Sources[i] = new TH1F(Form("hMC_%s_sources_%s", fPartNames[kPi0].Data(), s), Form("Sources of %s %ss ; PDG code", s, fPartNames[kPi0].Data()), sbins, sstart, sstop); fListOfHistos->Add(fPi0Sources[i]); } // Fill Generated histograms const char * np = fPartNames[kPi0]; TH1 * hist1 = new TH1F(Form("hPt_%s_primary_", np), "Distribution of primary #pi^{0}s from primary ; p_{T}, GeV/c", ptsize - 1, ptbins); TH1 * hist2 = new TH1F(Form("hPt_%s_secondary_", np), "Distribution of secondary #pi^{0}s from secondary ; p_{T}, GeV/c", ptsize - 1, ptbins); TH1 * hist3 = new TH1F(Form("hPt_%s_feeddown_", np), "Distribution of primary #pi^{0}s from secondary ; p_{T}, GeV/c", ptsize - 1, ptbins); TH1 * hist4 = new TH2F(Form("hMassPt_%s_primary_", np), "(M,p_{T})_{#gamma#gamma} from primary ; M_{#gamma#gamma}, GeV; p_{T}, GeV/c", nM, mMin, mMax, nPt, ptMin, ptMax); TH1 * hist5 = new TH2F(Form("hMassPt_%s_secondary_", np), "(M,p_{T})_{#gamma#gamma} from secondary ; M_{#gamma#gamma}, GeV; p_{T}, GeV/c", nM, mMin, mMax, nPt, ptMin, ptMax); TH1 * hist6 = new TH2F(Form("hMassPt_%s_feeddown_", np), "(M,p_{T})_{#gamma#gamma} from secondary ; M_{#gamma#gamma}, GeV; p_{T}, GeV/c", nM, mMin, mMax, nPt, ptMin, ptMax); fPrimaryPi0[kGenerated] = new AliPP13ParticlesHistogram(hist1, fListOfHistos, fPi0SourcesNames); fSecondaryPi0[kGenerated] = new AliPP13ParticlesHistogram(hist2, fListOfHistos, fPi0SourcesNames); fFeedDownPi0[kGenerated] = new AliPP13ParticlesHistogram(hist3, fListOfHistos, fPi0SourcesNames); fPrimaryPi0[kReconstructed] = new AliPP13ParticlesHistogram(hist4, fListOfHistos, fPi0SourcesNames); fSecondaryPi0[kReconstructed] = new AliPP13ParticlesHistogram(hist5, fListOfHistos, fPi0SourcesNames); fFeedDownPi0[kReconstructed] = new AliPP13ParticlesHistogram(hist6, fListOfHistos, fPi0SourcesNames); for (EnumNames::iterator i = fPartNames.begin(); i != fPartNames.end(); ++i) { const char * n = (const char *) i->second.Data(); fSpectrums[i->first] = new ParticleSpectrum(n, fListOfHistos, ptsize - 1, ptbins, i->first != kPi0); } for (Int_t i = 0; i < fListOfHistos->GetEntries(); ++i) { TH1 * hist = dynamic_cast<TH1 *>(fListOfHistos->At(i)); if (!hist) continue; hist->Sumw2(); } } void AliPP13MesonSelectionMC::ConsiderGeneratedParticles(const EventFlags & flags) { if (!flags.fMcParticles) return; for (Int_t i = 0; i < flags.fMcParticles->GetEntriesFast(); i++) { AliAODMCParticle * particle = ( AliAODMCParticle *) flags.fMcParticles->At(i); Int_t code = TMath::Abs(particle->GetPdgCode()); // NB: replace this condition by find, if the number of particles will grow // if (code != kGamma && code != kPi0 && code != kEta) continue; Double_t pt = particle->Pt(); // Use this to remove forward photons that can modify our true efficiency if (TMath::Abs(particle->Y()) > 0.5) // NB: Use rapidity instead of pseudo rapidity! continue; Double_t r = TMath::Sqrt(particle->Xv() * particle->Xv() + particle->Yv() * particle->Yv()); fSpectrums[code]->fPt->Fill(pt); fSpectrums[code]->fPtRadius->Fill(pt, r); Bool_t primary = IsPrimary(particle); if (primary && particle->E() > 0.3) { fSpectrums[code]->fPtLong->Fill(pt); fSpectrums[code]->fPtAllRange->Fill(pt); fSpectrums[code]->fEtaPhi->Fill(particle->Phi(), particle->Y()); } if (code != kPi0) { fSpectrums[code]->fPtPrimaries[Int_t(primary)]->Fill(pt); continue; } // TODO: Scale input distribution ConsiderGeneratedPi0(i, pt, primary, flags); } } void AliPP13MesonSelectionMC::ConsiderGeneratedPi0(Int_t i, Double_t pt, Bool_t primary, const EventFlags & flags) { // Reject MIPS and count again if (pt < 0.3) return; if (primary) fPrimaryPi0[kGenerated]->FillS(pt); else fSecondaryPi0[kGenerated]->FillS(pt); AliAODMCParticle * parent = GetParent(i, flags.fMcParticles); if (!parent) return; Int_t pcode = parent->GetPdgCode(); fPi0Sources[Int_t(primary)]->Fill(pcode); if (primary) { fPrimaryPi0[kGenerated]->Fill(pcode, pt); return; } // Only for decay pi0s // if (!IsPrimary(parent)) { fSecondaryPi0[kGenerated]->Fill(pcode, pt); return; } fFeedDownPi0[kGenerated]->FillAll(pcode, pt); } //________________________________________________________________ AliAODMCParticle * AliPP13MesonSelectionMC::GetParent(Int_t label, Int_t & plabel, TClonesArray * particles) const { if (label <= -1) return 0; // Int_t primLabel = cluster->GetLabelAt(0) ; // Particle # reached PHOS front surface AliAODMCParticle * particle = dynamic_cast<AliAODMCParticle * >(particles->At(label)); if (!particle) return 0; plabel = particle->GetMother(); if (plabel <= -1) return 0; AliAODMCParticle * parent = dynamic_cast<AliAODMCParticle * >(particles->At(plabel)); return parent; } //________________________________________________________________ Bool_t AliPP13MesonSelectionMC::IsPrimary(const AliAODMCParticle * particle) const { // Look what particle left vertex (e.g. with vertex with radius <1 cm) Double_t rcut = 1.; Double_t r2 = particle->Xv() * particle->Xv() + particle->Yv() * particle->Yv() ; return r2 < rcut * rcut; }
[ "okovalen@cern.ch" ]
okovalen@cern.ch
e15016511b6a3611acd5adb4535a78838c5edd38
e45e27e372cb077a0288e2dbfefa9b19c3b50344
/libs/ObjectViewerLibrary/object_viewer/canvas3d/canvas_3d.cpp
f109e663b333e85f680cd0dd05444edcc964a998
[ "Apache-2.0" ]
permissive
Engilian/3DObjectViewer
00a89617749c1d75f70ce3eaa78a1364b19723cf
586c95bdde320c3996ac0628369a2ce16b6f4d27
refs/heads/master
2021-01-02T22:53:07.254293
2018-03-25T14:01:17
2018-03-25T14:01:17
99,410,712
0
0
null
null
null
null
UTF-8
C++
false
false
6,245
cpp
#include "canvas_3d.h" #include <QColor> #include <QPainter> #include <thread> Canvas3D::Canvas3D() : QOpenGLWidget(), __mainCamera(0), __skyBox(0) { connect ( &__repaintTimer, SIGNAL(timeout()), this, SLOT(updateCanvas())); __repaintTimer.start ( 1000.0 / 60.0 ); std::thread th( std::bind( &Canvas3D::__checkFps, this ) ); th.detach (); } Canvas3D::~Canvas3D() { if ( __mainCamera ) { delete __mainCamera; } if ( __skyBox ) { delete __skyBox; } if ( __threadRunInfo.isActive ) { __threadRunInfo.isActive = false; while ( __threadRunInfo.isRuning ) std::this_thread::sleep_for( std::chrono::milliseconds( 200 ) ); } } QList<Object3D> *Canvas3D::objects() { return &__objects; } ISkyBox *Canvas3D::skybox() const { return __skyBox; } void Canvas3D::setSkyBox(ISkyBox *skybox) { __skyBox = skybox; } void Canvas3D::destroySkyBox() { if ( __skyBox ) { delete __skyBox; __skyBox = nullptr; } } void Canvas3D::initDefaultSkyBox() { __skyBox = new SkyBoxSixTextutes( 500.0f ); } Camera3D *Canvas3D::mainCamera() const { return __mainCamera; } void Canvas3D::initializeGL() { QColor clearColor( Qt::black ); glClearColor( clearColor.red(), clearColor.green(), clearColor.blue(), 1 ); glEnable( GL_DEPTH_TEST ); // glEnable( GL_CULL_FACE ); initShaders(); __mainCamera = new Camera3D(); __mainCamera->translate( QVector3D( 0.0f, 0.0f, -10.0f ) ); emit InitGL(); } void Canvas3D::resizeGL(int w, int h) { float aspect = w / (float)h; __projection.setToIdentity(); __projection.perspective( __viewingAngle, aspect, 0.1f, 2000.0f ); } void Canvas3D::paintGL() { ++__tempFps; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Отрисовка скайбокса if ( __skyBox ) { __skyBoxShaderProgram.bind(); if ( __mainCamera ) __mainCamera->draw( &__skyBoxShaderProgram, context()->functions() ); __skyBoxShaderProgram.setUniformValue("u_projectionMatrix", __projection); __skyBox->draw( &__skyBoxShaderProgram, context()->functions() ); __skyBoxShaderProgram.release(); } // Отрисовка объектов __shaderProgram.bind(); __shaderProgram.setUniformValue("u_projectionMatrix", __projection); __shaderProgram.setUniformValue("u_lightPosition", QVector4D(0.0, 0.0, 0.0, 10.0)); // x,y,z,1.0 - так как вершина а не вектор __shaderProgram.setUniformValue("u_lightPower", 5.0f); __shaderProgram.setUniformValue("u_colorSpecular", QVector4D(1.0, 0.0, 1.0, 1.0)); // цвет бликов if ( __mainCamera ) __mainCamera->draw( &__shaderProgram, context()->functions() ); for ( const Object3D &obj: __objects ) { obj.get()->draw( &__shaderProgram, context()->functions() ); } __shaderProgram.release(); __waitToUpdate = false; } void Canvas3D::initShaders() { if ( !__shaderProgram.addShaderFromSourceFile( QOpenGLShader::Vertex, ":/default_vertex_shader.vsh" ) ) { close(); } if ( !__shaderProgram.addShaderFromSourceFile( QOpenGLShader::Fragment, ":/default_fragmen_shader.fsh" ) ) { close(); } if ( !__shaderProgram.link() ) { close(); } if ( !__skyBoxShaderProgram.addShaderFromSourceFile( QOpenGLShader::Vertex, ":/skybox.vsh" ) ) { close(); } if ( !__skyBoxShaderProgram.addShaderFromSourceFile( QOpenGLShader::Fragment, ":/skybox.fsh" ) ) { close(); } if ( !__skyBoxShaderProgram.link() ) { close(); } } void Canvas3D::mouseReleaseEvent(QMouseEvent *event) { if ( event->buttons () == Qt::RightButton ) { if ( __mainCamera ) __mainCamera->resetRotation (); } } void Canvas3D::mousePressEvent ( QMouseEvent *event ) { if ( event->buttons () == Qt::LeftButton || event->button () == Qt::MidButton) { __mousePosition = QVector2D ( event->localPos () ); } else if ( event->buttons () == Qt::RightButton ) { if ( __mainCamera ) __mainCamera->resetRotation (); } event->accept (); } void Canvas3D::mouseMoveEvent ( QMouseEvent *event ) { if ( event->buttons () == Qt::LeftButton ) { QVector2D diff = QVector2D( event->localPos () ) - __mousePosition; __mousePosition = QVector2D( event->localPos () ); QVector2D diffX = QVector2D( diff.x(), 0 ); QVector2D diffY = QVector2D( 0, diff.y() ); float angleX = diffX.length () / 2.0f; float angleY = diffY.length () / 2.0f; QVector3D axisX = QVector3D( diffX.y (), diffX.x (), 0.0 ); __mainCamera->rotate( QQuaternion::fromAxisAndAngle ( axisX, angleX ) ); QVector3D axisY = QVector3D( diffY.y (), diffY.x (), 0.0 ); __mainCamera->rotate( QQuaternion::fromAxisAndAngle ( axisY, angleY ) ); } else if ( event->buttons () == Qt::MidButton ) { QVector2D diff = QVector2D( event->localPos () ) - __mousePosition; __mousePosition = QVector2D( event->localPos () ); QVector3D vector( diff.x () / 250.0f, -diff.y () / 250.0f, 0 ); __mainCamera->move( vector ); } } void Canvas3D::wheelEvent ( QWheelEvent *event ) { if ( event->delta() > 0 ) { QVector3D vector( 0.0, 0.0, 0.25 ); __mainCamera->move( vector ); } else if ( event->delta() < 0 ) { QVector3D vector( 0.0, 0.0, -0.25 ); __mainCamera->move( vector ); } } void Canvas3D::__checkFps() { __threadRunInfo.isActive = true; __threadRunInfo.isRuning = true; while ( __threadRunInfo.isActive ) { __fps = __tempFps; __tempFps = 0; emit Fps ( __fps ); std::this_thread::sleep_for( std::chrono::milliseconds( 1000 ) ); } __threadRunInfo.isRuning = false; } void Canvas3D::updateCanvas() { if ( !__waitToUpdate ) { __waitToUpdate = true; update (); } } int Canvas3D::viewingAngle() const { return __viewingAngle; } void Canvas3D::setViewingAngle(int viewingAngle) { __viewingAngle = viewingAngle; resizeGL ( width (), height () ); } int Canvas3D::fps() const { return __fps; }
[ "engilian@gmail.com" ]
engilian@gmail.com
3fe7b6e291195206892d940353c6080f1022adbf
a6a7b8742f5299e6537fa8065eff71d65132ea1a
/Week-Of-Code-35/surface_area_3d.cpp
4517c1a01cee643a4b330967c0cb45b3a72f672c
[]
no_license
blackenwhite/Competitive-Coding
bb25994a9ffe3c8ac1476b4b11640a01f10e36e7
c95ecfc1dfc7879c02899341083569a4e60da2f8
refs/heads/master
2021-05-19T08:23:41.785230
2020-04-02T13:12:04
2020-04-02T13:12:04
251,603,623
0
0
null
2020-03-31T12:59:16
2020-03-31T12:59:16
null
UTF-8
C++
false
false
2,643
cpp
#include <bits/stdc++.h> using namespace std; // long long surfaceArea(vector < vector<int> > A,int h,int w) { // // Complete this function // long long area = 2*h*w; // for(int i = 0; i < h; i++) // { // long long rowSum = 0; // for(int j = 0; j < w; j++) // { // if(A[i][j] > rowSum ) // rowSum = A[i][j]; // } // area += (rowSum*2); // } // for(int i = 0; i < w; i++) // { // long long rowSum = 0; // for(int j = 0; j < h; j++) // { // if(A[j][i] > rowSum ) // rowSum = A[j][i]; // } // area += (rowSum*2); // } // for(int i = 0; i < h; i++) // { // long long inBetween = 0; // for(int j = 1; j < w-1; j++) // { // if(A[i][j-1] > A[i][j] && A[i][j] < A[i][j+1]) // { // // cout<<A[i][j-1]<<" "<<A[i][j]<<" "<<A[i][j+1]<<endl; // int min_val = min(A[i][j-1],A[i][j+1]); // inBetween += (abs(min_val - A[i][j]) * 2); // } // } // // cout<<inBetween<<endl; // area += (inBetween); // } // for(int i = 0; i < w ; i++) // { // long long inBetween = 0; // for(int j = 1; j < h-1; j++) // { // if(A[j][i] < A[j-1][i] && A[j][i] < A[j+1][i]) // { // int min_val = min(A[j+1][i],A[j-1][i]); // inBetween += (abs(min_val - A[j][i])*2); // } // } // // cout<<inBetween<<endl; // area += (inBetween); // } // return area; // } long surfaceArea(vector < vector<int> > A,int h,int w) { // Complete this function long sum = 2*h*w; for(int i = 0; i < h; i++) { sum += (A[i][0]+A[i][w-1]); for(int j = 1; j < w ; j++) { sum += abs(A[i][j] - A[i][j-1]); } // cout<<sum<<endl; } for(int i = 0; i < w; i++) { sum += (A[0][i]+A[h-1][i]); for(int j = 1; j < h ; j++) { sum += abs(A[j][i] - A[j-1][i]); } // cout<<sum<<endl; } return sum; } int main() { int H; int W; cin >> H >> W; vector< vector<int> > A(H,vector<int>(W)); for(int A_i = 0;A_i < H;A_i++){ for(int A_j = 0;A_j < W;A_j++){ cin >> A[A_i][A_j]; } } if(H == 1 && W == 1) cout<<A[0][0]*6<<endl; else { long long result = surfaceArea(A,H,W); cout << result << endl; } return 0; }
[ "amrithchallenger@gmail.com" ]
amrithchallenger@gmail.com
630947e4f36394e9a176defa24f86d442ab5a671
50da0acf009b213f905f720576b175574644a620
/ex06/template/src/reduction_cpu.cpp
36fb5c26cef7b5f9d5354b07533b7f2043968744
[]
no_license
danielbarley/GPU_WS2021
539ea0f7a1d8a9bce1c6957d6ac0fa31bd7aec01
91148232e09a78b651323d73ba85a0dfd74e98ec
refs/heads/main
2023-02-21T08:53:05.176813
2021-01-26T06:26:14
2021-01-26T06:26:14
313,293,968
0
0
null
null
null
null
UTF-8
C++
false
false
1,007
cpp
#include <iostream> #include <string> #include <vector> #include <chTimer.hpp> using namespace std; void printHelp(char const* argv) { std::cout << "Help:" << std::endl << " Usage: " << std::endl << " " << argv << " [<num-elements>]" << std::endl; } float reduction(std::vector<float> vec) { float sum = 0; for (auto element: vec) { sum += element; } return sum; } int main(int argc, char** argv) { if (argc != 2) printHelp(argv[0]); long N = stol(argv[1]); vector<float> vec(N, 1); ChTimer reductionTimer; reductionTimer.start(); float result = reduction(vec); reductionTimer.stop(); if (result != N) { std::cout << "Wrong reduction result" << std::endl; return -1; } std::cout << "reduction took " << reductionTimer.getTime() * 1e3 << " ms" << std::endl; std::cout << "reduction bandwidth: " << reductionTimer.getBandwidth(N * sizeof(float)) * 1e-9 << " GB / s" << std::endl; }
[ "benjamin.maier@hexagon.com" ]
benjamin.maier@hexagon.com
ed25b00c9db956ca38c617b1506f4b2c5abb1772
b20d698f165eb105aa6f02a684fda4bcfd4e0ffc
/Source/3rdParty/PlayRho/Dynamics/WorldBody.cpp
94b0f87214580468e826c492e8f8bd5e19fcd373
[ "MIT" ]
permissive
Karshilov/Dorothy-SSR
139fef1a6074b060aae9bb77ef95b44d0d1e8e12
cce19ed2218d76f941977370f6b3894e2f87236a
refs/heads/master
2023-06-19T15:56:47.177341
2021-07-15T03:08:10
2021-07-15T03:08:10
384,729,588
0
0
NOASSERTION
2021-07-10T15:25:37
2021-07-10T15:25:36
null
UTF-8
C++
false
false
17,823
cpp
/* * Original work Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * Modified work Copyright (c) 2020 Louis Langholtz https://github.com/louis-langholtz/PlayRho * * 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 "PlayRho/Dynamics/WorldBody.hpp" #include "PlayRho/Dynamics/WorldShape.hpp" #include "PlayRho/Dynamics/World.hpp" #include "PlayRho/Dynamics/Body.hpp" #include <algorithm> #include <functional> #include <memory> using std::for_each; using std::remove; using std::sort; using std::transform; using std::unique; namespace playrho { namespace d2 { using playrho::size; BodyCounter GetBodyRange(const World& world) noexcept { return world.GetBodyRange(); } std::vector<BodyID> GetBodies(const World& world) noexcept { return world.GetBodies(); } std::vector<BodyID> GetBodiesForProxies(const World& world) noexcept { return world.GetBodiesForProxies(); } BodyID CreateBody(World& world, const Body& body, bool resetMassData) { const auto id = world.CreateBody(body); if (resetMassData) { ResetMassData(world, id); } return id; } const Body& GetBody(const World& world, BodyID id) { return world.GetBody(id); } void SetBody(World& world, BodyID id, const Body& body) { world.SetBody(id, body); } void Destroy(World& world, BodyID id) { world.Destroy(id); } void Attach(World& world, BodyID id, ShapeID shapeID, bool resetMassData) { auto body = GetBody(world, id); body.Attach(shapeID); SetBody(world, id, body); if (resetMassData) { ResetMassData(world, id); } } void Attach(World& world, BodyID id, const Shape& shape, bool resetMassData) { Attach(world, id, CreateShape(world, shape), resetMassData); } bool Detach(World& world, BodyID id, ShapeID shapeID, bool resetMassData) { auto body = GetBody(world, id); if (body.Detach(shapeID)) { SetBody(world, id, body); if (resetMassData) { ResetMassData(world, id); } return true; } return false; } bool Detach(World& world, BodyID id, bool resetMassData) { auto anyDetached = false; while (!GetShapes(world, id).empty()) { anyDetached |= Detach(world, id, GetShapes(world, id).back()); } if (anyDetached && resetMassData) { ResetMassData(world, id); } return anyDetached; } std::vector<ShapeID> GetShapes(const World& world, BodyID id) { return world.GetShapes(id); } LinearAcceleration2 GetLinearAcceleration(const World& world, BodyID id) { return GetLinearAcceleration(GetBody(world, id)); } AngularAcceleration GetAngularAcceleration(const World& world, BodyID id) { return GetAngularAcceleration(GetBody(world, id)); } Acceleration GetAcceleration(const World& world, BodyID id) { const auto& body = GetBody(world, id); return Acceleration{GetLinearAcceleration(body), GetAngularAcceleration(body)}; } void SetAcceleration(World& world, BodyID id, LinearAcceleration2 linear, AngularAcceleration angular) { auto body = GetBody(world, id); SetAcceleration(body, linear, angular); SetBody(world, id, body); } void SetAcceleration(World& world, BodyID id, LinearAcceleration2 value) { auto body = GetBody(world, id); SetAcceleration(body, value); SetBody(world, id, body); } void SetAcceleration(World& world, BodyID id, AngularAcceleration value) { auto body = GetBody(world, id); SetAcceleration(body, value); SetBody(world, id, body); } void SetAcceleration(World& world, BodyID id, Acceleration value) { auto body = GetBody(world, id); SetAcceleration(body, value); SetBody(world, id, body); } void SetTransformation(World& world, BodyID id, Transformation value) { auto body = GetBody(world, id); SetTransformation(body, value); SetBody(world, id, body); } void SetLocation(World& world, BodyID id, Length2 value) { auto body = GetBody(world, id); SetLocation(body, value); SetBody(world, id, body); } void SetAngle(World& world, BodyID id, Angle value) { auto body = GetBody(world, id); SetAngle(body, value); SetBody(world, id, body); } void RotateAboutWorldPoint(World& world, BodyID body, Angle amount, Length2 worldPoint) { const auto xfm = GetTransformation(world, body); const auto p = xfm.p - worldPoint; const auto c = cos(amount); const auto s = sin(amount); const auto x = GetX(p) * c - GetY(p) * s; const auto y = GetX(p) * s + GetY(p) * c; const auto pos = Length2{x, y} + worldPoint; const auto angle = GetAngle(xfm.q) + amount; SetTransform(world, body, pos, angle); } void RotateAboutLocalPoint(World& world, BodyID body, Angle amount, Length2 localPoint) { RotateAboutWorldPoint(world, body, amount, GetWorldPoint(world, body, localPoint)); } Acceleration CalcGravitationalAcceleration(const World& world, BodyID body) { const auto m1 = GetMass(world, body); if (m1 != 0_kg) { auto sumForce = Force2{}; const auto loc1 = GetLocation(world, body); for (const auto& b2: world.GetBodies()) { if (b2 == body) { continue; } const auto m2 = GetMass(world, b2); const auto delta = GetLocation(world, b2) - loc1; const auto dir = GetUnitVector(delta); const auto rr = GetMagnitudeSquared(delta); // Uses Newton's law of universal gravitation: F = G * m1 * m2 / rr. // See: https://en.wikipedia.org/wiki/Newton%27s_law_of_universal_gravitation // Note that BigG is typically very small numerically compared to either mass // or the square of the radius between the masses. That's important to recognize // in order to avoid operational underflows or overflows especially when // playrho::Real has less exponential range like when it's defined to be float // instead of double. The operational ordering is deliberately established here // to help with this. const auto orderedMass = std::minmax(m1, m2); const auto f = (BigG * std::get<0>(orderedMass)) * (std::get<1>(orderedMass) / rr); sumForce += f * dir; } // F = m a... i.e. a = F / m. return Acceleration{sumForce / m1, 0 * RadianPerSquareSecond}; } return Acceleration{}; } BodyCounter GetWorldIndex(const World&, BodyID id) noexcept { return to_underlying(id); } BodyType GetType(const World& world, BodyID id) { return GetType(GetBody(world, id)); } void SetType(World& world, BodyID id, BodyType value, bool resetMassData) { auto body = GetBody(world, id); if (GetType(body) != value) { SetType(body, value); world.SetBody(id, body); if (resetMassData) { ResetMassData(world, id); } } } Transformation GetTransformation(const World& world, BodyID id) { return GetTransformation(GetBody(world, id)); } Angle GetAngle(const World& world, BodyID id) { return GetAngle(GetBody(world, id)); } Velocity GetVelocity(const World& world, BodyID id) { return GetVelocity(GetBody(world, id)); } void SetVelocity(World& world, BodyID id, const Velocity& value) { auto body = GetBody(world, id); SetVelocity(body, value); world.SetBody(id, body); } void SetVelocity(World& world, BodyID id, const LinearVelocity2& value) { auto body = GetBody(world, id); SetVelocity(body, Velocity{value, GetAngularVelocity(body)}); world.SetBody(id, body); } void SetVelocity(World& world, BodyID id, AngularVelocity value) { auto body = GetBody(world, id); SetVelocity(body, Velocity{GetLinearVelocity(body), value}); world.SetBody(id, body); } bool IsEnabled(const World& world, BodyID id) { return IsEnabled(GetBody(world, id)); } void SetEnabled(World& world, BodyID id, bool value) { auto body = GetBody(world, id); SetEnabled(body, value); world.SetBody(id, body); } bool IsAwake(const World& world, BodyID id) { return IsAwake(GetBody(world, id)); } void SetAwake(World& world, BodyID id) { auto body = GetBody(world, id); SetAwake(body); world.SetBody(id, body); } void UnsetAwake(World& world, BodyID id) { auto body = GetBody(world, id); UnsetAwake(body); world.SetBody(id, body); } bool IsMassDataDirty(const World& world, BodyID id) { return IsMassDataDirty(GetBody(world, id)); } bool IsFixedRotation(const World& world, BodyID id) { return IsFixedRotation(GetBody(world, id)); } void SetFixedRotation(World& world, BodyID id, bool value) { auto body = GetBody(world, id); if (IsFixedRotation(body) != value) { SetFixedRotation(body, value); world.SetBody(id, body); ResetMassData(world, id); } } Length2 GetWorldCenter(const World& world, BodyID id) { return GetWorldCenter(GetBody(world, id)); } InvMass GetInvMass(const World& world, BodyID id) { return GetInvMass(GetBody(world, id)); } InvRotInertia GetInvRotInertia(const World& world, BodyID id) { return GetInvRotInertia(GetBody(world, id)); } Length2 GetLocalCenter(const World& world, BodyID id) { return GetLocalCenter(GetBody(world, id)); } MassData ComputeMassData(const World& world, BodyID id) { auto mass = 0_kg; auto I = RotInertia{0}; auto weightedCenter = Length2{}; for (const auto& shapeId: GetShapes(world, id)) { const auto& shape = GetShape(world, shapeId); if (GetDensity(shape) > 0_kgpm2) { const auto massData = GetMassData(shape); mass += Mass{massData.mass}; weightedCenter += Real{massData.mass / Kilogram} * massData.center; I += RotInertia{massData.I}; } } const auto center = (mass > 0_kg)? (weightedCenter / (Real{mass/1_kg})): Length2{}; return MassData{center, mass, I}; } void SetMassData(World& world, BodyID id, const MassData& massData) { auto body = GetBody(world, id); if (!body.IsAccelerable()) { body.SetInvMassData(InvMass{}, InvRotInertia{}); if (!body.IsSpeedable()) { body.SetSweep(Sweep{Position{GetLocation(body), GetAngle(body)}}); } world.SetBody(id, body); return; } const auto mass = (massData.mass > 0_kg)? Mass{massData.mass}: 1_kg; const auto invMass = Real{1} / mass; auto invRotInertia = Real(0) / (1_m2 * 1_kg / SquareRadian); if ((massData.I > RotInertia{0}) && (!body.IsFixedRotation())) { const auto lengthSquared = GetMagnitudeSquared(massData.center); // L^2 M QP^-2 const auto I = RotInertia{massData.I} - RotInertia{(mass * lengthSquared) / SquareRadian}; assert(I > RotInertia{0}); invRotInertia = Real{1} / I; } body.SetInvMassData(invMass, invRotInertia); // Move center of mass. const auto oldCenter = GetWorldCenter(body); SetSweep(body, Sweep{ Position{Transform(massData.center, GetTransformation(body)), GetAngle(body)}, massData.center }); // Update center of mass velocity. const auto newCenter = GetWorldCenter(body); const auto deltaCenter = newCenter - oldCenter; auto newVelocity = body.GetVelocity(); newVelocity.linear += GetRevPerpendicular(deltaCenter) * (newVelocity.angular / Radian); body.JustSetVelocity(newVelocity); world.SetBody(id, body); } std::vector<std::pair<BodyID, JointID>> GetJoints(const World& world, BodyID id) { return world.GetJoints(id); } bool IsSpeedable(const World& world, BodyID id) { return IsSpeedable(GetBody(world, id)); } bool IsAccelerable(const World& world, BodyID id) { return IsAccelerable(GetBody(world, id)); } bool IsImpenetrable(const World& world, BodyID id) { return IsImpenetrable(GetBody(world, id)); } void SetImpenetrable(World& world, BodyID id) { auto body = GetBody(world, id); SetImpenetrable(body); world.SetBody(id, body); } void UnsetImpenetrable(World& world, BodyID id) { auto body = GetBody(world, id); UnsetImpenetrable(body); world.SetBody(id, body); } bool IsSleepingAllowed(const World& world, BodyID id) { return IsSleepingAllowed(GetBody(world, id)); } void SetSleepingAllowed(World& world, BodyID id, bool value) { auto body = GetBody(world, id); SetSleepingAllowed(body, value); world.SetBody(id, body); } Frequency GetLinearDamping(const World& world, BodyID id) { return GetLinearDamping(GetBody(world, id)); } void SetLinearDamping(World& world, BodyID id, NonNegative<Frequency> value) { auto body = GetBody(world, id); SetLinearDamping(body, value); world.SetBody(id, body); } Frequency GetAngularDamping(const World& world, BodyID id) { return GetAngularDamping(GetBody(world, id)); } void SetAngularDamping(World& world, BodyID id, NonNegative<Frequency> value) { auto body = GetBody(world, id); SetAngularDamping(body, value); world.SetBody(id, body); } std::vector<KeyedContactPtr> GetContacts(const World& world, BodyID id) { return world.GetContacts(id); } Force2 GetCentripetalForce(const World& world, BodyID id, Length2 axis) { // For background on centripetal force, see: // https://en.wikipedia.org/wiki/Centripetal_force // Force is M L T^-2. const auto velocity = GetLinearVelocity(world, id); const auto magnitudeOfVelocity = GetMagnitude(GetVec2(velocity)) * MeterPerSecond; const auto location = GetLocation(world, id); const auto mass = GetMass(world, id); const auto delta = axis - location; const auto invRadius = Real{1} / GetMagnitude(delta); const auto dir = delta * invRadius; return Force2{dir * mass * Square(magnitudeOfVelocity) * invRadius}; } void ApplyForce(World& world, BodyID id, Force2 force, Length2 point) { // Torque is L^2 M T^-2 QP^-1. const auto& body = GetBody(world, id); const auto linAccel = LinearAcceleration2{force * GetInvMass(body)}; const auto invRotI = GetInvRotInertia(body); // L^-2 M^-1 QP^2 const auto dp = Length2{point - GetWorldCenter(body)}; // L const auto cp = Torque{Cross(dp, force) / Radian}; // L * M L T^-2 is L^2 M T^-2 // L^2 M T^-2 QP^-1 * L^-2 M^-1 QP^2 = QP T^-2; const auto angAccel = AngularAcceleration{cp * invRotI}; SetAcceleration(world, id, GetLinearAcceleration(world, id) + linAccel, GetAngularAcceleration(world, id) + angAccel); } void ApplyTorque(World& world, BodyID id, Torque torque) { const auto linAccel = GetLinearAcceleration(world, id); const auto invRotI = GetInvRotInertia(world, id); const auto angAccel = GetAngularAcceleration(world, id) + torque * invRotI; SetAcceleration(world, id, linAccel, angAccel); } void ApplyLinearImpulse(World& world, BodyID id, Momentum2 impulse, Length2 point) { auto body = GetBody(world, id); ApplyLinearImpulse(body, impulse, point); SetBody(world, id, body); } void ApplyAngularImpulse(World& world, BodyID id, AngularMomentum impulse) { auto body = GetBody(world, id); ApplyAngularImpulse(body, impulse); SetBody(world, id, body); } BodyCounter GetAwakeCount(const World& world) noexcept { const auto bodies = world.GetBodies(); return static_cast<BodyCounter>(count_if(cbegin(bodies), cend(bodies), [&](const auto &b) { return IsAwake(world, b); })); } BodyCounter Awaken(World& world) noexcept { // Can't use count_if since body gets modified. auto awoken = BodyCounter{0}; const auto bodies = world.GetBodies(); for_each(begin(bodies), end(bodies), [&world,&awoken](const auto &b) { if (::playrho::d2::Awaken(world, b)) { ++awoken; } }); return awoken; } void SetAccelerations(World& world, Acceleration acceleration) noexcept { const auto bodies = world.GetBodies(); for_each(begin(bodies), end(bodies), [&world, acceleration](const auto &b) { SetAcceleration(world, b, acceleration); }); } void SetAccelerations(World& world, LinearAcceleration2 acceleration) noexcept { const auto bodies = world.GetBodies(); for_each(begin(bodies), end(bodies), [&world, acceleration](const auto &b) { SetAcceleration(world, b, acceleration); }); } BodyID FindClosestBody(const World& world, Length2 location) noexcept { const auto bodies = world.GetBodies(); auto found = InvalidBodyID; auto minLengthSquared = std::numeric_limits<Area>::infinity(); for (const auto& body: bodies) { const auto bodyLoc = GetLocation(world, body); const auto lengthSquared = GetMagnitudeSquared(bodyLoc - location); if (minLengthSquared > lengthSquared) { minLengthSquared = lengthSquared; found = body; } } return found; } } // namespace d2 } // namespace playrho
[ "dragon-fly@qq.com" ]
dragon-fly@qq.com
251dbf0bd3457564ef56e5684d3ab0517c01ce2e
00da2c91f84bd67bbf8ca1289dc97ce02273d34f
/llvm_mode/dfsan_rt/sanitizer_common/sanitizer_libc.cc
4b462bfe97283299b5224cbabbb8181c184675d9
[ "NCSA", "Apache-2.0" ]
permissive
ChengyuSong/Kirenenko
3760b26062a80ff6892269cbc62b8f9326c769c1
3958161abff364fc67f2817e8fda7d1b57a1046e
refs/heads/master
2022-08-30T19:40:09.508196
2022-07-14T03:46:01
2022-07-14T03:46:01
222,802,397
72
16
Apache-2.0
2022-05-07T06:47:18
2019-11-19T22:30:48
C++
UTF-8
C++
false
false
7,028
cc
//===-- sanitizer_libc.cc -------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is shared between AddressSanitizer and ThreadSanitizer // run-time libraries. See sanitizer_libc.h for details. //===----------------------------------------------------------------------===// #include "sanitizer_allocator_internal.h" #include "sanitizer_common.h" #include "sanitizer_libc.h" namespace __sanitizer { s64 internal_atoll(const char *nptr) { return internal_simple_strtoll(nptr, nullptr, 10); } void *internal_memchr(const void *s, int c, uptr n) { const char *t = (const char *)s; for (uptr i = 0; i < n; ++i, ++t) if (*t == c) return reinterpret_cast<void *>(const_cast<char *>(t)); return nullptr; } void *internal_memrchr(const void *s, int c, uptr n) { const char *t = (const char *)s; void *res = nullptr; for (uptr i = 0; i < n; ++i, ++t) { if (*t == c) res = reinterpret_cast<void *>(const_cast<char *>(t)); } return res; } int internal_memcmp(const void* s1, const void* s2, uptr n) { const char *t1 = (const char *)s1; const char *t2 = (const char *)s2; for (uptr i = 0; i < n; ++i, ++t1, ++t2) if (*t1 != *t2) return *t1 < *t2 ? -1 : 1; return 0; } void *internal_memcpy(void *dest, const void *src, uptr n) { char *d = (char*)dest; const char *s = (const char *)src; for (uptr i = 0; i < n; ++i) d[i] = s[i]; return dest; } void *internal_memmove(void *dest, const void *src, uptr n) { char *d = (char*)dest; const char *s = (const char *)src; sptr i, signed_n = (sptr)n; CHECK_GE(signed_n, 0); if (d < s) { for (i = 0; i < signed_n; ++i) d[i] = s[i]; } else { if (d > s && signed_n > 0) for (i = signed_n - 1; i >= 0 ; --i) { d[i] = s[i]; } } return dest; } void *internal_memset(void* s, int c, uptr n) { // The next line prevents Clang from making a call to memset() instead of the // loop below. // FIXME: building the runtime with -ffreestanding is a better idea. However // there currently are linktime problems due to PR12396. char volatile *t = (char*)s; for (uptr i = 0; i < n; ++i, ++t) { *t = c; } return s; } uptr internal_strcspn(const char *s, const char *reject) { uptr i; for (i = 0; s[i]; i++) { if (internal_strchr(reject, s[i])) return i; } return i; } char* internal_strdup(const char *s) { uptr len = internal_strlen(s); char *s2 = (char*)InternalAlloc(len + 1); internal_memcpy(s2, s, len); s2[len] = 0; return s2; } int internal_strcmp(const char *s1, const char *s2) { while (true) { unsigned c1 = *s1; unsigned c2 = *s2; if (c1 != c2) return (c1 < c2) ? -1 : 1; if (c1 == 0) break; s1++; s2++; } return 0; } int internal_strncmp(const char *s1, const char *s2, uptr n) { for (uptr i = 0; i < n; i++) { unsigned c1 = *s1; unsigned c2 = *s2; if (c1 != c2) return (c1 < c2) ? -1 : 1; if (c1 == 0) break; s1++; s2++; } return 0; } char* internal_strchr(const char *s, int c) { while (true) { if (*s == (char)c) return const_cast<char *>(s); if (*s == 0) return nullptr; s++; } } char *internal_strchrnul(const char *s, int c) { char *res = internal_strchr(s, c); if (!res) res = const_cast<char *>(s) + internal_strlen(s); return res; } char *internal_strrchr(const char *s, int c) { const char *res = nullptr; for (uptr i = 0; s[i]; i++) { if (s[i] == c) res = s + i; } return const_cast<char *>(res); } uptr internal_strlen(const char *s) { uptr i = 0; while (s[i]) i++; return i; } uptr internal_strlcat(char *dst, const char *src, uptr maxlen) { const uptr srclen = internal_strlen(src); const uptr dstlen = internal_strnlen(dst, maxlen); if (dstlen == maxlen) return maxlen + srclen; if (srclen < maxlen - dstlen) { internal_memmove(dst + dstlen, src, srclen + 1); } else { internal_memmove(dst + dstlen, src, maxlen - dstlen - 1); dst[maxlen - 1] = '\0'; } return dstlen + srclen; } char *internal_strncat(char *dst, const char *src, uptr n) { uptr len = internal_strlen(dst); uptr i; for (i = 0; i < n && src[i]; i++) dst[len + i] = src[i]; dst[len + i] = 0; return dst; } uptr internal_strlcpy(char *dst, const char *src, uptr maxlen) { const uptr srclen = internal_strlen(src); if (srclen < maxlen) { internal_memmove(dst, src, srclen + 1); } else if (maxlen != 0) { internal_memmove(dst, src, maxlen - 1); dst[maxlen - 1] = '\0'; } return srclen; } char *internal_strncpy(char *dst, const char *src, uptr n) { uptr i; for (i = 0; i < n && src[i]; i++) dst[i] = src[i]; internal_memset(dst + i, '\0', n - i); return dst; } uptr internal_strnlen(const char *s, uptr maxlen) { uptr i = 0; while (i < maxlen && s[i]) i++; return i; } char *internal_strstr(const char *haystack, const char *needle) { // This is O(N^2), but we are not using it in hot places. uptr len1 = internal_strlen(haystack); uptr len2 = internal_strlen(needle); if (len1 < len2) return nullptr; for (uptr pos = 0; pos <= len1 - len2; pos++) { if (internal_memcmp(haystack + pos, needle, len2) == 0) return const_cast<char *>(haystack) + pos; } return nullptr; } s64 internal_simple_strtoll(const char *nptr, const char **endptr, int base) { CHECK_EQ(base, 10); while (IsSpace(*nptr)) nptr++; int sgn = 1; u64 res = 0; bool have_digits = false; char *old_nptr = const_cast<char *>(nptr); if (*nptr == '+') { sgn = 1; nptr++; } else if (*nptr == '-') { sgn = -1; nptr++; } while (IsDigit(*nptr)) { res = (res <= UINT64_MAX / 10) ? res * 10 : UINT64_MAX; int digit = ((*nptr) - '0'); res = (res <= UINT64_MAX - digit) ? res + digit : UINT64_MAX; have_digits = true; nptr++; } if (endptr) { *endptr = (have_digits) ? const_cast<char *>(nptr) : old_nptr; } if (sgn > 0) { return (s64)(Min((u64)INT64_MAX, res)); } else { return (res > INT64_MAX) ? INT64_MIN : ((s64)res * -1); } } bool mem_is_zero(const char *beg, uptr size) { CHECK_LE(size, 1ULL << FIRST_32_SECOND_64(30, 40)); // Sanity check. const char *end = beg + size; uptr *aligned_beg = (uptr *)RoundUpTo((uptr)beg, sizeof(uptr)); uptr *aligned_end = (uptr *)RoundDownTo((uptr)end, sizeof(uptr)); uptr all = 0; // Prologue. for (const char *mem = beg; mem < (char*)aligned_beg && mem < end; mem++) all |= *mem; // Aligned loop. for (; aligned_beg < aligned_end; aligned_beg++) all |= *aligned_beg; // Epilogue. if ((char*)aligned_end >= beg) for (const char *mem = (char*)aligned_end; mem < end; mem++) all |= *mem; return all == 0; } } // namespace __sanitizer
[ "csong@cs.ucr.edu" ]
csong@cs.ucr.edu
0ef7f47097752aaeb142d45e80f4918071ed21fd
5818af6730f02def65cfbb75150e80d006ae2c05
/tags/0.5/src/manzoni/dataProcessing/procDistrHisto.cc
f8eb10775b1e5ae4a3b34b429910c8c8601735b1
[]
no_license
chernals/manzoni
da4ed17cfaec2312028dbac46539efab4df30b9b
239d20182ae90fc757640274959443ccc439b2f5
refs/heads/master
2021-05-03T15:38:52.844743
2018-02-06T15:58:26
2018-02-06T15:58:26
120,482,907
0
0
null
null
null
null
UTF-8
C++
false
false
6,627
cc
#include <dataProcessing/procDistrHisto.h> ProcDistrHisto::ProcDistrHisto(ParticlesSet* set, std::string path,int h, std::vector<double> t) : part_set(set), xpath(path), histo_counter(h), tunes(t) { LOG(PROC_DISTR_HISTO, Instanciating ProcDistrHisto); store = part_set->getStore(); // Parameters readParameters(); hist_counter = 0; // Set ROOT options gROOT->SetStyle("Plain"); gStyle->SetPalette(1,0); gStyle->SetOptStat(0); gStyle->SetNumberContours(100); // Create the canvas int number_projections = projections.size(); if(number_projections % 2 == 1) { number_projections += 1; } number_projections /= 2; canvas = new TCanvas(title.c_str(),title.c_str(),2*350,number_projections*350); canvas->SetBorderMode(0); canvas->SetFillColor(kWhite); canvas->SetLeftMargin(0.13); canvas->SetRightMargin(100); canvas->SetBottomMargin(0.13); canvas->Divide(static_cast<const Int_t>(2),static_cast<Int_t>(number_projections)); LOG(PROC_DISTR_HISTO, ProcDistrHisto instanciated.); // Add the plot of the tune // TH1D* tune_plot = new TH1D("(axis).c_str()","_title.c_str()",300,0,20000); // tune_plot->GetXaxis()->SetTitle(axis.c_str()); //tune_plot->GetXaxis()->CenterTitle(); //tune_plot->GetXaxis()->SetTitleSize(static_cast<Float_t>(0.04)); // std::vector<double>::iterator i; // for(i=tunes.begin();i != tunes.end(); i++) // { // tune_plot->Fill(*i); // } // canvas->cd(1); // tune_plot-> Draw(); } ProcDistrHisto::~ProcDistrHisto() { LOG(PROC_DISTR_HISTO, Destructor called.); // Delete all histograms in the list std::list<TH2D*>::iterator i; for(i=hist_list.begin();i!=hist_list.end();i++) { delete *i; } delete canvas; } void ProcDistrHisto::readParameters() { LOG(PROC_DISTR_HISTO, Reading parameters); box_size = XMLInputParser::getInstance().getFirstTextd("./flows/alessandroFlow/windowSize"); LOG(PROC_DISTR_HISTO, Box size:); LOGV(PROC_DISTR_HISTO, d2s(box_size)); file = XMLInputParser::getInstance().getAttributeTextFromPath(xpath, "file"); title = XMLInputParser::getInstance().getAttributeTextFromPath(xpath, "title"); std::string p = xpath + "/projection"; projections = XMLInputParser::getInstance().getTextElementsFromPath(p); } void ProcDistrHisto::save() { LOG(PROC_DISTR_HISTO, Saving the canvas in the .pdf file.); // Save the canvas in a pdf file canvas->SaveAs((file+i2s(histo_counter)+".pdf").c_str(),"pdf"); } void ProcDistrHisto::draw() { std::vector<std::string>::iterator v; for(v=projections.begin();v != projections.end(); v++) { if((*v) == "XXP") { LOG(PROC_DISTR_HISTO, Creating histogram for X - XP); createHistogram("X","XP",X_PLANE,XP_PLANE); } else if((*v) == "XY") { if(part_set->getDims() == FOUR_DIMENSIONS || part_set->getDims() == SIX_DIMENSIONS) { LOG(PROC_DISTR_HISTO, Creating histogram for X - Y); createHistogram("X","Y",X_PLANE,Y_PLANE); } else { WARN(PROC_DISTR_HISTO, Invalid histogram requested for X - Y); } } else if((*v) == "XYP") { if(part_set->getDims() == FOUR_DIMENSIONS || part_set->getDims() ==SIX_DIMENSIONS) { LOG(PROC_DISTR_HISTO, Creating histogram for X - YP); createHistogram("X","YP",X_PLANE,YP_PLANE); } else { WARN(PROC_DISTR_HISTO, Invalid histogram requested for X - YP); } } else if((*v) == "YXP") { if(part_set->getDims() == FOUR_DIMENSIONS || part_set->getDims() == SIX_DIMENSIONS) { LOG(PROC_DISTR_HISTO, Creating histogram for Y - XP); createHistogram("Y","XP",Y_PLANE,XP_PLANE); } else { WARN(PROC_DISTR_HISTO, Invalid histogram requested for Y - XP); } } else if((*v) == "YYP") { if(part_set->getDims() == FOUR_DIMENSIONS || part_set->getDims() == SIX_DIMENSIONS) { LOG(PROC_DISTR_HISTO, Creating histogram for Y - YP); createHistogram("Y","YP",Y_PLANE,YP_PLANE); } else { WARN(PROC_DISTR_HISTO, Invalid histogram requested for Y - YP); } } else if((*v) == "XPYP") { if(part_set->getDims() == FOUR_DIMENSIONS || part_set->getDims() == SIX_DIMENSIONS) { LOG(PROC_DISTR_HISTO, Creating histogram for XP - YP); createHistogram("XP","YP",XP_PLANE,YP_PLANE); } else { WARN(PROC_DISTR_HISTO, Invalid histogram requested for XP - YP); } } else if((*v) == "ZZP") { if(part_set->getDims() == SIX_DIMENSIONS) { LOG(PROC_DISTR_HISTO, Creating histogram for Z - ZP); createHistogram("Z","ZP",4,5); } else { WARN(PROC_DISTR_HISTO, Invalid histogram requested for Z - ZP); } } } std::list<TH2D*>::iterator i; for(i=hist_list.begin();i!=hist_list.end();i++) { #ifdef DEBUG_FLAG Log::getInstance().log("PROC_DISTR_HISTO", "Adding histogram in pad", "id: ", hist_counter+1); #endif canvas->cd(hist_counter+1)->SetGrid(); (*i)->Draw("contz"); hist_counter++; } } void ProcDistrHisto::createHistogram(std::string axis1, std::string axis2, unsigned short int a1, unsigned short int a2) { TH2D* hist = new TH2D((axis1+axis2).c_str(),title.c_str(),300,-static_cast<double>(box_size),static_cast<double>(box_size),300,-static_cast<double>(box_size),static_cast<double>(box_size)); hist_list.push_back(hist); hist->GetXaxis()->SetTitle(axis1.c_str()); hist->GetXaxis()->CenterTitle(); hist->GetXaxis()->SetTitleSize(static_cast<Float_t>(0.04)); hist->GetYaxis()->SetTitle(axis2.c_str()); hist->GetYaxis()->CenterTitle(); hist->GetYaxis()->SetTitleSize(static_cast<Float_t>(0.04)); for(int i = 0; i < part_set->getParticlesNumber(); ++i) { hist->Fill(static_cast<double>((*store)(i,static_cast<int>(a1))),static_cast<double>((*store)(i,static_cast<int>(a2)))); } LOG(PROC_DISTR_HISTO, Histogram created); }
[ "cedric.hernalsteens@iba-group.com" ]
cedric.hernalsteens@iba-group.com
0b5111e8bda4a7c13556e0af2c591ca41211e248
5fb9cf1282f5f461d671bfd36b3cf10b03922e11
/test/src/safearray.cpp
1e51f153cdef26f9b36b0b5765e1cb0b635f3792
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
XLTools/autocom
24e63783913f96dc4617b3d66dac6c4bd056d7c5
e35f38815f89a959d828fb1530540063fb392d99
refs/heads/master
2021-01-12T02:05:18.826367
2017-06-20T22:19:54
2017-06-20T22:19:54
78,469,755
0
0
null
2017-01-09T21:16:12
2017-01-09T21:16:12
null
UTF-8
C++
false
false
1,095
cpp
// :copyright: (c) 2015-2016 The Regents of the University of California. // :license: MIT, see LICENSE.md for more details. /* * \addtogroup AutoComTests * \brief SaffeArray test suite. */ #include "autocom.hpp" #include <gtest/gtest.h> namespace com = autocom; struct X { int y; }; // TESTS // ----- TEST(SafeArrayBound, Methods) { com::SafeArrayBound bound; bound.lower() = 0; bound.upper() = 5; EXPECT_EQ(bound.size(), 5); EXPECT_EQ(bound.lower(), bound.lLbound); EXPECT_EQ(bound.upper(), bound.cElements); } TEST(SafeArray, Stl) { com::SafeArray<INT> array = {3, 4, 5}; EXPECT_EQ(array.size(), 3); EXPECT_EQ(array.front(), 3); EXPECT_EQ(array.back(), 5); EXPECT_EQ(array[0], 3); EXPECT_EQ(array[1], 4); EXPECT_EQ(array[2], 5); LONG index = 0; EXPECT_EQ(array[&index], 3); std::vector<INT> copy(array.begin(), array.end()); EXPECT_EQ(copy[0], 3); EXPECT_EQ(copy[2], 5); } TEST(SafeArray, Type) { EXPECT_EQ(com::SafeArray<X>::vt, VT_RECORD); EXPECT_EQ(com::SafeArray<INT>::vt, VT_INT); }
[ "ahuszagh@ahuszagh.localdomain" ]
ahuszagh@ahuszagh.localdomain
042bea3072838413d3731ae79cda2b6f54f84971
2f556a9a94bd39e68225c894c80ba3f015b37e91
/Example-073/src/main.cpp
19c6b507440822213f26041ca00c553756dd7b08
[]
no_license
wesenu/C_plus_plus_examples
4ac7255446caffd67e8ce04f587e657d8d0d1b8f
0cce0d44e223b779244616a25c511738b11d3574
refs/heads/master
2023-03-17T07:52:00.203733
2017-07-22T15:11:41
2017-07-22T15:11:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,661
cpp
/************************************************************************************************** * Examples in the C++ language (the 'Example-073' Test). * * GitHub repository: http://github.com/davidcanino/C_plus_plus_examples * * Created by David Canino (canino.david@gmail.com), June 2017 * * main.cpp - the source file, implementing the main function for the 'Example-073' Test. **************************************************************************************************/ #include <cstdlib> #include <iostream> #include <queue> #include <list> using namespace std; /// The main function for the <i>'Example-073'</i> Test. int main(void) { /* This is the 'Example-073' Test, where the 'queue' containers are validated. */ cout<<endl<<"\tThis is the 'Example-073' Test in the C++ language."<<endl<<endl; cout.flush(); /* TASK #1: validating the empty constructor for the 'queue' containers. */ cout<<"\tCreating the empty queue 'q0' of 'int' values ... "; queue<int> q0; cout<<"ok"<<endl; cout<<"\t#values in the queue 'q0' is "<<q0.size()<<"."<<endl; if(q0.empty()==true) cout<<"\tThe queue 'q0' is empty."<<endl<<endl; else cout<<"\tThe queue 'q0' is not empty."<<endl<<endl; cout << "\tPress the RETURN key to continue ... "; cin.get(); cout << endl; cout.flush(); /* TASK #2: adding several 'int' values to the queue 'q0'. */ cout<<"\tAdding several 'int' values to the queue 'q0' ... "; q0.emplace(11); q0.emplace(3); q0.emplace(-1); q0.push(5); q0.push(6); cout<<"ok"<<endl; cout<<"\t#values in the queue 'q0' is "<<q0.size()<<"."<<endl; if(q0.empty()==true) cout<<"\tThe queue 'q0' is empty."<<endl; else cout<<"\tThe queue 'q0' is not empty."<<endl; cout.flush(); cout<<"\tThe first 'int' value in the queue 'q0' is "<<q0.front()<<"."<<endl; cout<<"\tThe last 'int' value in the queue 'q0' is "<<q0.back()<<"."<<endl; cout<<"\tRemoving and visiting iteratively all 'int' values in the queue 'q0' (as follows):"; while(!q0.empty()) { cout<<" "<<q0.front(); q0.pop(); } /* At the end, the queue 'q0' should be empty! */ cout<<"."<<endl<<"\t#values in the queue 'q0' is "<<q0.size()<<"."<<endl; if(q0.empty()==true) cout<<"\tThe queue 'q0' is empty."<<endl<<endl; else cout<<"\tThe queue 'q0' is not empty."<<endl<<endl; cout << "\tPress the RETURN key to continue ... "; cin.get(); cout << endl; cout.flush(); /* TASK #3: validating the constructor for the 'queue' containers, starting from another container (e.g., the 'list' container). */ cout<<"\tCreating the new queue 'q1' by initializing its content through another container ... "; queue<int,list<int>> q1(list<int>(2,100)); cout<<"ok"<<endl; cout<<"\t#values in the queue 'q1' is "<<q1.size()<<"."<<endl; if(q1.empty()==true) cout<<"\tThe queue 'q1' is empty."<<endl<<endl; else cout<<"\tThe queue 'q1' is not empty."<<endl<<endl; cout << "\tPress the RETURN key to continue ... "; cin.get(); cout << endl; cout.flush(); /* TASK #4: validating the 'copy' constructor for the 'queue' containers. */ cout<<"\tCreating the new queue 'q2' as the copy of the queue 'q1' ... "; queue<int,list<int>> q2=queue<int,list<int>>(q1); cout<<"ok"<<endl; cout<<"\t#values in the queue 'q2' is "<<q2.size()<<"."<<endl; if(q2.empty()==true) cout<<"\tThe queue 'q2' is empty."<<endl; else cout<<"\tThe queue 'q2' is not empty."<<endl; if(q1==q2) cout<<"\tThe queue 'q1' is 'the same as' the queue 'q2' (with respect to the '==' operator)."<<endl<<endl; else cout<<"\tThe queue 'q1' is not 'the same as' the queue 'q2' (with respect to the '==' operator)."<<endl<<endl; cout << "\tPress the RETURN key to continue ... "; cin.get(); cout << endl; cout.flush(); /* TASK #5: allocating and initializing a new queue 'q3'! */ cout<<"\tAllocating and initializing the new queue 'q3' ... "; queue<int> *q3=nullptr; q3=new queue<int>(); for(int k=0;k<6;k++) q3->emplace(k); cout<<"ok"<<endl; cout.flush(); cout<<"\t#values in the queue 'q3' is "<<q3->size()<<"."<<endl; if(q3->empty()==true) cout<<"\tThe queue 'q3' is empty."<<endl; else cout<<"\tThe queue 'q3' is not empty."<<endl; cout<<"\t#values in the queue 'q0' is "<<q0.size()<<"."<<endl; if(q0.empty()==true) cout<<"\tThe queue 'q0' is empty."<<endl<<endl; else cout<<"\tThe queue 'q0' is not empty."<<endl<<endl; cout << "\tPress the RETURN key to continue ... "; cin.get(); cout << endl; cout.flush(); /* TASK #6: swapping the content of the queues 'q0' and 'q3'. */ cout<<"\t#values in the queue 'q0' is "<<q0.size()<<"."<<endl; if(q0.empty()==true) cout<<"\tThe queue 'q0' is empty."<<endl; else cout<<"\tThe queue 'q0' is not empty."<<endl; cout<<"\t#values in the queue 'q3' is "<<q3->size()<<"."<<endl; if(q3->empty()==true) cout<<"\tThe queue 'q3' is empty."<<endl; else cout<<"\tThe queue 'q3' is not empty."<<endl; cout<<"\tThe 'int' values in the queue 'q0':"<<endl<<endl; if(q0==(*q3)) cout<<"\t\t-) are 'the same as' the 'int' values in the queue 'q3' (see the '==' operator);"<<endl; else cout<<"\t\t-) are not 'the same as' the 'int' values in the queue 'q3' (see the '==' operator);"<<endl; if(q0!=(*q3)) cout<<"\t\t-) are not 'the same as' the 'int' values in the queue 'q3' (see the '!=' operator);"<<endl; else cout<<"\t\t-) are 'the same as' the 'int' values in the queue 'q3' (see the '!=' operator);"<<endl; if(q0<(*q3)) cout<<"\t\t-) are 'strictly less than' the 'int' values in the queue 'q3' (see the '<' operator);"<<endl; else cout<<"\t\t-) are not 'strictly less than' the 'int' values in the queue 'q3' (see the '<' operator);"<<endl; if(q0>(*q3)) cout<<"\t\t-) are 'strictly greater than' the 'int' values in the queue 'q3' (see the '>' operator);"<<endl; else cout<<"\t\t-) are not 'strictly greater than' the 'int' values in the queue 'q3' (see the '>' operator);"<<endl; if(q0<=(*q3)) cout<<"\t\t-) may be either 'strictly less than', or 'the same as' the 'int' values in the queue 'q3' (with respect to the '<=' operator);"<<endl; else cout<<"\t\t-) are not both 'strictly less than', and 'the same as' the 'int' values in the queue 'q3' (with respect to the '<=' operator);"<<endl; if(q0>=(*q3)) cout<<"\t\t-) may be either 'strictly greater than', or 'the same as' the 'int' values in the queue 'q3' (with respect to the '>=' operator)."<<endl<<endl; else cout<<"\t\t-) are not both 'strictly greater than', and 'the same as' the 'int' values in the queue 'q3' (with respect to the '>=' operator)."<<endl<<endl; cout<<"\tSwapping the content of the queues 'q0' and 'q3' ... "; q3->swap(q0); cout<<"ok"<<endl; cout<<"\t#values in the queue 'q0' is "<<q0.size()<<"."<<endl; if(q0.empty()==true) cout<<"\tThe queue 'q0' is empty."<<endl; else cout<<"\tThe queue 'q0' is not empty."<<endl; cout<<"\t#values in the queue 'q3' is "<<q3->size()<<"."<<endl; if(q3->empty()==true) cout<<"\tThe queue 'q3' is empty."<<endl; else cout<<"\tThe queue 'q3' is not empty."<<endl; cout<<"\tThe 'int' values in the queue 'q0':"<<endl<<endl; if(q0==(*q3)) cout<<"\t\t-) are 'the same as' the 'int' values in the queue 'q3' (see the '==' operator);"<<endl; else cout<<"\t\t-) are not 'the same as' the 'int' values in the queue 'q3' (see the '==' operator);"<<endl; if(q0!=(*q3)) cout<<"\t\t-) are not 'the same as' the 'int' values in the queue 'q3' (see the '!=' operator);"<<endl; else cout<<"\t\t-) are 'the same as' the 'int' values in the queue 'q3' (see the '!=' operator);"<<endl; if(q0<(*q3)) cout<<"\t\t-) are 'strictly less than' the 'int' values in the queue 'q3' (see the '<' operator);"<<endl; else cout<<"\t\t-) are not 'strictly less than' the 'int' values in the queue 'q3' (see the '<' operator);"<<endl; if(q0>(*q3)) cout<<"\t\t-) are 'strictly greater than' the 'int' values in the queue 'q3' (see the '>' operator);"<<endl; else cout<<"\t\t-) are not 'strictly greater than' the 'int' values in the queue 'q3' (see the '>' operator);"<<endl; if(q0<=(*q3)) cout<<"\t\t-) may be either 'strictly less than', or 'the same as' the 'int' values in the queue 'q3' (with respect to the '<=' operator);"<<endl; else cout<<"\t\t-) are not both 'strictly less than', and 'the same as' the 'int' values in the queue 'q3' (with respect to the '<=' operator);"<<endl; if(q0>=(*q3)) cout<<"\t\t-) may be either 'strictly greater than', or 'the same as' the 'int' values in the queue 'q3' (with respect to the '>=' operator)."<<endl<<endl; else cout<<"\t\t-) are not both 'strictly greater than', and 'the same as' the 'int' values in the queue 'q3' (with respect to the '>=' operator)."<<endl<<endl; cout<<"\tRemoving and visiting iteratively all 'int' values in the queue 'q0' (as follows):"; while(!q0.empty()) { cout<<" "<<q0.front(); q0.pop(); } /* At the end, the queue 'q0' should be empty! */ cout<<"."<<endl<<"\t#values in the queue 'q0' is "<<q0.size()<<"."<<endl; if(q0.empty()==true) cout<<"\tThe queue 'q0' is empty."<<endl<<endl; else cout<<"\tThe queue 'q0' is not empty."<<endl<<endl; cout<<"\tPress the RETURN key to continue ... "; cin.get(); cout << endl; cout.flush(); /* TASK #7 - deallocating all queues */ cout<<"\tDeallocating all queues in this test ... "; while(!q0.empty()) q0.pop(); while(!q1.empty()) q1.pop(); while(!q2.empty()) q2.pop(); if(q3!=nullptr) { while(!q3->empty()) q3->pop(); delete q3; q3=nullptr; } /* All is ok. */ cout<<"ok"<<endl<<endl; cout << "\tPress the RETURN key to finish ... "; cin.get(); #ifndef _MSC_VER cout << endl; cout.flush(); #endif return EXIT_SUCCESS; }
[ "canino.david@gmail.com" ]
canino.david@gmail.com
ebcf4d81a75590937c4341c47829318a57e984d9
3dff775734ba488f4badaae1e0b68abb53a8b0c2
/adspc++2code/Xref.cpp
8930e25d8c14e1263d60e088f656b2c0e2067844
[]
no_license
barrygu/dsaa
22211497c127f28658f74c256d1fefe416257e19
432f5c764c0b8531f5063e1839445fbeb496dc73
refs/heads/master
2016-08-05T16:35:47.312632
2014-07-14T03:14:21
2014-07-14T03:14:21
21,804,296
0
1
null
null
null
null
UTF-8
C++
false
false
2,544
cpp
// Xref class interface: generate cross-reference. // // CONSTRUCTION: with an istream object. // // ******************PUBLIC OPERATIONS*********************** // void generateCrossReference( ) --> Name says it all ... // ******************ERRORS********************************** // Error checking on comments and quotes is performed. #include "Tokenizer.h" #ifdef USE_DOT_H #include <iostream.h> #include <fstream.h> #else #include <fstream> #include <iostream> #if !defined( __BORLANDC__ ) || __BORLANDC__ >= 0x0530 using namespace std; // Borland 5.0 has a bug #endif #endif #ifndef SAFE_STL #include <list> #include <string> #include <map> #include <functional> using namespace std; #else #include "list.h" #include "mystring.h" #include "map.h" #include "functional.h" #include "StartConv.h" #endif class Xref { public: Xref( istream & input ) : tok( input ) { } void generateCrossReference( ); private: Tokenizer tok; // Token source }; // Output the cross reference. void Xref::generateCrossReference( ) { typedef map<string,list<int>, less<string> > MapType; typedef MapType::const_iterator MapIteratorType; MapType xrefMap; string current; // Insert identifiers into the map. while( ( current = tok.getNextID( ) ) != "" ) xrefMap[ current ].push_back( tok.getLineNumber( ) ); // Iterate through map and output // identifiers and their line number. MapIteratorType itr; for( itr = xrefMap.begin( ); itr != xrefMap.end( ); ++itr ) { const list<int> & theLines = (*itr).second; list<int>::const_iterator lineItr = theLines.begin( ); // Print identifier and first line where it occurs. cout << (*itr).first << ": " << *lineItr; // Print all other lines on which it occurs. for( ++lineItr; lineItr != theLines.end( ); ++lineItr ) cout << ", " << *lineItr; cout << endl; } } int main( int argc, const char **argv ) { if( argc == 1 ) { Xref p( cin ); p.generateCrossReference( ); return 0; } while( --argc ) { ifstream ifp( *++argv ); if( !ifp ) { cout << "Cannot open " << *argv << endl; continue; } cout << "*********" << *argv << "*********\n"; Xref p( ifp ); p.generateCrossReference( ); } return 0; } #ifdef SAFE_STL #include "EndConv.h" #endif
[ "barry.gu@ftid.cn" ]
barry.gu@ftid.cn
882c3c30cadcd88780ea877bf0e4a77987096a92
dbcbd51e50314a081817171de2df8e71dc354e99
/AtCoder/PracticeProblems/計算/ABC153_B_CommonRaccoonVSMonster/prog.cpp
37a6ec9ab411c72cfee8ed3ad1f3c75e38e80354
[]
no_license
Shitakami/AtCoder_SolveProblems
cb3dfedad42486d32d036f896b7b09b1c92bbfa1
a273d001852273581e1749c2c63820946122c1e2
refs/heads/master
2021-01-03T05:19:13.944110
2020-07-05T16:42:09
2020-07-05T16:42:09
239,938,798
0
0
null
null
null
null
UTF-8
C++
false
false
322
cpp
#include <iostream> using namespace std; int main() { int h, n; cin >> h >> n; int sum = 0; for(int i = 0; i < n; ++i) { int p; cin >> p; sum += p; } if(sum >= h) cout << "Yes"; else { cout << "No"; } cout << endl; return 0; }
[ "vxd.naoshi.19961205.maro@gmail.com" ]
vxd.naoshi.19961205.maro@gmail.com
cfb98e47f037d71e143d8f6b46c2759b4aa3586b
be8f2d39d70cf86fe4a26d56aa2479cb083b871e
/bonjourresolver.h
b5339f406781f0b99c3e9b9b281b0321e3ca899b
[]
no_license
mm2mm2/nuvo-json-client
8016c3b9d12a8916c708af2a4079dd10e1f7848c
2e33812d6acd588c861674c2edf194c6907bb91a
refs/heads/master
2021-01-16T22:59:12.278280
2013-12-31T18:03:23
2013-12-31T18:03:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,121
h
#ifndef BONJOURRESOLVER_H #define BONJOURRESOLVER_H #include <QtCore/QObject> #include <dns_sd.h> class QSocketNotifier; class QHostInfo; class BonjourRecord; class BonjourResolver : public QObject { Q_OBJECT public: BonjourResolver(QObject *parent); ~BonjourResolver(); void resolveBonjourRecord(const BonjourRecord &record); signals: void bonjourRecordResolved(const QHostInfo &hostInfo, int port, BonjourResolver *resolver); void error(DNSServiceErrorType error); private slots: void bonjourSocketReadyRead(); void cleanupResolve(); void finishConnect(const QHostInfo &hostInfo); private: static void DNSSD_API bonjourResolveReply(DNSServiceRef sdRef, DNSServiceFlags flags, quint32 interfaceIndex, DNSServiceErrorType errorCode, const char *fullName, const char *hosttarget, quint16 port, quint16 txtLen, const char *txtRecord, void *context); DNSServiceRef dnssref; QSocketNotifier *bonjourSocket; int bonjourPort; }; #endif // BONJOURRESOLVER_H
[ "bradyt@nuvotechnologies.com" ]
bradyt@nuvotechnologies.com
9589b301f82d719bcd9576be0b9da2bfd964b53a
adfad536bb190561013448590ddadaf312094039
/plugins/MacAU/Air2/Air2.cpp
5434080e5029a1905d49f280423b7e755ad04e44
[ "MIT" ]
permissive
themucha/airwindows
ae7c1d5061f6e6b565c7be1b09cae21e5f601915
13bace268f2356e2a037e935c0845d91bfcb79a6
refs/heads/master
2022-02-21T08:46:53.021402
2022-01-30T18:30:35
2022-01-30T18:30:35
204,864,549
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
15,696
cpp
/* * File: Air2.cpp * * Version: 1.0 * * Created: 7/5/21 * * Copyright: Copyright © 2021 Airwindows, All Rights Reserved * * Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in * consideration of your agreement to the following terms, and your use, installation, modification * or redistribution of this Apple software constitutes acceptance of these terms. If you do * not agree with these terms, please do not use, install, modify or redistribute this Apple * software. * * In consideration of your agreement to abide by the following terms, and subject to these terms, * Apple grants you a personal, non-exclusive license, under Apple's copyrights in this * original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the * Apple Software, with or without modifications, in source and/or binary forms; provided that if you * redistribute the Apple Software in its entirety and without modifications, you must retain this * notice and the following text and disclaimers in all such redistributions of the Apple Software. * Neither the name, trademarks, service marks or logos of Apple Computer, Inc. may be used to * endorse or promote products derived from the Apple Software without specific prior written * permission from Apple. Except as expressly stated in this notice, no other rights or * licenses, express or implied, are granted by Apple herein, including but not limited to any * patent rights that may be infringed by your derivative works or by other works in which the * Apple Software may be incorporated. * * The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR * IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE * OR IN COMBINATION WITH YOUR PRODUCTS. * * IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, * REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER * UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN * IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /*============================================================================= Air2.cpp =============================================================================*/ #include "Air2.h" //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ COMPONENT_ENTRY(Air2) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Air2::Air2 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Air2::Air2(AudioUnit component) : AUEffectBase(component) { CreateElements(); Globals()->UseIndexedParameters(kNumberOfParameters); SetParameter(kParam_One, kDefaultValue_ParamOne ); SetParameter(kParam_Two, kDefaultValue_ParamTwo ); SetParameter(kParam_Three, kDefaultValue_ParamThree ); SetParameter(kParam_Four, kDefaultValue_ParamFour ); SetParameter(kParam_Five, kDefaultValue_ParamFive ); #if AU_DEBUG_DISPATCHER mDebugDispatcher = new AUDebugDispatcher (this); #endif } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Air2::GetParameterValueStrings //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ComponentResult Air2::GetParameterValueStrings(AudioUnitScope inScope, AudioUnitParameterID inParameterID, CFArrayRef * outStrings) { return kAudioUnitErr_InvalidProperty; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Air2::GetParameterInfo //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ComponentResult Air2::GetParameterInfo(AudioUnitScope inScope, AudioUnitParameterID inParameterID, AudioUnitParameterInfo &outParameterInfo ) { ComponentResult result = noErr; outParameterInfo.flags = kAudioUnitParameterFlag_IsWritable | kAudioUnitParameterFlag_IsReadable; if (inScope == kAudioUnitScope_Global) { switch(inParameterID) { case kParam_One: AUBase::FillInParameterName (outParameterInfo, kParameterOneName, false); outParameterInfo.unit = kAudioUnitParameterUnit_Generic; outParameterInfo.minValue = -1.0; outParameterInfo.maxValue = 1.0; outParameterInfo.defaultValue = kDefaultValue_ParamOne; break; case kParam_Two: AUBase::FillInParameterName (outParameterInfo, kParameterTwoName, false); outParameterInfo.unit = kAudioUnitParameterUnit_Generic; outParameterInfo.minValue = -1.0; outParameterInfo.maxValue = 1.0; outParameterInfo.defaultValue = kDefaultValue_ParamTwo; break; case kParam_Three: AUBase::FillInParameterName (outParameterInfo, kParameterThreeName, false); outParameterInfo.unit = kAudioUnitParameterUnit_Generic; outParameterInfo.minValue = -1.0; outParameterInfo.maxValue = 1.0; outParameterInfo.defaultValue = kDefaultValue_ParamThree; break; case kParam_Four: AUBase::FillInParameterName (outParameterInfo, kParameterFourName, false); outParameterInfo.unit = kAudioUnitParameterUnit_Generic; outParameterInfo.minValue = 0.0; outParameterInfo.maxValue = 1.0; outParameterInfo.defaultValue = kDefaultValue_ParamFour; break; case kParam_Five: AUBase::FillInParameterName (outParameterInfo, kParameterFiveName, false); outParameterInfo.unit = kAudioUnitParameterUnit_Generic; outParameterInfo.minValue = 0.0; outParameterInfo.maxValue = 1.0; outParameterInfo.defaultValue = kDefaultValue_ParamFive; break; default: result = kAudioUnitErr_InvalidParameter; break; } } else { result = kAudioUnitErr_InvalidParameter; } return result; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Air2::GetPropertyInfo //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ComponentResult Air2::GetPropertyInfo (AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, UInt32 & outDataSize, Boolean & outWritable) { return AUEffectBase::GetPropertyInfo (inID, inScope, inElement, outDataSize, outWritable); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Air2::GetProperty //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ComponentResult Air2::GetProperty( AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, void * outData ) { return AUEffectBase::GetProperty (inID, inScope, inElement, outData); } // Air2::Initialize //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ComponentResult Air2::Initialize() { ComponentResult result = AUEffectBase::Initialize(); if (result == noErr) Reset(kAudioUnitScope_Global, 0); return result; } #pragma mark ____Air2EffectKernel //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Air2::Air2Kernel::Reset() //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void Air2::Air2Kernel::Reset() { airPrevA = 0.0; airEvenA = 0.0; airOddA = 0.0; airFactorA = 0.0; flipA = false; airPrevB = 0.0; airEvenB = 0.0; airOddB = 0.0; airFactorB = 0.0; flipB = false; airPrevC = 0.0; airEvenC = 0.0; airOddC = 0.0; airFactorC = 0.0; flop = false; tripletPrev = 0.0; tripletMid = 0.0; tripletA = 0.0; tripletB = 0.0; tripletC = 0.0; tripletFactor = 0.0; count = 1; postsine = sin(1.0); for(int c = 0; c < 9; c++) {lastRef[c] = 0.0;} cycle = 0; fpd = 1.0; while (fpd < 16386) fpd = rand()*UINT32_MAX; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Air2::Air2Kernel::Process //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void Air2::Air2Kernel::Process( const Float32 *inSourceP, Float32 *inDestP, UInt32 inFramesToProcess, UInt32 inNumChannels, bool &ioSilence ) { UInt32 nSampleFrames = inFramesToProcess; const Float32 *sourceP = inSourceP; Float32 *destP = inDestP; long double overallscale = 1.0; overallscale /= 44100.0; overallscale *= GetSampleRate(); int cycleEnd = floor(overallscale); if (cycleEnd < 1) cycleEnd = 1; if (cycleEnd > 4) cycleEnd = 4; //this is going to be 2 for 88.1 or 96k, 3 for silly people, 4 for 176 or 192k if (cycle > cycleEnd-1) cycle = cycleEnd-1; //sanity check Float64 hiIntensity = GetParameter( kParam_One ); Float64 tripletIntensity = GetParameter( kParam_Two ); Float64 airIntensity = GetParameter( kParam_Three ); if (hiIntensity < 0.0) hiIntensity *= 0.57525; if (tripletIntensity < 0.0) tripletIntensity *= 0.71325; if (airIntensity < 0.0) airIntensity *= 0.5712; hiIntensity = -pow(hiIntensity,3); tripletIntensity = -pow(tripletIntensity,3); airIntensity = -pow(airIntensity,3); Float64 hiQ = 1.5+fabs(hiIntensity*0.5); Float64 tripletQ = 1.5+fabs(tripletIntensity*0.5); Float64 airQ = 1.5+fabs(airIntensity*0.5); Float64 intensity = (pow(GetParameter( kParam_Four ),3)*4.0) + 0.0001; Float64 mix = GetParameter( kParam_Five ); Float64 drymix = (1.0-mix)*4.0; if (drymix > 1.0) drymix = 1.0; //all types of air band are running in parallel, not series while (nSampleFrames-- > 0) { long double inputSample = *sourceP; if (fabs(inputSample)<1.18e-37) inputSample = fpd * 1.18e-37; double drySample = inputSample; cycle++; if (cycle == cycleEnd) { //hit the end point and we do an Air sample long double correction = 0.0; if (fabs(hiIntensity) > 0.0001) { airFactorC = airPrevC - inputSample; if (flop) { airEvenC += airFactorC; airOddC -= airFactorC; airFactorC = airEvenC * hiIntensity; } else { airOddC += airFactorC; airEvenC -= airFactorC; airFactorC = airOddC * hiIntensity; } airOddC = (airOddC - ((airOddC - airEvenC)/256.0)) / hiQ; airEvenC = (airEvenC - ((airEvenC - airOddC)/256.0)) / hiQ; airPrevC = inputSample; correction = correction + airFactorC; flop = !flop; }//22k if (fabs(tripletIntensity) > 0.0001) { tripletFactor = tripletPrev - inputSample; if (count < 1 || count > 3) count = 1; switch (count) { case 1: tripletA += tripletFactor; tripletC -= tripletFactor; tripletFactor = tripletA * tripletIntensity; tripletPrev = tripletMid; tripletMid = inputSample; break; case 2: tripletB += tripletFactor; tripletA -= tripletFactor; tripletFactor = tripletB * tripletIntensity; tripletPrev = tripletMid; tripletMid = inputSample; break; case 3: tripletC += tripletFactor; tripletB -= tripletFactor; tripletFactor = tripletC * tripletIntensity; tripletPrev = tripletMid; tripletMid = inputSample; break; } tripletA /= tripletQ; tripletB /= tripletQ; tripletC /= tripletQ; correction = correction + tripletFactor; count++; }//15K if (fabs(airIntensity) > 0.0001) { if (flop) { airFactorA = airPrevA - inputSample; if (flipA) { airEvenA += airFactorA; airOddA -= airFactorA; airFactorA = airEvenA * airIntensity; } else { airOddA += airFactorA; airEvenA -= airFactorA; airFactorA = airOddA * airIntensity; } airOddA = (airOddA - ((airOddA - airEvenA)/256.0)) / airQ; airEvenA = (airEvenA - ((airEvenA - airOddA)/256.0)) / airQ; airPrevA = inputSample; correction = correction + airFactorA; flipA = !flipA; } else { airFactorB = airPrevB - inputSample; if (flipB) { airEvenB += airFactorB; airOddB -= airFactorB; airFactorB = airEvenB * airIntensity; } else { airOddB += airFactorB; airEvenB -= airFactorB; airFactorB = airOddB * airIntensity; } airOddB = (airOddB - ((airOddB - airEvenB)/256.0)) / airQ; airEvenB = (airEvenB - ((airEvenB - airOddB)/256.0)) / airQ; airPrevB = inputSample; correction = correction + airFactorB; flipB = !flipB; } }//11k correction *= intensity; correction -= 1.0; long double bridgerectifier = fabs(correction); if (bridgerectifier > 1.57079633) bridgerectifier = 1.57079633; bridgerectifier = sin(bridgerectifier); if (correction > 0) correction = bridgerectifier; else correction = -bridgerectifier; correction += postsine; correction /= intensity; inputSample = correction * 4.0 * mix; if (cycleEnd == 4) { lastRef[0] = lastRef[4]; //start from previous last lastRef[2] = (lastRef[0] + inputSample)/2; //half lastRef[1] = (lastRef[0] + lastRef[2])/2; //one quarter lastRef[3] = (lastRef[2] + inputSample)/2; //three quarters lastRef[4] = inputSample; //full } if (cycleEnd == 3) { lastRef[0] = lastRef[3]; //start from previous last lastRef[2] = (lastRef[0]+lastRef[0]+inputSample)/3; //third lastRef[1] = (lastRef[0]+inputSample+inputSample)/3; //two thirds lastRef[3] = inputSample; //full } if (cycleEnd == 2) { lastRef[0] = lastRef[2]; //start from previous last lastRef[1] = (lastRef[0] + inputSample)/2; //half lastRef[2] = inputSample; //full } if (cycleEnd == 1) lastRef[0] = inputSample; cycle = 0; //reset inputSample = lastRef[cycle]; } else { inputSample = lastRef[cycle]; //we are going through our references now } switch (cycleEnd) //multi-pole average using lastRef[] variables { case 4: lastRef[8] = inputSample; inputSample = (inputSample+lastRef[7])*0.5; lastRef[7] = lastRef[8]; //continue, do not break case 3: lastRef[8] = inputSample; inputSample = (inputSample+lastRef[6])*0.5; lastRef[6] = lastRef[8]; //continue, do not break case 2: lastRef[8] = inputSample; inputSample = (inputSample+lastRef[5])*0.5; lastRef[5] = lastRef[8]; //continue, do not break case 1: break; //no further averaging } if (drymix < 1.0) drySample *= drymix; inputSample += drySample; //begin 32 bit floating point dither int expon; frexpf((float)inputSample, &expon); fpd ^= fpd << 13; fpd ^= fpd >> 17; fpd ^= fpd << 5; inputSample += ((double(fpd)-uint32_t(0x7fffffff)) * 5.5e-36l * pow(2,expon+62)); //end 32 bit floating point dither *destP = inputSample; sourceP += inNumChannels; destP += inNumChannels; } }
[ "jinx6568@sover.net" ]
jinx6568@sover.net
b6d59db5a71627a897b21d25078e0400931a6f0a
89dedd7f3c7acc81d12e2bcb2e716f9af9e5fa04
/cc/tiles/tile_manager.cc
ed30f468df20d007e762e907d9af49c54afd01d3
[ "BSD-3-Clause" ]
permissive
bino7/chromium
8d26f84a1b6e38a73d1b97fea6057c634eff68cb
4666a6bb6fdcb1114afecf77bdaa239d9787b752
refs/heads/master
2022-12-22T14:31:53.913081
2016-09-06T10:05:11
2016-09-06T10:05:11
67,410,510
1
3
BSD-3-Clause
2022-12-17T03:08:52
2016-09-05T10:11:59
null
UTF-8
C++
false
false
50,812
cc
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/tiles/tile_manager.h" #include <stddef.h> #include <stdint.h> #include <algorithm> #include <limits> #include <string> #include "base/bind.h" #include "base/json/json_writer.h" #include "base/logging.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram.h" #include "base/numerics/safe_conversions.h" #include "base/threading/thread_checker.h" #include "base/trace_event/trace_event_argument.h" #include "cc/base/histograms.h" #include "cc/debug/devtools_instrumentation.h" #include "cc/debug/frame_viewer_instrumentation.h" #include "cc/debug/traced_value.h" #include "cc/layers/picture_layer_impl.h" #include "cc/raster/raster_buffer.h" #include "cc/raster/task_category.h" #include "cc/tiles/tile.h" #include "ui/gfx/geometry/rect_conversions.h" namespace cc { namespace { // Flag to indicate whether we should try and detect that // a tile is of solid color. const bool kUseColorEstimator = true; DEFINE_SCOPED_UMA_HISTOGRAM_AREA_TIMER( ScopedRasterTaskTimer, "Compositing.%s.RasterTask.RasterUs", "Compositing.%s.RasterTask.RasterPixelsPerMs"); class RasterTaskImpl : public TileTask { public: RasterTaskImpl(TileManager* tile_manager, Tile* tile, Resource* resource, scoped_refptr<RasterSource> raster_source, const RasterSource::PlaybackSettings& playback_settings, TileResolution tile_resolution, gfx::Rect invalidated_rect, uint64_t source_prepare_tiles_id, std::unique_ptr<RasterBuffer> raster_buffer, TileTask::Vector* dependencies, bool supports_concurrent_execution) : TileTask(supports_concurrent_execution, dependencies), tile_manager_(tile_manager), tile_(tile), resource_(resource), raster_source_(std::move(raster_source)), content_rect_(tile->content_rect()), invalid_content_rect_(invalidated_rect), contents_scale_(tile->contents_scale()), playback_settings_(playback_settings), tile_resolution_(tile_resolution), layer_id_(tile->layer_id()), source_prepare_tiles_id_(source_prepare_tiles_id), tile_tracing_id_(static_cast<void*>(tile)), new_content_id_(tile->id()), source_frame_number_(tile->source_frame_number()), raster_buffer_(std::move(raster_buffer)) { DCHECK(origin_thread_checker_.CalledOnValidThread()); } // Overridden from Task: void RunOnWorkerThread() override { TRACE_EVENT1("cc", "RasterizerTaskImpl::RunOnWorkerThread", "source_prepare_tiles_id", source_prepare_tiles_id_); DCHECK(raster_source_.get()); DCHECK(raster_buffer_); frame_viewer_instrumentation::ScopedRasterTask raster_task( tile_tracing_id_, tile_resolution_, source_frame_number_, layer_id_); ScopedRasterTaskTimer timer; timer.SetArea(content_rect_.size().GetArea()); DCHECK(raster_source_); raster_buffer_->Playback(raster_source_.get(), content_rect_, invalid_content_rect_, new_content_id_, contents_scale_, playback_settings_); } // Overridden from TileTask: void OnTaskCompleted() override { DCHECK(origin_thread_checker_.CalledOnValidThread()); // Here calling state().IsCanceled() is thread-safe, because this task is // already concluded as FINISHED or CANCELLED and no longer will be worked // upon by task graph runner. tile_manager_->OnRasterTaskCompleted(std::move(raster_buffer_), tile_, resource_, state().IsCanceled()); } protected: ~RasterTaskImpl() override { DCHECK(origin_thread_checker_.CalledOnValidThread()); DCHECK(!raster_buffer_); } private: base::ThreadChecker origin_thread_checker_; // The following members are needed for processing completion of this task on // origin thread. These are not thread-safe and should be accessed only in // origin thread. Ensure their access by checking CalledOnValidThread(). TileManager* tile_manager_; Tile* tile_; Resource* resource_; // The following members should be used for running the task. scoped_refptr<RasterSource> raster_source_; gfx::Rect content_rect_; gfx::Rect invalid_content_rect_; float contents_scale_; RasterSource::PlaybackSettings playback_settings_; TileResolution tile_resolution_; int layer_id_; uint64_t source_prepare_tiles_id_; void* tile_tracing_id_; uint64_t new_content_id_; int source_frame_number_; std::unique_ptr<RasterBuffer> raster_buffer_; DISALLOW_COPY_AND_ASSIGN(RasterTaskImpl); }; TaskCategory TaskCategoryForTileTask(TileTask* task, bool use_foreground_category) { if (!task->supports_concurrent_execution()) return TASK_CATEGORY_NONCONCURRENT_FOREGROUND; if (use_foreground_category) return TASK_CATEGORY_FOREGROUND; return TASK_CATEGORY_BACKGROUND; } bool IsForegroundCategory(uint16_t category) { TaskCategory enum_category = static_cast<TaskCategory>(category); switch (enum_category) { case TASK_CATEGORY_NONCONCURRENT_FOREGROUND: case TASK_CATEGORY_FOREGROUND: return true; case TASK_CATEGORY_BACKGROUND: return false; } DCHECK(false); return false; } // Task priorities that make sure that the task set done tasks run before any // other remaining tasks. const size_t kRequiredForActivationDoneTaskPriority = 1u; const size_t kRequiredForDrawDoneTaskPriority = 2u; const size_t kAllDoneTaskPriority = 3u; // For correctness, |kTileTaskPriorityBase| must be greater than // all task set done task priorities. size_t kTileTaskPriorityBase = 10u; void InsertNodeForTask(TaskGraph* graph, TileTask* task, uint16_t category, uint16_t priority, size_t dependencies) { DCHECK(std::find_if(graph->nodes.begin(), graph->nodes.end(), [task](const TaskGraph::Node& node) { return node.task == task; }) == graph->nodes.end()); graph->nodes.push_back( TaskGraph::Node(task, category, priority, dependencies)); } void InsertNodeForDecodeTask(TaskGraph* graph, TileTask* task, bool use_foreground_category, uint16_t priority) { uint32_t dependency_count = 0u; if (task->dependencies().size()) { DCHECK_EQ(task->dependencies().size(), 1u); auto* dependency = task->dependencies()[0].get(); if (!dependency->HasCompleted()) { InsertNodeForDecodeTask(graph, dependency, use_foreground_category, priority); graph->edges.push_back(TaskGraph::Edge(dependency, task)); dependency_count = 1u; } } InsertNodeForTask(graph, task, TaskCategoryForTileTask(task, use_foreground_category), priority, dependency_count); } void InsertNodesForRasterTask(TaskGraph* graph, TileTask* raster_task, const TileTask::Vector& decode_tasks, size_t priority, bool use_foreground_category) { size_t dependencies = 0u; // Insert image decode tasks. for (TileTask::Vector::const_iterator it = decode_tasks.begin(); it != decode_tasks.end(); ++it) { TileTask* decode_task = it->get(); // Skip if already decoded. if (decode_task->HasCompleted()) continue; dependencies++; // Add decode task if it doesn't already exist in graph. TaskGraph::Node::Vector::iterator decode_it = std::find_if(graph->nodes.begin(), graph->nodes.end(), [decode_task](const TaskGraph::Node& node) { return node.task == decode_task; }); // In rare circumstances, a background category task may come in before a // foreground category task. In these cases, upgrade any background category // dependencies of the current task. // TODO(ericrk): Task iterators should be updated to avoid this. // crbug.com/594851 // TODO(ericrk): This should handle dependencies recursively. // crbug.com/605234 if (decode_it != graph->nodes.end() && use_foreground_category && !IsForegroundCategory(decode_it->category)) { decode_it->category = TASK_CATEGORY_FOREGROUND; } if (decode_it == graph->nodes.end()) { InsertNodeForDecodeTask(graph, decode_task, use_foreground_category, priority); } graph->edges.push_back(TaskGraph::Edge(decode_task, raster_task)); } InsertNodeForTask( graph, raster_task, TaskCategoryForTileTask(raster_task, use_foreground_category), priority, dependencies); } class TaskSetFinishedTaskImpl : public TileTask { public: explicit TaskSetFinishedTaskImpl( base::SequencedTaskRunner* task_runner, const base::Closure& on_task_set_finished_callback) : TileTask(true), task_runner_(task_runner), on_task_set_finished_callback_(on_task_set_finished_callback) {} // Overridden from Task: void RunOnWorkerThread() override { TRACE_EVENT0("cc", "TaskSetFinishedTaskImpl::RunOnWorkerThread"); TaskSetFinished(); } // Overridden from TileTask: void OnTaskCompleted() override {} protected: ~TaskSetFinishedTaskImpl() override {} void TaskSetFinished() { task_runner_->PostTask(FROM_HERE, on_task_set_finished_callback_); } private: base::SequencedTaskRunner* task_runner_; const base::Closure on_task_set_finished_callback_; DISALLOW_COPY_AND_ASSIGN(TaskSetFinishedTaskImpl); }; } // namespace RasterTaskCompletionStats::RasterTaskCompletionStats() : completed_count(0u), canceled_count(0u) {} std::unique_ptr<base::trace_event::ConvertableToTraceFormat> RasterTaskCompletionStatsAsValue(const RasterTaskCompletionStats& stats) { std::unique_ptr<base::trace_event::TracedValue> state( new base::trace_event::TracedValue()); state->SetInteger("completed_count", base::saturated_cast<int>(stats.completed_count)); state->SetInteger("canceled_count", base::saturated_cast<int>(stats.canceled_count)); return std::move(state); } TileManager::TileManager(TileManagerClient* client, base::SequencedTaskRunner* task_runner, size_t scheduled_raster_task_limit, bool use_partial_raster, int max_preraster_distance_in_screen_pixels) : client_(client), task_runner_(task_runner), resource_pool_(nullptr), tile_task_manager_(nullptr), scheduled_raster_task_limit_(scheduled_raster_task_limit), use_partial_raster_(use_partial_raster), use_gpu_rasterization_(false), all_tiles_that_need_to_be_rasterized_are_scheduled_(true), did_check_for_completed_tasks_since_last_schedule_tasks_(true), did_oom_on_last_assign_(false), more_tiles_need_prepare_check_notifier_( task_runner_, base::Bind(&TileManager::CheckIfMoreTilesNeedToBePrepared, base::Unretained(this))), signals_check_notifier_(task_runner_, base::Bind(&TileManager::CheckAndIssueSignals, base::Unretained(this))), has_scheduled_tile_tasks_(false), prepare_tiles_count_(0u), next_tile_id_(0u), max_preraster_distance_in_screen_pixels_( max_preraster_distance_in_screen_pixels), task_set_finished_weak_ptr_factory_(this) {} TileManager::~TileManager() { FinishTasksAndCleanUp(); } void TileManager::FinishTasksAndCleanUp() { if (!tile_task_manager_) return; global_state_ = GlobalStateThatImpactsTilePriority(); // This cancels tasks if possible, finishes pending tasks, and release any // uninitialized resources. tile_task_manager_->Shutdown(); raster_buffer_provider_->Shutdown(); // Now that all tasks have been finished, we can clear any |orphan_tasks_|. orphan_tasks_.clear(); tile_task_manager_->CheckForCompletedTasks(); FreeResourcesForReleasedTiles(); CleanUpReleasedTiles(); tile_task_manager_ = nullptr; resource_pool_ = nullptr; more_tiles_need_prepare_check_notifier_.Cancel(); signals_check_notifier_.Cancel(); task_set_finished_weak_ptr_factory_.InvalidateWeakPtrs(); for (auto& draw_image_pair : locked_images_) image_decode_controller_->UnrefImage(draw_image_pair.first); locked_images_.clear(); } void TileManager::SetResources(ResourcePool* resource_pool, ImageDecodeController* image_decode_controller, TileTaskManager* tile_task_manager, RasterBufferProvider* raster_buffer_provider, size_t scheduled_raster_task_limit, bool use_gpu_rasterization) { DCHECK(!tile_task_manager_); DCHECK(tile_task_manager); use_gpu_rasterization_ = use_gpu_rasterization; scheduled_raster_task_limit_ = scheduled_raster_task_limit; resource_pool_ = resource_pool; image_decode_controller_ = image_decode_controller; tile_task_manager_ = tile_task_manager; raster_buffer_provider_ = raster_buffer_provider; } void TileManager::Release(Tile* tile) { released_tiles_.push_back(tile); } void TileManager::FreeResourcesForReleasedTiles() { for (auto* tile : released_tiles_) FreeResourcesForTile(tile); } void TileManager::CleanUpReleasedTiles() { std::vector<Tile*> tiles_to_retain; for (auto* tile : released_tiles_) { if (tile->HasRasterTask()) { tiles_to_retain.push_back(tile); continue; } DCHECK(!tile->draw_info().has_resource()); DCHECK(tiles_.find(tile->id()) != tiles_.end()); tiles_.erase(tile->id()); delete tile; } released_tiles_.swap(tiles_to_retain); } void TileManager::DidFinishRunningTileTasksRequiredForActivation() { TRACE_EVENT0("cc", "TileManager::DidFinishRunningTileTasksRequiredForActivation"); TRACE_EVENT_ASYNC_STEP_INTO1("cc", "ScheduledTasks", this, "running", "state", ScheduledTasksStateAsValue()); signals_.ready_to_activate = true; signals_check_notifier_.Schedule(); } void TileManager::DidFinishRunningTileTasksRequiredForDraw() { TRACE_EVENT0("cc", "TileManager::DidFinishRunningTileTasksRequiredForDraw"); TRACE_EVENT_ASYNC_STEP_INTO1("cc", "ScheduledTasks", this, "running", "state", ScheduledTasksStateAsValue()); signals_.ready_to_draw = true; signals_check_notifier_.Schedule(); } void TileManager::DidFinishRunningAllTileTasks() { TRACE_EVENT0("cc", "TileManager::DidFinishRunningAllTileTasks"); TRACE_EVENT_ASYNC_END0("cc", "ScheduledTasks", this); DCHECK(resource_pool_); DCHECK(tile_task_manager_); has_scheduled_tile_tasks_ = false; bool memory_usage_above_limit = resource_pool_->memory_usage_bytes() > global_state_.soft_memory_limit_in_bytes; if (all_tiles_that_need_to_be_rasterized_are_scheduled_ && !memory_usage_above_limit) { // TODO(ericrk): We should find a better way to safely handle re-entrant // notifications than always having to schedule a new task. // http://crbug.com/498439 signals_.all_tile_tasks_completed = true; signals_check_notifier_.Schedule(); return; } more_tiles_need_prepare_check_notifier_.Schedule(); } bool TileManager::PrepareTiles( const GlobalStateThatImpactsTilePriority& state) { ++prepare_tiles_count_; TRACE_EVENT1("cc", "TileManager::PrepareTiles", "prepare_tiles_id", prepare_tiles_count_); if (!tile_task_manager_) { TRACE_EVENT_INSTANT0("cc", "PrepareTiles aborted", TRACE_EVENT_SCOPE_THREAD); return false; } signals_.reset(); global_state_ = state; // We need to call CheckForCompletedTasks() once in-between each call // to ScheduleTasks() to prevent canceled tasks from being scheduled. if (!did_check_for_completed_tasks_since_last_schedule_tasks_) { tile_task_manager_->CheckForCompletedTasks(); did_check_for_completed_tasks_since_last_schedule_tasks_ = true; } FreeResourcesForReleasedTiles(); CleanUpReleasedTiles(); PrioritizedWorkToSchedule prioritized_work = AssignGpuMemoryToTiles(); // Inform the client that will likely require a draw if the highest priority // tile that will be rasterized is required for draw. client_->SetIsLikelyToRequireADraw( !prioritized_work.tiles_to_raster.empty() && prioritized_work.tiles_to_raster.front().tile()->required_for_draw()); // Schedule tile tasks. ScheduleTasks(prioritized_work); TRACE_EVENT_INSTANT1("cc", "DidPrepareTiles", TRACE_EVENT_SCOPE_THREAD, "state", BasicStateAsValue()); return true; } void TileManager::Flush() { TRACE_EVENT0("cc", "TileManager::Flush"); if (!tile_task_manager_) { TRACE_EVENT_INSTANT0("cc", "Flush aborted", TRACE_EVENT_SCOPE_THREAD); return; } tile_task_manager_->CheckForCompletedTasks(); did_check_for_completed_tasks_since_last_schedule_tasks_ = true; TRACE_EVENT_INSTANT1("cc", "DidFlush", TRACE_EVENT_SCOPE_THREAD, "stats", RasterTaskCompletionStatsAsValue(flush_stats_)); flush_stats_ = RasterTaskCompletionStats(); } std::unique_ptr<base::trace_event::ConvertableToTraceFormat> TileManager::BasicStateAsValue() const { std::unique_ptr<base::trace_event::TracedValue> value( new base::trace_event::TracedValue()); BasicStateAsValueInto(value.get()); return std::move(value); } void TileManager::BasicStateAsValueInto( base::trace_event::TracedValue* state) const { state->SetInteger("tile_count", base::saturated_cast<int>(tiles_.size())); state->SetBoolean("did_oom_on_last_assign", did_oom_on_last_assign_); state->BeginDictionary("global_state"); global_state_.AsValueInto(state); state->EndDictionary(); } std::unique_ptr<EvictionTilePriorityQueue> TileManager::FreeTileResourcesUntilUsageIsWithinLimit( std::unique_ptr<EvictionTilePriorityQueue> eviction_priority_queue, const MemoryUsage& limit, MemoryUsage* usage) { while (usage->Exceeds(limit)) { if (!eviction_priority_queue) { eviction_priority_queue = client_->BuildEvictionQueue(global_state_.tree_priority); } if (eviction_priority_queue->IsEmpty()) break; Tile* tile = eviction_priority_queue->Top().tile(); *usage -= MemoryUsage::FromTile(tile); FreeResourcesForTileAndNotifyClientIfTileWasReadyToDraw(tile); eviction_priority_queue->Pop(); } return eviction_priority_queue; } std::unique_ptr<EvictionTilePriorityQueue> TileManager::FreeTileResourcesWithLowerPriorityUntilUsageIsWithinLimit( std::unique_ptr<EvictionTilePriorityQueue> eviction_priority_queue, const MemoryUsage& limit, const TilePriority& other_priority, MemoryUsage* usage) { while (usage->Exceeds(limit)) { if (!eviction_priority_queue) { eviction_priority_queue = client_->BuildEvictionQueue(global_state_.tree_priority); } if (eviction_priority_queue->IsEmpty()) break; const PrioritizedTile& prioritized_tile = eviction_priority_queue->Top(); if (!other_priority.IsHigherPriorityThan(prioritized_tile.priority())) break; Tile* tile = prioritized_tile.tile(); *usage -= MemoryUsage::FromTile(tile); FreeResourcesForTileAndNotifyClientIfTileWasReadyToDraw(tile); eviction_priority_queue->Pop(); } return eviction_priority_queue; } bool TileManager::TilePriorityViolatesMemoryPolicy( const TilePriority& priority) { switch (global_state_.memory_limit_policy) { case ALLOW_NOTHING: return true; case ALLOW_ABSOLUTE_MINIMUM: return priority.priority_bin > TilePriority::NOW; case ALLOW_PREPAINT_ONLY: return priority.priority_bin > TilePriority::SOON; case ALLOW_ANYTHING: return priority.distance_to_visible == std::numeric_limits<float>::infinity(); } NOTREACHED(); return true; } TileManager::PrioritizedWorkToSchedule TileManager::AssignGpuMemoryToTiles() { TRACE_EVENT_BEGIN0("cc", "TileManager::AssignGpuMemoryToTiles"); DCHECK(resource_pool_); DCHECK(tile_task_manager_); // Maintain the list of released resources that can potentially be re-used // or deleted. If this operation becomes expensive too, only do this after // some resource(s) was returned. Note that in that case, one also need to // invalidate when releasing some resource from the pool. resource_pool_->CheckBusyResources(); // Now give memory out to the tiles until we're out, and build // the needs-to-be-rasterized queue. unsigned schedule_priority = 1u; all_tiles_that_need_to_be_rasterized_are_scheduled_ = true; bool had_enough_memory_to_schedule_tiles_needed_now = true; MemoryUsage hard_memory_limit(global_state_.hard_memory_limit_in_bytes, global_state_.num_resources_limit); MemoryUsage soft_memory_limit(global_state_.soft_memory_limit_in_bytes, global_state_.num_resources_limit); MemoryUsage memory_usage(resource_pool_->memory_usage_bytes(), resource_pool_->resource_count()); std::unique_ptr<RasterTilePriorityQueue> raster_priority_queue( client_->BuildRasterQueue(global_state_.tree_priority, RasterTilePriorityQueue::Type::ALL)); std::unique_ptr<EvictionTilePriorityQueue> eviction_priority_queue; PrioritizedWorkToSchedule work_to_schedule; for (; !raster_priority_queue->IsEmpty(); raster_priority_queue->Pop()) { const PrioritizedTile& prioritized_tile = raster_priority_queue->Top(); Tile* tile = prioritized_tile.tile(); TilePriority priority = prioritized_tile.priority(); if (TilePriorityViolatesMemoryPolicy(priority)) { TRACE_EVENT_INSTANT0( "cc", "TileManager::AssignGpuMemory tile violates memory policy", TRACE_EVENT_SCOPE_THREAD); break; } bool tile_is_needed_now = priority.priority_bin == TilePriority::NOW; if (tile->use_picture_analysis() && kUseColorEstimator) { // We analyze for solid color here, to decide to continue // or drop the tile for scheduling and raster. // TODO(sohanjg): Check if we could use a shared analysis // canvas which is reset between tiles. SkColor color = SK_ColorTRANSPARENT; bool is_solid_color = prioritized_tile.raster_source()->PerformSolidColorAnalysis( tile->content_rect(), tile->contents_scale(), &color); if (is_solid_color) { tile->draw_info().set_solid_color(color); tile->draw_info().set_was_ever_ready_to_draw(); if (!tile_is_needed_now) tile->draw_info().set_was_a_prepaint_tile(); client_->NotifyTileStateChanged(tile); continue; } } // Prepaint tiles that are far away are only processed for images. if (!tile->required_for_activation() && !tile->required_for_draw() && priority.distance_to_visible > max_preraster_distance_in_screen_pixels_) { work_to_schedule.tiles_to_process_for_images.push_back(prioritized_tile); continue; } // We won't be able to schedule this tile, so break out early. if (work_to_schedule.tiles_to_raster.size() >= scheduled_raster_task_limit_) { all_tiles_that_need_to_be_rasterized_are_scheduled_ = false; break; } tile->scheduled_priority_ = schedule_priority++; DCHECK(tile->draw_info().mode() == TileDrawInfo::OOM_MODE || !tile->draw_info().IsReadyToDraw()); // If the tile already has a raster_task, then the memory used by it is // already accounted for in memory_usage. Otherwise, we'll have to acquire // more memory to create a raster task. MemoryUsage memory_required_by_tile_to_be_scheduled; if (!tile->raster_task_.get()) { memory_required_by_tile_to_be_scheduled = MemoryUsage::FromConfig( tile->desired_texture_size(), DetermineResourceFormat(tile)); } // This is the memory limit that will be used by this tile. Depending on // the tile priority, it will be one of hard_memory_limit or // soft_memory_limit. MemoryUsage& tile_memory_limit = tile_is_needed_now ? hard_memory_limit : soft_memory_limit; const MemoryUsage& scheduled_tile_memory_limit = tile_memory_limit - memory_required_by_tile_to_be_scheduled; eviction_priority_queue = FreeTileResourcesWithLowerPriorityUntilUsageIsWithinLimit( std::move(eviction_priority_queue), scheduled_tile_memory_limit, priority, &memory_usage); bool memory_usage_is_within_limit = !memory_usage.Exceeds(scheduled_tile_memory_limit); // If we couldn't fit the tile into our current memory limit, then we're // done. if (!memory_usage_is_within_limit) { if (tile_is_needed_now) had_enough_memory_to_schedule_tiles_needed_now = false; all_tiles_that_need_to_be_rasterized_are_scheduled_ = false; break; } memory_usage += memory_required_by_tile_to_be_scheduled; work_to_schedule.tiles_to_raster.push_back(prioritized_tile); // Since we scheduled the tile, set whether it was a prepaint or not // assuming that the tile will successfully finish running. We don't have // priority information at the time the tile completes, so it should be done // here. if (!tile_is_needed_now) tile->draw_info().set_was_a_prepaint_tile(); } // Note that we should try and further reduce memory in case the above loop // didn't reduce memory. This ensures that we always release as many resources // as possible to stay within the memory limit. eviction_priority_queue = FreeTileResourcesUntilUsageIsWithinLimit( std::move(eviction_priority_queue), hard_memory_limit, &memory_usage); UMA_HISTOGRAM_BOOLEAN("TileManager.ExceededMemoryBudget", !had_enough_memory_to_schedule_tiles_needed_now); did_oom_on_last_assign_ = !had_enough_memory_to_schedule_tiles_needed_now; memory_stats_from_last_assign_.total_budget_in_bytes = global_state_.hard_memory_limit_in_bytes; memory_stats_from_last_assign_.total_bytes_used = memory_usage.memory_bytes(); DCHECK_GE(memory_stats_from_last_assign_.total_bytes_used, 0); memory_stats_from_last_assign_.had_enough_memory = had_enough_memory_to_schedule_tiles_needed_now; TRACE_EVENT_END2("cc", "TileManager::AssignGpuMemoryToTiles", "all_tiles_that_need_to_be_rasterized_are_scheduled", all_tiles_that_need_to_be_rasterized_are_scheduled_, "had_enough_memory_to_schedule_tiles_needed_now", had_enough_memory_to_schedule_tiles_needed_now); return work_to_schedule; } void TileManager::FreeResourcesForTile(Tile* tile) { TileDrawInfo& draw_info = tile->draw_info(); if (draw_info.resource_) { resource_pool_->ReleaseResource(draw_info.resource_); draw_info.resource_ = nullptr; } } void TileManager::FreeResourcesForTileAndNotifyClientIfTileWasReadyToDraw( Tile* tile) { bool was_ready_to_draw = tile->draw_info().IsReadyToDraw(); FreeResourcesForTile(tile); if (was_ready_to_draw) client_->NotifyTileStateChanged(tile); } void TileManager::ScheduleTasks( const PrioritizedWorkToSchedule& work_to_schedule) { const std::vector<PrioritizedTile>& tiles_that_need_to_be_rasterized = work_to_schedule.tiles_to_raster; TRACE_EVENT1("cc", "TileManager::ScheduleTasks", "count", tiles_that_need_to_be_rasterized.size()); DCHECK(did_check_for_completed_tasks_since_last_schedule_tasks_); if (!has_scheduled_tile_tasks_) { TRACE_EVENT_ASYNC_BEGIN0("cc", "ScheduledTasks", this); } // Cancel existing OnTaskSetFinished callbacks. task_set_finished_weak_ptr_factory_.InvalidateWeakPtrs(); // Even when scheduling an empty set of tiles, the TTWP does some work, and // will always trigger a DidFinishRunningTileTasks notification. Because of // this we unconditionally set |has_scheduled_tile_tasks_| to true. has_scheduled_tile_tasks_ = true; // Track the number of dependents for each *_done task. size_t required_for_activate_count = 0; size_t required_for_draw_count = 0; size_t all_count = 0; size_t priority = kTileTaskPriorityBase; graph_.Reset(); scoped_refptr<TileTask> required_for_activation_done_task = CreateTaskSetFinishedTask( &TileManager::DidFinishRunningTileTasksRequiredForActivation); scoped_refptr<TileTask> required_for_draw_done_task = CreateTaskSetFinishedTask( &TileManager::DidFinishRunningTileTasksRequiredForDraw); scoped_refptr<TileTask> all_done_task = CreateTaskSetFinishedTask(&TileManager::DidFinishRunningAllTileTasks); // Build a new task queue containing all task currently needed. Tasks // are added in order of priority, highest priority task first. for (auto& prioritized_tile : tiles_that_need_to_be_rasterized) { Tile* tile = prioritized_tile.tile(); DCHECK(tile->draw_info().requires_resource()); DCHECK(!tile->draw_info().resource_); if (!tile->raster_task_) tile->raster_task_ = CreateRasterTask(prioritized_tile); TileTask* task = tile->raster_task_.get(); DCHECK(!task->HasCompleted()); if (tile->required_for_activation()) { required_for_activate_count++; graph_.edges.push_back( TaskGraph::Edge(task, required_for_activation_done_task.get())); } if (tile->required_for_draw()) { required_for_draw_count++; graph_.edges.push_back( TaskGraph::Edge(task, required_for_draw_done_task.get())); } all_count++; graph_.edges.push_back(TaskGraph::Edge(task, all_done_task.get())); // A tile should use a foreground task cateogry if it is either blocking // future compositing (required for draw or required for activation), or if // it has a priority bin of NOW for another reason (low resolution tiles). bool use_foreground_category = tile->required_for_draw() || tile->required_for_activation() || prioritized_tile.priority().priority_bin == TilePriority::NOW; InsertNodesForRasterTask(&graph_, task, task->dependencies(), priority++, use_foreground_category); } const std::vector<PrioritizedTile>& tiles_to_process_for_images = work_to_schedule.tiles_to_process_for_images; std::vector<std::pair<DrawImage, scoped_refptr<TileTask>>> new_locked_images; for (const PrioritizedTile& prioritized_tile : tiles_to_process_for_images) { Tile* tile = prioritized_tile.tile(); std::vector<DrawImage> images; prioritized_tile.raster_source()->GetDiscardableImagesInRect( tile->enclosing_layer_rect(), tile->contents_scale(), &images); ImageDecodeController::TracingInfo tracing_info( prepare_tiles_count_, prioritized_tile.priority().priority_bin); for (DrawImage& draw_image : images) { scoped_refptr<TileTask> task; bool need_to_unref_when_finished = image_decode_controller_->GetTaskForImageAndRef(draw_image, tracing_info, &task); // We only care about images that need to be locked (ie they need to be // unreffed later). if (!need_to_unref_when_finished) continue; new_locked_images.emplace_back(draw_image, task); // If there's no actual task associated with this image, then we're done. if (!task) continue; auto decode_it = std::find_if(graph_.nodes.begin(), graph_.nodes.end(), [&task](const TaskGraph::Node& node) { return node.task == task.get(); }); // If this task is already in the graph, then we don't have to insert it. if (decode_it != graph_.nodes.end()) continue; InsertNodeForDecodeTask(&graph_, task.get(), false, priority++); all_count++; graph_.edges.push_back(TaskGraph::Edge(task.get(), all_done_task.get())); } } for (auto& draw_image_pair : locked_images_) image_decode_controller_->UnrefImage(draw_image_pair.first); // The old locked images have to stay around until past the ScheduleTasks call // below, so we do a swap instead of a move. locked_images_.swap(new_locked_images); // We must reduce the amount of unused resources before calling // ScheduleTasks to prevent usage from rising above limits. resource_pool_->ReduceResourceUsage(); image_decode_controller_->ReduceCacheUsage(); // Insert nodes for our task completion tasks. We enqueue these using // NONCONCURRENT_FOREGROUND category this is the highest prioirty category and // we'd like to run these tasks as soon as possible. InsertNodeForTask(&graph_, required_for_activation_done_task.get(), TASK_CATEGORY_NONCONCURRENT_FOREGROUND, kRequiredForActivationDoneTaskPriority, required_for_activate_count); InsertNodeForTask(&graph_, required_for_draw_done_task.get(), TASK_CATEGORY_NONCONCURRENT_FOREGROUND, kRequiredForDrawDoneTaskPriority, required_for_draw_count); InsertNodeForTask(&graph_, all_done_task.get(), TASK_CATEGORY_NONCONCURRENT_FOREGROUND, kAllDoneTaskPriority, all_count); // Synchronize worker with compositor. raster_buffer_provider_->OrderingBarrier(); // Schedule running of |raster_queue_|. This replaces any previously // scheduled tasks and effectively cancels all tasks not present // in |raster_queue_|. tile_task_manager_->ScheduleTasks(&graph_); // It's now safe to clean up orphan tasks as raster worker pool is not // allowed to keep around unreferenced raster tasks after ScheduleTasks() has // been called. orphan_tasks_.clear(); // It's also now safe to replace our *_done_task_ tasks. required_for_activation_done_task_ = std::move(required_for_activation_done_task); required_for_draw_done_task_ = std::move(required_for_draw_done_task); all_done_task_ = std::move(all_done_task); did_check_for_completed_tasks_since_last_schedule_tasks_ = false; TRACE_EVENT_ASYNC_STEP_INTO1("cc", "ScheduledTasks", this, "running", "state", ScheduledTasksStateAsValue()); } scoped_refptr<TileTask> TileManager::CreateRasterTask( const PrioritizedTile& prioritized_tile) { Tile* tile = prioritized_tile.tile(); // Get the resource. uint64_t resource_content_id = 0; Resource* resource = nullptr; gfx::Rect invalidated_rect = tile->invalidated_content_rect(); if (UsePartialRaster() && tile->invalidated_id()) { resource = resource_pool_->TryAcquireResourceForPartialRaster( tile->id(), tile->invalidated_content_rect(), tile->invalidated_id(), &invalidated_rect); } if (resource) { resource_content_id = tile->invalidated_id(); DCHECK_EQ(DetermineResourceFormat(tile), resource->format()); } else { resource = resource_pool_->AcquireResource(tile->desired_texture_size(), DetermineResourceFormat(tile), gfx::ColorSpace()); } // For LOW_RESOLUTION tiles, we don't draw or predecode images. RasterSource::PlaybackSettings playback_settings; playback_settings.skip_images = prioritized_tile.priority().resolution == LOW_RESOLUTION; // Create and queue all image decode tasks that this tile depends on. TileTask::Vector decode_tasks; std::vector<DrawImage>& images = scheduled_draw_images_[tile->id()]; images.clear(); if (!playback_settings.skip_images) { prioritized_tile.raster_source()->GetDiscardableImagesInRect( tile->enclosing_layer_rect(), tile->contents_scale(), &images); } // We can skip the image hijack canvas if we have no images. playback_settings.use_image_hijack_canvas = !images.empty(); ImageDecodeController::TracingInfo tracing_info( prepare_tiles_count_, prioritized_tile.priority().priority_bin); for (auto it = images.begin(); it != images.end();) { scoped_refptr<TileTask> task; bool need_to_unref_when_finished = image_decode_controller_->GetTaskForImageAndRef(*it, tracing_info, &task); if (task) decode_tasks.push_back(task); if (need_to_unref_when_finished) ++it; else it = images.erase(it); } bool supports_concurrent_execution = !use_gpu_rasterization_; std::unique_ptr<RasterBuffer> raster_buffer = raster_buffer_provider_->AcquireBufferForRaster( resource, resource_content_id, tile->invalidated_id()); return make_scoped_refptr(new RasterTaskImpl( this, tile, resource, prioritized_tile.raster_source(), playback_settings, prioritized_tile.priority().resolution, invalidated_rect, prepare_tiles_count_, std::move(raster_buffer), &decode_tasks, supports_concurrent_execution)); } void TileManager::OnRasterTaskCompleted( std::unique_ptr<RasterBuffer> raster_buffer, Tile* tile, Resource* resource, bool was_canceled) { DCHECK(tile); DCHECK(tiles_.find(tile->id()) != tiles_.end()); raster_buffer_provider_->ReleaseBufferForRaster(std::move(raster_buffer)); TileDrawInfo& draw_info = tile->draw_info(); DCHECK(tile->raster_task_.get()); orphan_tasks_.push_back(tile->raster_task_); tile->raster_task_ = nullptr; // Unref all the images. auto images_it = scheduled_draw_images_.find(tile->id()); const std::vector<DrawImage>& images = images_it->second; for (const auto& image : images) image_decode_controller_->UnrefImage(image); scheduled_draw_images_.erase(images_it); if (was_canceled) { ++flush_stats_.canceled_count; resource_pool_->ReleaseResource(resource); return; } resource_pool_->OnContentReplaced(resource->id(), tile->id()); ++flush_stats_.completed_count; draw_info.set_use_resource(); draw_info.resource_ = resource; draw_info.contents_swizzled_ = DetermineResourceRequiresSwizzle(tile); DCHECK(draw_info.IsReadyToDraw()); draw_info.set_was_ever_ready_to_draw(); client_->NotifyTileStateChanged(tile); } ScopedTilePtr TileManager::CreateTile(const Tile::CreateInfo& info, int layer_id, int source_frame_number, int flags) { // We need to have a tile task worker pool to do anything meaningful with // tiles. DCHECK(tile_task_manager_); ScopedTilePtr tile( new Tile(this, info, layer_id, source_frame_number, flags)); DCHECK(tiles_.find(tile->id()) == tiles_.end()); tiles_[tile->id()] = tile.get(); return tile; } void TileManager::SetTileTaskManagerForTesting( TileTaskManager* tile_task_manager) { tile_task_manager_ = tile_task_manager; } void TileManager::SetRasterBufferProviderForTesting( RasterBufferProvider* raster_buffer_provider) { raster_buffer_provider_ = raster_buffer_provider; } bool TileManager::AreRequiredTilesReadyToDraw( RasterTilePriorityQueue::Type type) const { std::unique_ptr<RasterTilePriorityQueue> raster_priority_queue( client_->BuildRasterQueue(global_state_.tree_priority, type)); // It is insufficient to check whether the raster queue we constructed is // empty. The reason for this is that there are situations (rasterize on // demand) when the tile both needs raster and it's ready to draw. Hence, we // have to iterate the queue to check whether the required tiles are ready to // draw. for (; !raster_priority_queue->IsEmpty(); raster_priority_queue->Pop()) { if (!raster_priority_queue->Top().tile()->draw_info().IsReadyToDraw()) return false; } #if DCHECK_IS_ON() std::unique_ptr<RasterTilePriorityQueue> all_queue( client_->BuildRasterQueue(global_state_.tree_priority, type)); for (; !all_queue->IsEmpty(); all_queue->Pop()) { Tile* tile = all_queue->Top().tile(); DCHECK(!tile->required_for_activation() || tile->draw_info().IsReadyToDraw()); } #endif return true; } bool TileManager::IsReadyToActivate() const { TRACE_EVENT0("cc", "TileManager::IsReadyToActivate"); return AreRequiredTilesReadyToDraw( RasterTilePriorityQueue::Type::REQUIRED_FOR_ACTIVATION); } bool TileManager::IsReadyToDraw() const { TRACE_EVENT0("cc", "TileManager::IsReadyToDraw"); return AreRequiredTilesReadyToDraw( RasterTilePriorityQueue::Type::REQUIRED_FOR_DRAW); } void TileManager::CheckAndIssueSignals() { TRACE_EVENT0("cc", "TileManager::CheckAndIssueSignals"); tile_task_manager_->CheckForCompletedTasks(); did_check_for_completed_tasks_since_last_schedule_tasks_ = true; // Ready to activate. if (signals_.ready_to_activate && !signals_.did_notify_ready_to_activate) { signals_.ready_to_activate = false; if (IsReadyToActivate()) { TRACE_EVENT0("disabled-by-default-cc.debug", "TileManager::CheckAndIssueSignals - ready to activate"); signals_.did_notify_ready_to_activate = true; client_->NotifyReadyToActivate(); } } // Ready to draw. if (signals_.ready_to_draw && !signals_.did_notify_ready_to_draw) { signals_.ready_to_draw = false; if (IsReadyToDraw()) { TRACE_EVENT0("disabled-by-default-cc.debug", "TileManager::CheckAndIssueSignals - ready to draw"); signals_.did_notify_ready_to_draw = true; client_->NotifyReadyToDraw(); } } // All tile tasks completed. if (signals_.all_tile_tasks_completed && !signals_.did_notify_all_tile_tasks_completed) { signals_.all_tile_tasks_completed = false; if (!has_scheduled_tile_tasks_) { TRACE_EVENT0( "disabled-by-default-cc.debug", "TileManager::CheckAndIssueSignals - all tile tasks completed"); signals_.did_notify_all_tile_tasks_completed = true; client_->NotifyAllTileTasksCompleted(); } } } void TileManager::CheckIfMoreTilesNeedToBePrepared() { tile_task_manager_->CheckForCompletedTasks(); did_check_for_completed_tasks_since_last_schedule_tasks_ = true; // When OOM, keep re-assigning memory until we reach a steady state // where top-priority tiles are initialized. PrioritizedWorkToSchedule work_to_schedule = AssignGpuMemoryToTiles(); // Inform the client that will likely require a draw if the highest priority // tile that will be rasterized is required for draw. client_->SetIsLikelyToRequireADraw( !work_to_schedule.tiles_to_raster.empty() && work_to_schedule.tiles_to_raster.front().tile()->required_for_draw()); // |tiles_that_need_to_be_rasterized| will be empty when we reach a // steady memory state. Keep scheduling tasks until we reach this state. if (!work_to_schedule.tiles_to_raster.empty()) { ScheduleTasks(work_to_schedule); return; } // If we're not in SMOOTHNESS_TAKES_PRIORITY mode, we should unlock all // images since we're technically going idle here at least for this frame. if (global_state_.tree_priority != SMOOTHNESS_TAKES_PRIORITY) { for (auto& draw_image_pair : locked_images_) image_decode_controller_->UnrefImage(draw_image_pair.first); locked_images_.clear(); } FreeResourcesForReleasedTiles(); resource_pool_->ReduceResourceUsage(); image_decode_controller_->ReduceCacheUsage(); signals_.all_tile_tasks_completed = true; signals_check_notifier_.Schedule(); // We don't reserve memory for required-for-activation tiles during // accelerated gestures, so we just postpone activation when we don't // have these tiles, and activate after the accelerated gesture. // Likewise if we don't allow any tiles (as is the case when we're // invisible), if we have tiles that aren't ready, then we shouldn't // activate as activation can cause checkerboards. bool wait_for_all_required_tiles = global_state_.tree_priority == SMOOTHNESS_TAKES_PRIORITY || global_state_.memory_limit_policy == ALLOW_NOTHING; // If we have tiles left to raster for activation, and we don't allow // activating without them, then skip activation and return early. if (wait_for_all_required_tiles) return; // Mark any required tiles that have not been been assigned memory after // reaching a steady memory state as OOM. This ensures that we activate/draw // even when OOM. Note that we can't reuse the queue we used for // AssignGpuMemoryToTiles, since the AssignGpuMemoryToTiles call could have // evicted some tiles that would not be picked up by the old raster queue. bool need_to_signal_activate = MarkTilesOutOfMemory(client_->BuildRasterQueue( global_state_.tree_priority, RasterTilePriorityQueue::Type::REQUIRED_FOR_ACTIVATION)); bool need_to_signal_draw = MarkTilesOutOfMemory(client_->BuildRasterQueue( global_state_.tree_priority, RasterTilePriorityQueue::Type::REQUIRED_FOR_DRAW)); DCHECK(IsReadyToActivate()); DCHECK(IsReadyToDraw()); signals_.ready_to_activate = need_to_signal_activate; signals_.ready_to_draw = need_to_signal_draw; // TODO(ericrk): Investigate why we need to schedule this (not just call it // inline). http://crbug.com/498439 signals_check_notifier_.Schedule(); } bool TileManager::MarkTilesOutOfMemory( std::unique_ptr<RasterTilePriorityQueue> queue) const { // Mark required tiles as OOM so that we can activate/draw without them. if (queue->IsEmpty()) return false; for (; !queue->IsEmpty(); queue->Pop()) { Tile* tile = queue->Top().tile(); if (tile->draw_info().IsReadyToDraw()) continue; tile->draw_info().set_oom(); client_->NotifyTileStateChanged(tile); } return true; } ResourceFormat TileManager::DetermineResourceFormat(const Tile* tile) const { return raster_buffer_provider_->GetResourceFormat(!tile->is_opaque()); } bool TileManager::DetermineResourceRequiresSwizzle(const Tile* tile) const { return raster_buffer_provider_->IsResourceSwizzleRequired(!tile->is_opaque()); } std::unique_ptr<base::trace_event::ConvertableToTraceFormat> TileManager::ScheduledTasksStateAsValue() const { std::unique_ptr<base::trace_event::TracedValue> state( new base::trace_event::TracedValue()); state->BeginDictionary("tasks_pending"); state->SetBoolean("ready_to_activate", signals_.ready_to_activate); state->SetBoolean("ready_to_draw", signals_.ready_to_draw); state->SetBoolean("all_tile_tasks_completed", signals_.all_tile_tasks_completed); state->EndDictionary(); return std::move(state); } bool TileManager::UsePartialRaster() const { return use_partial_raster_ && raster_buffer_provider_->CanPartialRasterIntoProvidedResource(); } // Utility function that can be used to create a "Task set finished" task that // posts |callback| to |task_runner| when run. scoped_refptr<TileTask> TileManager::CreateTaskSetFinishedTask( void (TileManager::*callback)()) { return make_scoped_refptr(new TaskSetFinishedTaskImpl( task_runner_, base::Bind(callback, task_set_finished_weak_ptr_factory_.GetWeakPtr()))); } TileManager::MemoryUsage::MemoryUsage() : memory_bytes_(0), resource_count_(0) {} TileManager::MemoryUsage::MemoryUsage(size_t memory_bytes, size_t resource_count) : memory_bytes_(static_cast<int64_t>(memory_bytes)), resource_count_(static_cast<int>(resource_count)) { // MemoryUsage is constructed using size_ts, since it deals with memory and // the inputs are typically size_t. However, during the course of usage (in // particular operator-=) can cause internal values to become negative. Thus, // member variables are signed. DCHECK_LE(memory_bytes, static_cast<size_t>(std::numeric_limits<int64_t>::max())); DCHECK_LE(resource_count, static_cast<size_t>(std::numeric_limits<int>::max())); } // static TileManager::MemoryUsage TileManager::MemoryUsage::FromConfig( const gfx::Size& size, ResourceFormat format) { // We can use UncheckedSizeInBytes here since this is used with a tile // size which is determined by the compositor (it's at most max texture size). return MemoryUsage(ResourceUtil::UncheckedSizeInBytes<size_t>(size, format), 1); } // static TileManager::MemoryUsage TileManager::MemoryUsage::FromTile(const Tile* tile) { const TileDrawInfo& draw_info = tile->draw_info(); if (draw_info.resource_) { return MemoryUsage::FromConfig(draw_info.resource_->size(), draw_info.resource_->format()); } return MemoryUsage(); } TileManager::MemoryUsage& TileManager::MemoryUsage::operator+=( const MemoryUsage& other) { memory_bytes_ += other.memory_bytes_; resource_count_ += other.resource_count_; return *this; } TileManager::MemoryUsage& TileManager::MemoryUsage::operator-=( const MemoryUsage& other) { memory_bytes_ -= other.memory_bytes_; resource_count_ -= other.resource_count_; return *this; } TileManager::MemoryUsage TileManager::MemoryUsage::operator-( const MemoryUsage& other) { MemoryUsage result = *this; result -= other; return result; } bool TileManager::MemoryUsage::Exceeds(const MemoryUsage& limit) const { return memory_bytes_ > limit.memory_bytes_ || resource_count_ > limit.resource_count_; } TileManager::Signals::Signals() { reset(); } void TileManager::Signals::reset() { ready_to_activate = false; did_notify_ready_to_activate = false; ready_to_draw = false; did_notify_ready_to_draw = false; all_tile_tasks_completed = false; did_notify_all_tile_tasks_completed = false; } TileManager::PrioritizedWorkToSchedule::PrioritizedWorkToSchedule() = default; TileManager::PrioritizedWorkToSchedule::PrioritizedWorkToSchedule( PrioritizedWorkToSchedule&& other) = default; TileManager::PrioritizedWorkToSchedule::~PrioritizedWorkToSchedule() = default; } // namespace cc
[ "bino.zh@gmail.com" ]
bino.zh@gmail.com
cddccdec67323a703104b911ae0d4d4caa22b5c0
c12fc5319fb3fc3b99a148009bfdca97d095fcab
/Qt-OpenCV/Qt-OpenCV/detection.h
ff0db46cfe3f18fb28d5e655003b58414fde5365
[]
no_license
ruansongbo/image-segmentation
1181a29398b233b1a59c8522b4d421e97d274bc9
2f6868a822882a1586f7b5f3fa3f3c48dbc3a474
refs/heads/master
2021-08-14T07:54:06.965133
2017-10-13T10:46:20
2017-10-13T10:46:20
106,823,315
0
0
null
null
null
null
GB18030
C++
false
false
988
h
#ifndef DETECTION_H #define DETECTION_H #include <QtWidgets/QMainWindow> #include "ui_detection.h" #include <qtimer.h> #include <qstring.h> #include<opencv2/opencv.hpp> #include "opencv2/features2d/features2d.hpp" #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include<opencv2/legacy/legacy.hpp> #include <iostream> #include <vector> #include<windows.h> using namespace cv; class detection : public QMainWindow { Q_OBJECT public: detection(QWidget *parent = 0); ~detection(); private: Ui::detectionClass ui; QTimer *timer; VideoCapture *capture;// 视频获取结构, 用来作为视频获取函数的一个参数 QButtonGroup *typeGroup; int checkedID; private slots: void openCamera(); // 打开摄像头 void readFrame(); // 读取当前帧信息 void closeCamera(); // 关闭摄像头。 void takingPictures(); // 拍照 QImage Mat2QImage(cv::Mat cvImg); }; #endif // DETECTION_H
[ "ruansongbo@gmail.com" ]
ruansongbo@gmail.com
d09b06a94f35ead0decc6e9c2c98af03e93e3c02
1caca62a48044acf396e0cd17c137ef23591e063
/mbed06/6_6_FXOS8700CQ/main.cpp
c7152cebefbb2a405ddb4d14d305910501656ada
[]
no_license
andrew1205lin/109EE2405
1fffe573161accd39b308707335f76373fc9d5b9
465b3b18a5534460736b15b960cfb8bebcb8b0a4
refs/heads/master
2023-02-21T19:22:25.972052
2021-01-28T11:35:26
2021-01-28T11:35:26
333,670,421
0
0
null
null
null
null
UTF-8
C++
false
false
2,872
cpp
#include "mbed.h" #include "fsl_port.h" #include "fsl_gpio.h" #include "uLCD_4DGL.h" //add for uLCD #define UINT14_MAX 16383 // FXOS8700CQ I2C address #define FXOS8700CQ_SLAVE_ADDR0 (0x1E<<1) // with pins SA0=0, SA1=0 #define FXOS8700CQ_SLAVE_ADDR1 (0x1D<<1) // with pins SA0=1, SA1=0 #define FXOS8700CQ_SLAVE_ADDR2 (0x1C<<1) // with pins SA0=0, SA1=1 #define FXOS8700CQ_SLAVE_ADDR3 (0x1F<<1) // with pins SA0=1, SA1=1 // FXOS8700CQ internal register addresses #define FXOS8700Q_STATUS 0x00 #define FXOS8700Q_OUT_X_MSB 0x01 #define FXOS8700Q_OUT_Y_MSB 0x03 #define FXOS8700Q_OUT_Z_MSB 0x05 #define FXOS8700Q_M_OUT_X_MSB 0x33 #define FXOS8700Q_M_OUT_Y_MSB 0x35 #define FXOS8700Q_M_OUT_Z_MSB 0x37 #define FXOS8700Q_WHOAMI 0x0D #define FXOS8700Q_XYZ_DATA_CFG 0x0E #define FXOS8700Q_CTRL_REG1 0x2A #define FXOS8700Q_M_CTRL_REG1 0x5B #define FXOS8700Q_M_CTRL_REG2 0x5C #define FXOS8700Q_WHOAMI_VAL 0xC7 I2C i2c( PTD9,PTD8); Serial pc(USBTX, USBRX); uLCD_4DGL uLCD(D1, D0, D2); //add for uLCD int m_addr = FXOS8700CQ_SLAVE_ADDR1; void FXOS8700CQ_readRegs(int addr, uint8_t * data, int len); void FXOS8700CQ_writeRegs(uint8_t * data, int len); int main() { pc.baud(115200); uint8_t who_am_i, data[2], res[6]; int16_t acc16; float t[3]; // Enable the FXOS8700Q FXOS8700CQ_readRegs( FXOS8700Q_CTRL_REG1, &data[1], 1); data[1] |= 0x01; data[0] = FXOS8700Q_CTRL_REG1; FXOS8700CQ_writeRegs(data, 2); // Get the slave address FXOS8700CQ_readRegs(FXOS8700Q_WHOAMI, &who_am_i, 1); pc.printf("Here is %x\r\n", who_am_i); while (true) { FXOS8700CQ_readRegs(FXOS8700Q_OUT_X_MSB, res, 6); acc16 = (res[0] << 6) | (res[1] >> 2); if (acc16 > UINT14_MAX/2) acc16 -= UINT14_MAX; t[0] = ((float)acc16) / 4096.0f; acc16 = (res[2] << 6) | (res[3] >> 2); if (acc16 > UINT14_MAX/2) acc16 -= UINT14_MAX; t[1] = ((float)acc16) / 4096.0f; acc16 = (res[4] << 6) | (res[5] >> 2); if (acc16 > UINT14_MAX/2) acc16 -= UINT14_MAX; t[2] = ((float)acc16) / 4096.0f; printf("FXOS8700Q ACC: X=%1.4f(%x%x) Y=%1.4f(%x%x) Z=%1.4f(%x%x)\r\n",\ t[0], res[0], res[1],\ t[1], res[2], res[3],\ t[2], res[4], res[5]\ ); uLCD.locate(0, 0); //add for uLCD uLCD.printf("FXOS8700Q ACC: X=%1.4f(%x%x) Y=%1.4f(%x%x) Z=%1.4f(%x%x)\r\n",\ t[0], res[0], res[1],\ t[1], res[2], res[3],\ t[2], res[4], res[5]\ ); //add for uLCD wait(1.0); } } void FXOS8700CQ_readRegs(int addr, uint8_t * data, int len) { char t = addr; i2c.write(m_addr, &t, 1, true); i2c.read(m_addr, (char *)data, len); } void FXOS8700CQ_writeRegs(uint8_t * data, int len) { i2c.write(m_addr, (char *)data, len); }
[ "andrew1205lin@gmail.com" ]
andrew1205lin@gmail.com
4de5e2f310229d0e9992f3145924d90787e0b77c
d779e59530bab2f01190a382acd1d64cfc197568
/Placement Preparation Course [PPC 1]/17. Dynamic Programming/05. Coin Change - Minumum Number of Coins.cpp
f8940c225b0dc6f43d9997d143f6fd625c8cd2d9
[]
no_license
GokuPiyush/CP.cpp
6cef1f8268481deca8e40a190d667c1ccb92c78e
1f675197428ab726daaabc4fa5ab6a10044a202d
refs/heads/master
2023-02-21T17:44:20.080003
2021-01-20T09:00:30
2021-01-20T09:00:30
331,248,061
0
0
null
null
null
null
UTF-8
C++
false
false
2,655
cpp
/* You are given an amount denoted by value. You are also given an array of coins. The array contains the denominations of the give coins. You need to find the minimum number of coins to make the change for value using the coins of given denominations. Also, keep in mind that you have infinite supply of the coins. */ //Initial Template for C++ #include <bits/stdc++.h> using namespace std; // } Driver Code Ends //Complete this function int minCoins(int coins[], int m, int V) { // table[i] will be storing the minimum number of coins // required for i value. So table[V] will have result int table[V+1]; // Base case (If given value V is 0) table[0] = 0; // Initialize all table values as Infinite for (int i=1; i<=V; i++) table[i] = INT_MAX; // Compute minimum coins required for all // values from 1 to V for (int i=1; i<=V; i++) { // Go through all coins smaller than i for (int j=0; j<m; j++) if (coins[j] <= i) { int sub_res = table[i-coins[j]]; if (sub_res != INT_MAX && sub_res + 1 < table[i]) table[i] = sub_res + 1; } } return table[V] == INT_MAX? -1: table[V]; } long long minimumNumberOfCoinsUtil(int *coins, int n, int value, long long** dp){ if(value<0 || n==0){ return INT_MAX; } if(value == 0){ return 0; } if(dp[value][n] != -1){ return dp[value][n]; } return dp[value][n] = min(1+minimumNumberOfCoinsUtil(coins, n, value-coins[n-1], dp), minimumNumberOfCoinsUtil(coins, n-1, value, dp)); } long long minimumNumberOfCoins(int coins[],int numberOfCoins,int value) { // your code here long long **dp = new long long*[value+1]; for(int i=0; i<value+1; i++){ dp[i] = new long long[numberOfCoins+1]; for(int j=0; j<numberOfCoins+1; j++){ dp[i][j] = -1; } } long long ans = minimumNumberOfCoinsUtil(coins, numberOfCoins, value, dp); for(int i=0; i<value+1; i++){ delete[] dp[i]; } delete[] dp; return ans == INT_MAX? -1: ans; } // { Driver Code Starts. int main() { int testcases; cin>>testcases; while(testcases--) { int value; cin>>value; int numberOfCoins; cin>>numberOfCoins; int coins[numberOfCoins]; for(int i=0;i<numberOfCoins;i++) cin>>coins[i]; int answer=minimumNumberOfCoins(coins,numberOfCoins,value); if(answer==-1) cout<<"Not Possible"<<endl; else cout<<answer<<endl; } return 0; } // } Driver Code Ends
[ "PiyushTheGoku@gamil.com" ]
PiyushTheGoku@gamil.com
cbfd804267539007bc038749f5a7b97aa0aa34f4
025e31348577d6081e0839ff2d9765d2fa4ef8e0
/Segundo Semestre 2018-2/IPOO/Clases/Excepciones/Main.cpp
4652b64ec3381a8b8fb56cf383218815a1035936
[]
no_license
camilojm27/Universidad
0d777644d021049b2c238af623df67f70ce8c29b
7ce4f0fbfa65d68414555b1f670b6ad59c10293e
refs/heads/master
2022-01-15T18:45:51.915970
2019-07-27T16:10:03
2019-07-27T16:10:03
150,368,266
0
0
null
null
null
null
UTF-8
C++
false
false
2,314
cpp
/* Archivo: main.cpp Autor: Ángel García Baños Email: angel.garcia@correounivalle.edu.co Fecha creación: 2017-10-20 Fecha última modificación: 2019-02-22 Versión: 0.1 Licencia: GPL */ // Utilidad: excepciones #include<iostream> #include<string> using namespace std; int main() { /* // Si pedimos demasiada memoria (que el computador no tenga) se genera una excepción: int tamano = 8; for(int veces = 0; veces<10000000;veces++) { cout << "Veces=" << veces << endl; double *vector = new double[800000000]; for(int elemento = 0; elemento<tamano; elemento++) vector[elemento] = elemento* 1.2; for(int elemento = 0; elemento<tamano; elemento++) cout << vector[elemento] << " "; cout << endl; } */ /* // Podemos manejarla así: try { int tamano = 8; for(int veces = 0; veces<10000000;veces++) { cout << "Veces=" << veces << endl; double *vector = new double[800000000]; for(int elemento = 0; elemento<tamano; elemento++) vector[elemento] = elemento* 1.2; for(int elemento = 0; elemento<tamano; elemento++) cout << vector[elemento] << " "; cout << endl; } } catch(...) { cout << "ERROR: No hay espacio en memoria" << endl; } return 0; */ // Otras excepciones: /* int numerador = 7; int denominador = 0; int cociente = numerador/denominador; */ bool reintentar = true; while(reintentar) { try { cout << "Dime el numerador: "; int numerador; cin >> numerador; cout << "Dime el denominador: "; int denominador; cin >> denominador; if (numerador==77) throw 1; if(denominador==0) throw string("NO DIVIDAS POR CERO, POR FAVOR"); int cociente = numerador/denominador; cout << "El resultado de dividir " << numerador << " entre " << denominador << " es " << cociente << endl; reintentar = false; } catch(string mensaje) { cout << "ERROR: " << mensaje << endl; cout << "¿Quieres volverlo a intentar? (s/n)" << endl; string opcion; cin >> opcion; if(opcion=="n") reintentar=false; } catch(int codigo) { cout << "ERROR: codigo" << codigo << endl; } } return 0; }
[ "camilo272001@gmail.com" ]
camilo272001@gmail.com
63bc110d097023385ec2c3c3a5f654a6707887d4
fc38a55144a0ad33bd94301e2d06abd65bd2da3c
/thirdparty/cgal/CGAL-4.13/include/CGAL/CORE/BigRat.h
7886651f35ad35f7c69f43dd1ed82fc8e492bdea
[ "LGPL-3.0-only", "GPL-3.0-only", "GPL-1.0-or-later", "LGPL-2.1-or-later", "LicenseRef-scancode-free-unknown", "LGPL-2.0-or-later", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-unknown-license-reference", "MIT-0", "MIT", "LGPL-3.0-or-later", "LicenseRef-scancode-warranty-disc...
permissive
bobpepin/dust3d
20fc2fa4380865bc6376724f0843100accd4b08d
6dcc6b1675cb49ef3fac4a58845f9c9025aa4c9f
refs/heads/master
2022-11-30T06:00:10.020207
2020-08-09T09:54:29
2020-08-09T09:54:29
286,051,200
0
0
MIT
2020-08-08T13:45:15
2020-08-08T13:45:14
null
UTF-8
C++
false
false
12,623
h
/**************************************************************************** * Core Library Version 1.7, August 2004 * Copyright (c) 1995-2004 Exact Computation Project * All rights reserved. * * This file is part of CGAL (www.cgal.org). * You can redistribute it and/or modify it under the terms of the GNU * Lesser General Public License as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * Licensees holding a valid commercial license may use this file in * accordance with the commercial license agreement provided with the * software. * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * * File: BigRat.h * Synopsis: * a wrapper class for mpq from GMP * * Written by * Chee Yap <yap@cs.nyu.edu> * Chen Li <chenli@cs.nyu.edu> * Zilin Du <zilin@cs.nyu.edu> * * WWW URL: http://cs.nyu.edu/exact/ * Email: exact@cs.nyu.edu * * $URL$ * $Id$ * SPDX-License-Identifier: LGPL-3.0+ ***************************************************************************/ #ifndef _CORE_BIGRAT_H_ #define _CORE_BIGRAT_H_ #include <CGAL/CORE/BigInt.h> namespace CORE { class BigRatRep : public RCRepImpl<BigRatRep> { public: BigRatRep() { mpq_init(mp); } // Note : should the copy-ctor be alloed at all ? [Sylvain Pion] BigRatRep(const BigRatRep& z) : RCRepImpl<BigRatRep>() { mpq_init(mp); mpq_set(mp, z.mp); } BigRatRep(signed char c) { mpq_init(mp); mpq_set_si(mp, c, 1); } BigRatRep(unsigned char c) { mpq_init(mp); mpq_set_ui(mp, c, 1); } BigRatRep(signed int i) { mpq_init(mp); mpq_set_si(mp, i, 1); } BigRatRep(unsigned int i) { mpq_init(mp); mpq_set_ui(mp, i, 1); } BigRatRep(signed short int s) { mpq_init(mp); mpq_set_si(mp, s, 1); } BigRatRep(unsigned short int s) { mpq_init(mp); mpq_set_ui(mp, s, 1); } BigRatRep(signed long int l) { mpq_init(mp); mpq_set_si(mp, l, 1); } BigRatRep(unsigned long int l) { mpq_init(mp); mpq_set_ui(mp, l, 1); } BigRatRep(float f) { mpq_init(mp); mpq_set_d(mp, f); } BigRatRep(double d) { mpq_init(mp); mpq_set_d(mp, d); } BigRatRep(const char* s) { mpq_init(mp); mpq_set_str(mp, s, 0); } BigRatRep(const std::string& s) { mpq_init(mp); mpq_set_str(mp, s.c_str(), 0); } explicit BigRatRep(mpq_srcptr q) { mpq_init(mp); mpq_set(mp, q); } BigRatRep(mpz_srcptr z) { mpq_init(mp); mpq_set_z(mp, z); } BigRatRep(mpz_srcptr n, mpz_srcptr d) { mpq_init(mp); mpz_set(mpq_numref(mp), n); mpz_set(mpq_denref(mp), d); mpq_canonicalize(mp); } ~BigRatRep() { mpq_clear(mp); } CGAL_CORE_EXPORT CORE_NEW(BigRatRep) CGAL_CORE_EXPORT CORE_DELETE(BigRatRep) mpq_srcptr get_mp() const { return mp; } mpq_ptr get_mp() { return mp; } private: mpq_t mp; }; //BigRatRep class BigFloat; typedef RCImpl<BigRatRep> RCBigRat; class BigRat : public RCBigRat { public: /// \name Constructors //@{ /// default constructor BigRat() : RCBigRat(new BigRatRep()) {} /// constructor for <tt>signed char</tt> BigRat(signed char x) : RCBigRat(new BigRatRep(x)) {} /// constructor for <tt>unsigned char</tt> BigRat(unsigned char x) : RCBigRat(new BigRatRep(x)) {} /// constructor for <tt>signed short int</tt> BigRat(signed short int x) : RCBigRat(new BigRatRep(x)) {} /// constructor for <tt>unsigned short int</tt> BigRat(unsigned short int x) : RCBigRat(new BigRatRep(x)) {} /// constructor for <tt>signed int</tt> BigRat(signed int x) : RCBigRat(new BigRatRep(x)) {} /// constructor for <tt>unsigned int</tt> BigRat(unsigned int x) : RCBigRat(new BigRatRep(x)) {} /// constructor for <tt>signed long int</tt> BigRat(signed long int x) : RCBigRat(new BigRatRep(x)) {} /// constructor for <tt>unsigned long int</tt> BigRat(unsigned long int x) : RCBigRat(new BigRatRep(x)) {} /// constructor for <tt>float</tt> BigRat(float x) : RCBigRat(new BigRatRep(x)) {} /// constructor for <tt>double</tt> BigRat(double x) : RCBigRat(new BigRatRep(x)) {} /// constructor for <tt>const char*</tt> with base BigRat(const char* s) : RCBigRat(new BigRatRep(s)) {} /// constructor for <tt>std::string</tt> with base BigRat(const std::string& s) : RCBigRat(new BigRatRep(s)) {} /// constructor for <tt>mpq_srcptr</tt> explicit BigRat(mpq_srcptr z) : RCBigRat(new BigRatRep(z)) {} /// constructor for <tt>BigInt</tt> BigRat(const BigInt& z) : RCBigRat(new BigRatRep(z.get_mp())) {} /// constructor for two <tt>BigInts</tt> BigRat(const BigInt& n, const BigInt& d) : RCBigRat(new BigRatRep(n.get_mp(), d.get_mp())) {} /// constructor for <tt>BigFloat</tt> BigRat(const BigFloat&); //@} /// \name Copy-Assignment-Destructor //@{ /// copy constructor BigRat(const BigRat& rhs) : RCBigRat(rhs) { rep->incRef(); } /// assignment operator BigRat& operator=(const BigRat& rhs) { if (this != &rhs) { rep->decRef(); rep = rhs.rep; rep->incRef(); } return *this; } /// destructor ~BigRat() { rep->decRef(); } //@} /// \name Overloaded operators //@{ BigRat& operator +=(const BigRat& rhs) { makeCopy(); mpq_add(get_mp(), get_mp(), rhs.get_mp()); return *this; } BigRat& operator -=(const BigRat& rhs) { makeCopy(); mpq_sub(get_mp(), get_mp(), rhs.get_mp()); return *this; } BigRat& operator *=(const BigRat& rhs) { makeCopy(); mpq_mul(get_mp(), get_mp(), rhs.get_mp()); return *this; } BigRat& operator /=(const BigRat& rhs) { makeCopy(); mpq_div(get_mp(), get_mp(), rhs.get_mp()); return *this; } BigRat& operator <<=(unsigned long ul) { makeCopy(); mpq_mul_2exp(get_mp(), get_mp(), ul); return *this; } BigRat& operator >>=(unsigned long ul) { makeCopy(); mpq_div_2exp(get_mp(), get_mp(), ul); return *this; } //@} /// \name div2, unary, increment, decrement operators //@{ /// exact division by 2 (this method is provided for compatibility) BigRat div2() const { BigRat r; BigRat t(2); // probably not most efficient way mpq_div(r.get_mp(), get_mp(), t.get_mp()); return r; } BigRat operator+() const { return BigRat(*this); } BigRat operator-() const { BigRat r; mpq_neg(r.get_mp(), get_mp()); return r; } BigRat& operator++() { makeCopy(); mpz_add(get_num_mp(),get_num_mp(),get_den_mp()); return *this; } BigRat& operator--() { makeCopy(); mpz_sub(get_num_mp(),get_num_mp(),get_den_mp()); return *this; } BigRat operator++(int) { BigRat r(*this); ++(*this); return r; } BigRat operator--(int) { BigRat r(*this); --(*this); return r; } //@} /// \name Helper Functions //@{ /// Canonicalize void canonicalize() { makeCopy(); mpq_canonicalize(get_mp()); } /// Has Exact Division static bool hasExactDivision() { return true; } /// return mpz pointer of numerator (const) mpz_srcptr get_num_mp() const { return mpq_numref(get_mp()); } /// return mpz pointer of numerator mpz_ptr get_num_mp() { return mpq_numref(get_mp()); } /// return mpz pointer of denominator mpz_srcptr get_den_mp() const { return mpq_denref(get_mp()); } /// return mpz pointer of denominator mpz_ptr get_den_mp() { return mpq_denref(get_mp()); } /// get mpq pointer (const) mpq_srcptr get_mp() const { return rep->get_mp(); } /// get mpq pointer mpq_ptr get_mp() { return rep->get_mp(); } //@} /// \name String Conversion Functions //@{ /// set value from <tt>const char*</tt> int set_str(const char* s, int base = 0) { makeCopy(); return mpq_set_str(get_mp(), s, base); } /// convert to <tt>std::string</tt> std::string get_str(int base = 10) const { int n = mpz_sizeinbase(mpq_numref(get_mp()), base) + mpz_sizeinbase(mpq_denref(get_mp()), base)+ 3; char *buffer = new char[n]; mpq_get_str(buffer, base, get_mp()); std::string result(buffer); delete [] buffer; return result; } //@} /// \name Conversion Functions //@{ /// intValue int intValue() const { return static_cast<int>(doubleValue()); } /// longValue long longValue() const { return static_cast<long>(doubleValue()); } /// doubleValue double doubleValue() const { return mpq_get_d(get_mp()); } /// BigIntValue BigInt BigIntValue() const { BigInt r; mpz_tdiv_q(r.get_mp(), get_num_mp(), get_den_mp()); return r; } //@} }; //BigRat class inline BigRat operator+(const BigRat& a, const BigRat& b) { BigRat r; mpq_add(r.get_mp(), a.get_mp(), b.get_mp()); return r; } inline BigRat operator-(const BigRat& a, const BigRat& b) { BigRat r; mpq_sub(r.get_mp(), a.get_mp(), b.get_mp()); return r; } inline BigRat operator*(const BigRat& a, const BigRat& b) { BigRat r; mpq_mul(r.get_mp(), a.get_mp(), b.get_mp()); return r; } inline BigRat operator/(const BigRat& a, const BigRat& b) { BigRat r; mpq_div(r.get_mp(), a.get_mp(), b.get_mp()); return r; } // Chee (3/19/2004): // The following definitions of div_exact(x,y) and gcd(x,y) // ensures that in Polynomial<NT> /// divisible(x,y) = "x | y" inline BigRat div_exact(const BigRat& x, const BigRat& y) { BigRat z; mpq_div(z.get_mp(), x.get_mp(), y.get_mp()); return z; } /// numerator inline BigInt numerator(const BigRat& a) { return BigInt(a.get_num_mp()); } /// denominator inline BigInt denominator(const BigRat& a) { return BigInt(a.get_den_mp()); } inline BigRat gcd(const BigRat& x, const BigRat& y) { // return BigRat(1); // Remark: we may want replace this by // the definition of gcd of a quotient field // of a UFD [Yap's book, Chap.3] //Here is one possible definition: gcd of x and y is just the //gcd of the numerators of x and y divided by the gcd of the //denominators of x and y. BigInt n = gcd(numerator(x), numerator(y)); BigInt d = gcd(denominator(x), denominator(y)); return BigRat(n,d); } // Chee: 8/8/2004: need isDivisible to compile Polynomial<BigRat> // A trivial implementation is to return true always. But this // caused tPolyRat to fail. // So we follow the definition of // Expr::isDivisible(e1, e2) which checks if e1/e2 is an integer. inline bool isInteger(const BigRat& x) { return BigInt(x.get_den_mp()) == 1; } inline bool isDivisible(const BigRat& x, const BigRat& y) { BigRat r; mpq_div(r.get_mp(), x.get_mp(), y.get_mp()); return isInteger(r); } inline BigRat operator<<(const BigRat& a, unsigned long ul) { BigRat r; mpq_mul_2exp(r.get_mp(), a.get_mp(), ul); return r; } inline BigRat operator>>(const BigRat& a, unsigned long ul) { BigRat r; mpq_div_2exp(r.get_mp(), a.get_mp(), ul); return r; } inline int cmp(const BigRat& x, const BigRat& y) { return mpq_cmp(x.get_mp(), y.get_mp()); } inline bool operator==(const BigRat& a, const BigRat& b) { return cmp(a, b) == 0; } inline bool operator!=(const BigRat& a, const BigRat& b) { return cmp(a, b) != 0; } inline bool operator>=(const BigRat& a, const BigRat& b) { return cmp(a, b) >= 0; } inline bool operator>(const BigRat& a, const BigRat& b) { return cmp(a, b) > 0; } inline bool operator<=(const BigRat& a, const BigRat& b) { return cmp(a, b) <= 0; } inline bool operator<(const BigRat& a, const BigRat& b) { return cmp(a, b) < 0; } inline std::ostream& operator<<(std::ostream& o, const BigRat& x) { //return CORE::operator<<(o, x.get_mp()); return CORE::io_write(o, x.get_mp()); } inline std::istream& operator>>(std::istream& i, BigRat& x) { x.makeCopy(); //return CORE::operator>>(i, x.get_mp()); return CORE::io_read(i, x.get_mp()); } /// sign inline int sign(const BigRat& a) { return mpq_sgn(a.get_mp()); } /// abs inline BigRat abs(const BigRat& a) { BigRat r; mpq_abs(r.get_mp(), a.get_mp()); return r; } /// neg inline BigRat neg(const BigRat& a) { BigRat r; mpq_neg(r.get_mp(), a.get_mp()); return r; } /// div2 inline BigRat div2(const BigRat& a) { BigRat r(a); return r.div2(); } /// longValue inline long longValue(const BigRat& a) { return a.longValue(); } /// doubleValue inline double doubleValue(const BigRat& a) { return a.doubleValue(); } /// return BigInt value inline BigInt BigIntValue(const BigRat& a) { return a.BigIntValue(); } } //namespace CORE #endif // _CORE_BIGRAT_H_
[ "huxingyi@msn.com" ]
huxingyi@msn.com
29134a489d0999199c865cb0aa9dd1f11df8e312
9bccd122450d6a12f7c60092ead774aff8e24241
/queen.cpp
eaf80d510c2246e5f24cf77e0acab07f5b60b751
[]
no_license
romuloschiavon/QTChess
c2b6833177ef909deca993379fafc40a85dc3084
6760ff6ecc5218d2ec6ab2f3525c4fce04273474
refs/heads/main
2023-02-06T09:33:19.208118
2020-12-26T00:31:59
2020-12-26T00:31:59
320,921,038
0
0
null
null
null
null
UTF-8
C++
false
false
2,013
cpp
#include "queen.h" #include "chessboard.h" Queen::Queen(QObject *parent) : ChessAlgorithm(parent) { } void Queen::newGame() { setupBoard(); board()->setFen("rnbqkbnr/pp3ppp/8/8/8/8/PP3PPP/RNBQKBNR w KQkq - 0 1"); // 'w' - white to move setResult(NoResult); setCurrentPlayer(Player1); } bool Queen::move(int colFrom, int rankFrom, int colTo, int rankTo) { if(currentPlayer() == NoPlayer) return false; // is there a piece of the right color? char source = board()->data(colFrom, rankFrom); if(currentPlayer() == Player1 && source != 'B') return false; if(currentPlayer() == Player2 && source != 'b') return false; char destination = board()->data(colTo, rankTo); if ((currentPlayer() == Player1) && (destination == 'P' || destination == 'N' || destination == 'B' || destination == 'Q' || destination == 'R' )) return false; if ((currentPlayer() == Player2) && (destination == 'p' || destination == 'n' || destination == 'b' || destination == 'q' || destination == 'r')) return false; if (destination == 'k') setResult(Player1Wins); if (destination == 'K') setResult(Player2Wins); // if(colFrom != colTo && rankFrom != rankTo){ //if(colFrom + rankFrom == colTo + rankTo){ board()->movePiece(colFrom, rankFrom, colTo, rankTo); setCurrentPlayer(currentPlayer() == Player1 ? Player2 : Player1); return true; // }else if(colFrom == colTo || rankFrom == rankTo){ return false; }if(colFrom != colTo && rankFrom == rankTo){ board()->movePiece(colFrom, rankFrom, colTo, rankTo); setCurrentPlayer(currentPlayer() == Player1 ? Player2 : Player1); return true; } else if (colFrom == colTo && rankFrom != rankTo){ board()->movePiece(colFrom, rankFrom, colTo, rankTo); setCurrentPlayer(currentPlayer() == Player1 ? Player2 : Player1); return true; } else return false; }
[ "noreply@github.com" ]
noreply@github.com
5bdce5c1cb44c374b6402b898aaf0346ef537843
598d50ac6dc155e762560f6aa494924e4af60e9a
/first_fit.cpp
8bd6ef6c882f9a677be032be8a8f691c8070f07d
[]
no_license
shawon-tanvir/Operating-System-Algorithms
c9c083867ab84f88e0295ad9356e092d63f94dd9
bf2a2ad0a1a45284fe53c70fef7f1b4dfc81b82e
refs/heads/master
2022-12-19T14:38:58.072900
2019-04-22T19:19:45
2019-04-22T19:19:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,234
cpp
#include<bits/stdc++.h> using namespace std; int main(){ int m,n; cin>>m; int mem[m]; for(int i=0;i<m;i++){ cin>>mem[i]; } cin>>n; int req[n]; int frag=0; for(int i=0;i<n;i++){ cin>>req[i]; } int table[m][n]; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ table[i][j]=-2; } } int col=0; bool check; for(int i=0;i<n;i++){ check=false; for(int j=0;j<m;j++){ if(req[i]<=mem[j]){ check=true; mem[j]-=req[i]; break; } } if(check==true){ for(int row=0,j=0;j<m;j++){ table[row++][col]=mem[j]; } col++; } if(check==false){ for(int i=0;i<m;i++){ frag+=mem[i]; } break; } } for(int i=0;i<n;i++){ cout<<req[i]<<"\t"; } cout<<endl; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ cout<<table[i][j]<<"\t"; } cout<<endl; } if(frag>0){ cout<<"External Fragmentation = "<<frag<<endl; } } /* 5 50 200 70 115 15 10 100 10 35 15 23 6 25 55 88 40 */
[ "shawontanvir95@gmail.com" ]
shawontanvir95@gmail.com
45c0763e34dc09ffed8a7b689e4d6da94e57c89b
697b291e677d61411abf678f9133ec3e0bf1545f
/1765577/Control de Flujo/PUNTO 3.cpp
714c9d9990e81490788c26e1858c53c228ef8417
[]
no_license
gomezpirry/IPOO_Febrero-Junio_2018
400a059caac71d0c1d04b1b1bc509776f7e8bded
bf2bfc12f75cd041ebd3c78581f7d6a8876fe586
refs/heads/master
2021-01-25T10:29:44.613499
2018-06-26T18:46:08
2018-06-26T18:46:08
123,357,208
0
0
null
null
null
null
UTF-8
C++
false
false
1,036
cpp
//------------------------------------------ //------ Calificación 0.71 // //------------------------------------------ #include <iostream> using namespace std; int main(){ int numero; cout<<"Ingrese el numero del mes: ";cin>>numero; switch (numero){ case 1: cout<<"El numero corresponde a: Enero";break; case 2: cout<<"El numero corresponde a: Febrero";break; case 3: cout<<"El numero corresponde a: Marzo";break; case 4: cout<<"El numero corresponde a: Abril";break; case 5: cout<<"El numero corresponde a: Mayo";break; case 6: cout<<"El numero corresponde a: Junio";break; case 7: cout<<"El numero corresponde a: Julio";break; case 8: cout<<"El numero corresponde a: Agosto";break; case 9: cout<<"El numero corresponde a: Septiembre";break; case 10: cout<<"El numero corresponde a: Octubre";break; case 11: cout<<"El numero corresponde a: Noviembre";break; case 12: cout<<"El numero corresponde a: Diciembre";break; default: cout<<"El numero ingresado no corresponde a ningun mes";break; } }
[ "augusto.gomez@correounivalle.edu.co" ]
augusto.gomez@correounivalle.edu.co
5534e12a75d3c6f469524d85996011608ed3f06a
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_14373.cpp
6dc02aaf041ede84ff43977931dd63a1f8a9e8bf
[]
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
37
cpp
{ count++; p = p->next_filter; }
[ "993273596@qq.com" ]
993273596@qq.com
7b09559007759ec04eba41aacf8e00e372d60701
c0caed81b5b3e1498cbca4c1627513c456908e38
/src/core/scoring/aa_composition_energy/AACompositionConstraint.cc
dcbb4a421a873517ad86fd6331c78c4a3ee2c1c0
[]
no_license
malaifa/source
5b34ac0a4e7777265b291fc824da8837ecc3ee84
fc0af245885de0fb82e0a1144422796a6674aeae
refs/heads/master
2021-01-19T22:10:22.942155
2017-04-19T14:13:07
2017-04-19T14:13:07
88,761,668
0
2
null
null
null
null
UTF-8
C++
false
false
4,480
cc
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington UW TechTransfer, email: license@u.washington.edu. /// @file src/core/scoring/aa_composition_energy/AACompositionConstraint.cc /// @brief A constraint for constraining sequences to have a desired amino acid composition, analogous to a geometric constraint. /// @details The corresponding energy term for this constraint is the AACompositionEnergy (aa_composition in wts files). /// @author Vikram K. Mulligan (vmullig@uw.edu) #include <core/scoring/aa_composition_energy/AACompositionConstraint.hh> #include <core/scoring/constraints/ConstraintIO.hh> #include <core/pose/Pose.hh> #include <core/pose/util.hh> #include <core/conformation/Conformation.hh> #include <core/select/residue_selector/ResidueSelector.hh> #include <core/scoring/aa_composition_energy/AACompositionEnergySetup.hh> #include <basic/Tracer.hh> #include <numeric/xyz.functions.hh> #include <numeric/trig.functions.hh> #include <numeric/deriv/dihedral_deriv.hh> #include <utility/exit.hh> #include <utility/vector1.hh> namespace core { namespace scoring { namespace aa_composition_energy { static THREAD_LOCAL basic::Tracer TR( "core.scoring.aa_composition_energy.AACompositionConstraint" ); /// @brief Constructor /// AACompositionConstraint::AACompositionConstraint(): core::scoring::aa_composition_energy::SequenceConstraint( core::scoring::aa_composition ), //TODO -- initialize variables here. selector_(), aa_comp_setup_( new AACompositionEnergySetup ) {} /// @brief Copy constructor /// AACompositionConstraint::AACompositionConstraint( AACompositionConstraint const &src ): core::scoring::aa_composition_energy::SequenceConstraint( core::scoring::aa_composition ), //TODO -- copy variables here. selector_(), //Cloned if present, below aa_comp_setup_() //Cloned below. { if ( src.selector_ ) selector_ = src.selector_->clone(); runtime_assert( src.aa_comp_setup_ ); aa_comp_setup_ = src.aa_comp_setup_->clone(); } /// @brief Destructor /// AACompositionConstraint::~AACompositionConstraint() {} /// @brief Clone operator /// core::scoring::constraints::ConstraintOP AACompositionConstraint::clone() const { return core::scoring::constraints::ConstraintOP( new AACompositionConstraint( *this ) ); } bool AACompositionConstraint::operator == ( Constraint const & other ) const { if ( ! other.same_type_as_me( *this ) ) return false; if ( ! same_type_as_me( other ) ) return false; // TO DO: implement ResidueSelector comparison operators. // TO DO: implement AACompositionEnergySetup comparison operator return false; } bool AACompositionConstraint::same_type_as_me( Constraint const & other ) const { return dynamic_cast< AACompositionConstraint const * > (&other); } /// @brief Set the selector to be used by this constraint. /// @details Clones the input. void AACompositionConstraint::set_selector( core::select::residue_selector::ResidueSelectorCOP selector_in ) { selector_ = selector_in->clone(); return; } select::residue_selector::ResidueSelectorCOP AACompositionConstraint::selector() const { return selector_; } AACompositionEnergySetupCOP AACompositionConstraint::aa_composition_energy_setup() const { return aa_comp_setup_; } /// @brief Initialize the AACompositionEnergySetup object from a file. /// void AACompositionConstraint::initialize_from_file( std::string const &filename ) { runtime_assert( aa_comp_setup_ ); //The pointer should point at an actual object. aa_comp_setup_->initialize_from_file( filename ); return; } /// @brief Initialize the AACompositionEnergySetup object from the contents of a file. /// @details Allows external code to initialize a constriant object without having the /// object read directly from disk. void AACompositionConstraint::initialize_from_file_contents( std::string const &filecontents ) { runtime_assert( aa_comp_setup_ ); //The pointer should point at an actual object. aa_comp_setup_->initialize_from_file_contents( filecontents ); return; } } // aa_composition_energy } // scoring } // core
[ "malaifa@yahoo.com" ]
malaifa@yahoo.com
547348424f51630d8c79db0e030e580e41bdbbe0
4cb0da26684cd377b48a881914174ee68971cec3
/longestSubarraysumDivisiblebyk.cpp
4593cb1b20c0da2780f371d91c6e0aff2d671569
[]
no_license
randomuy1289/Introduction-to-Data-Structures-and-Algorithms
d0294f246d0cd9fa772236a00e5989b1fd2d38d1
60be8349bb3f5da5c438047bec24de24de91475e
refs/heads/master
2022-06-21T23:10:25.349110
2020-05-09T12:55:56
2020-05-09T12:55:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
719
cpp
#include<bits/stdc++.h> using namespace std; int longSubarraywithSum(int arr[], int n, int k){ unordered_map<int,int> um; int mod_arr[n], max=0; int curr_sum=0; for(int i=0;i<n;i++) { curr_sum += arr[i]; mod_arr[i] = ((curr_sum %k)+k)%k; } for(int i=0;i<n;i++){ if(mod_arr[i] == 0) max= i+1; else if(um.find(mod_arr[i])==um.end()) um[mod_arr[i]] = i; else if(max< (i-um[mod_arr[i]])) max= i - um[mod_arr[i]]; } return max; } int main(){ int arr[]= {2,7,6,1,4,5}; int n = sizeof(arr)/sizeof(arr[0]); int k=3; cout<<"Length= "<<longSubarraywithSum(arr,n,k); return 0; }
[ "swastikarora007@gmail.com" ]
swastikarora007@gmail.com
cebbfc104e956049f44d8c58d9d0cf0786669e1e
a95a044b475f20f48d999a260a72726bb6e72318
/lab3/GameOfLife/mainwindow.cpp
b8761283e7a4f336594f9ff6a3de0c0834d1e661
[]
no_license
IlyaRomahin/16208_romahin
4f2c85a7b9357dea89f0da3de4c459f711bba986
b12484d2a43cab1537b1fbbe378f113d6baf4824
refs/heads/master
2021-09-09T09:29:09.045417
2018-03-14T20:17:34
2018-03-14T20:17:34
103,540,354
0
0
null
null
null
null
UTF-8
C++
false
false
7,985
cpp
#include <QTextStream> #include <QFileDialog> #include <QDebug> #include <QColor> #include <QColorDialog> #include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), currentColor(QColor("#000")), field(new RenderArea(this)) { ui->setupUi(this); QPixmap icon(16, 16); icon.fill(currentColor); ui->colorButton->setIcon( QIcon(icon) ); connect(ui->startButton, SIGNAL(clicked()), this, SLOT(startBut())); connect(ui->stopButton, SIGNAL(clicked()), this, SLOT(stopBut())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clearBut())); connect(ui->rulesControl, SIGNAL(currentTextChanged(QString)), this, SLOT(rulesCont(QString))); connect(ui->iterInterval, SIGNAL(valueChanged(int)), this, SLOT(iterInter(int))); connect(ui->heightControl, SIGNAL(valueChanged(int)), this, SLOT(heightCont(int))); connect(ui->widthControl, SIGNAL(valueChanged(int)), this, SLOT(widthCont(int))); connect(ui->colorButton, SIGNAL(clicked()), this, SLOT(colorBut())); connect(ui->scrollButton, SIGNAL(clicked()), this, SLOT(scrollBut())); connect(ui->loadButton, SIGNAL(clicked()), this, SLOT(loadBut())); connect(ui->saveButton, SIGNAL(clicked()), this, SLOT(saveBut())); connect(field, SIGNAL(environmentChanged(bool)), this, SLOT(updateModel(bool))); connect(field, SIGNAL(environmentChanged(bool)), ui->heightControl, SLOT(setDisabled(bool))); connect(field, SIGNAL(environmentChanged(bool)), ui->widthControl, SLOT(setDisabled(bool))); connect(field, SIGNAL(environmentChanged(bool)), ui->colorButton, SLOT(setDisabled(bool))); connect(field, &RenderArea::nextGeneration, [this](bool b){newGeneration(b);}); connect(field, &RenderArea::needCheck, [this](bool b){check(b);}); ui->rulesControl->addItem( "Conway`s" ); ui->rulesControl->addItem( "HighLife" ); ui->rulesControl->addItem( "Day & Night" ); ui->rulesControl->addItem( "Life without Death" ); ui->rulesControl->addItem( "Seeds" ); ui->rulesControl->addItem( "My rule" ); ui->mainLayout->setStretchFactor(ui->gameLayout, 8); ui->mainLayout->setStretchFactor(ui->setLayout, 2); ui->gameLayout->setStretchFactor(ui->scrollArea, 8); ui->scrollArea->setWidget(field); setDisabledBoxes(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::startGame() { field->startGame(); ui->saveButton->setDisabled(true); ui->loadButton->setDisabled(true); } void MainWindow::stopGame() { field->stopGame(); ui->saveButton->setEnabled(true); ui->loadButton->setEnabled(true); } std::vector<bool> &MainWindow::getUniverse() { return field->getUniverse(); } std::vector<bool> &MainWindow::getNext() { return field->getNext(); } void MainWindow::setNext(std::vector<bool> &n) { field->setNext(n); } void MainWindow::setUniverse(std::vector<bool> &u) { field->setUniverse(u); } void MainWindow::setRule(std::string fRule) { QString rule = QString::fromStdString(fRule); ui->rulesControl->setCurrentText(rule); rulesCont(rule); } void MainWindow::setHeight(const int h) { field->setHeight(h); } void MainWindow::setWidth(const int w) { field->setWidth(w); } void MainWindow::setEnabledSpinBoxes() { ui->widthControl->setEnabled(true); ui->heightControl->setEnabled(true); ui->colorButton->setEnabled(true); } void MainWindow::setEnabledBoxes() { ui->lc1->setEnabled(true); ui->lc2->setEnabled(true); ui->lc3->setEnabled(true); ui->lc4->setEnabled(true); ui->lc5->setEnabled(true); ui->lc6->setEnabled(true); ui->lc7->setEnabled(true); ui->lc8->setEnabled(true); ui->bc1->setEnabled(true); ui->bc2->setEnabled(true); ui->bc3->setEnabled(true); ui->bc4->setEnabled(true); ui->bc5->setEnabled(true); ui->bc6->setEnabled(true); ui->bc7->setEnabled(true); ui->bc8->setEnabled(true); } void MainWindow::setDisabledBoxes() { ui->lc1->setDisabled(true); ui->lc2->setDisabled(true); ui->lc3->setDisabled(true); ui->lc4->setDisabled(true); ui->lc5->setDisabled(true); ui->lc6->setDisabled(true); ui->lc7->setDisabled(true); ui->lc8->setDisabled(true); ui->bc1->setDisabled(true); ui->bc2->setDisabled(true); ui->bc3->setDisabled(true); ui->bc4->setDisabled(true); ui->bc5->setDisabled(true); ui->bc6->setDisabled(true); ui->bc7->setDisabled(true); ui->bc8->setDisabled(true); } void MainWindow::needUpdate() { field->needUpdate(); } void MainWindow::updateModel(bool) { emit(environmentChanged(true)); } void MainWindow::newGeneration(bool) { emit(nextGeneration(true)); } void MainWindow::check(bool) { life.clear(); birth.clear(); life.resize(8, bool()); birth.resize(8, bool()); if (ui->lc1->isChecked() && ui->lc1->isEnabled()) { life[0] = true; } if (ui->lc2->isChecked() && ui->lc2->isEnabled()) { life[1] = true; } if (ui->lc3->isChecked() && ui->lc3->isEnabled()) { life[2] = true; } if (ui->lc4->isChecked() && ui->lc4->isEnabled()) { life[3] = true; } if (ui->lc5->isChecked() && ui->lc5->isEnabled()) { life[4] = true; } if (ui->lc6->isChecked() && ui->lc6->isEnabled()) { life[5] = true; } if (ui->lc7->isChecked() && ui->lc7->isEnabled()) { life[6] = true; } if (ui->lc8->isChecked() && ui->lc8->isEnabled()) { life[7] = true; } if (ui->bc1->isChecked() && ui->bc1->isEnabled()) { birth[0] = true; } if (ui->bc2->isChecked() && ui->bc2->isEnabled()) { birth[1] = true; } if (ui->bc3->isChecked() && ui->bc3->isEnabled()) { birth[2] = true; } if (ui->bc4->isChecked() && ui->bc4->isEnabled()) { birth[3] = true; } if (ui->bc5->isChecked() && ui->bc5->isEnabled()) { birth[4] = true; } if (ui->bc6->isChecked() && ui->bc6->isEnabled()) { birth[5] = true; } if (ui->bc7->isChecked() && ui->bc7->isEnabled()) { birth[6] = true; } if (ui->bc8->isChecked() && ui->bc8->isEnabled()) { birth[7] = true; } emit(needCheck(birth, life)); } int MainWindow::interval() { return field->interval(); } void MainWindow::setInterval(const int msec) { field->setInterval(msec); } void MainWindow::startBut() { emit startButclicked(true); } void MainWindow::stopBut() { emit(stopButclicked(true)); } void MainWindow::clearBut() { emit(clearButclicked(true)); } void MainWindow::saveBut() { emit(saveButclicked(true)); } void MainWindow::loadBut() { emit(loadButclicked(true)); } void MainWindow::colorBut() { emit(colorButclicked(true)); } void MainWindow::scrollBut() { field->returnToNormalZoom(); } void MainWindow::rulesCont(QString r) { emit(rulesContValueChanged(r)); } void MainWindow::iterInter(int it) { emit(iterInterValueChanged(it)); } void MainWindow::setCellsWidth(int cw) { ui->widthControl->setValue(cw); emit(widthContValueChanged(cw)); } void MainWindow::setCellsHeight(int ch) { ui->heightControl->setValue(ch); emit(heightContValueChanged(ch)); } void MainWindow::heightCont(int h) { emit(heightContValueChanged(h)); } void MainWindow::widthCont(int w) { emit(widthContValueChanged(w)); } QColor MainWindow::masterColor() { return field->masterColor(); } void MainWindow::setMasterColor(const QColor &color) { field->setMasterColor(color); } void MainWindow::selectMasterColor() { QColor color = QColorDialog::getColor(currentColor, this, tr("Select color of figures")); if(!color.isValid()) return; currentColor = color; field->setMasterColor(color); QPixmap icon(16, 16); icon.fill(color); ui->colorButton->setIcon( QIcon(icon) ); }
[ "i.romakhin@g.nsu.ru" ]
i.romakhin@g.nsu.ru
a50d725ae838ced8341f4ccdd5251faa6bd53fab
b3839099049a5d34e14b2452c4969fd4f2a3333c
/src/pipeline_layout.test.cpp
a21cc6895fbb33d99a8aa17564cb0c652ee0c007
[ "MIT" ]
permissive
jeffw387/vkaEngine
bb71827118929ec5aaa883e7bb41bbfbf26d0e22
69bc21d4c10229ab823a887147cb45888d9afbaf
refs/heads/master
2021-07-08T19:07:34.049415
2019-02-24T06:53:45
2019-02-24T06:53:45
144,421,157
1
0
null
null
null
null
UTF-8
C++
false
false
278
cpp
#include "pipeline_layout.hpp" #include <catch2/catch.hpp> #include "descriptor_set_layout.hpp" #include "device.hpp" #include "instance.hpp" #include "move_into.hpp" #include "physical_device.hpp" #include "platform_glfw.hpp" #include "queue_family.hpp" using namespace vka;
[ "jeffw387@gmail.com" ]
jeffw387@gmail.com
5025bbfe71566ac38baa995bdb7a2b8ae483db4e
c057e033602e465adfa3d84d80331a3a21cef609
/C/testcases/CWE126_Buffer_Overread/s02/CWE126_Buffer_Overread__new_wchar_t_memcpy_82.h
775af26061e1911d8bdbd318997fac1f8ffa755a
[]
no_license
Anzsley/My_Juliet_Test_Suite_v1.3_for_C_Cpp
12c2796ae7e580d89e4e7b8274dddf920361c41c
f278f1464588ffb763b7d06e2650fda01702148f
refs/heads/main
2023-04-11T08:29:22.597042
2021-04-09T11:53:16
2021-04-09T11:53:16
356,251,613
1
0
null
null
null
null
UTF-8
C++
false
false
1,153
h
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE126_Buffer_Overread__new_wchar_t_memcpy_82.h Label Definition File: CWE126_Buffer_Overread__new.label.xml Template File: sources-sink-82.tmpl.h */ /* * @description * CWE: 126 Buffer Over-read * BadSource: Use a small buffer * GoodSource: Use a large buffer * Sinks: memcpy * BadSink : Copy data to string using memcpy * Flow Variant: 82 Data flow: data passed in a parameter to a virtual method called via a pointer * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE126_Buffer_Overread__new_wchar_t_memcpy_82 { class CWE126_Buffer_Overread__new_wchar_t_memcpy_82_base { public: /* pure virtual function */ virtual void action(wchar_t * data) = 0; }; #ifndef OMITBAD class CWE126_Buffer_Overread__new_wchar_t_memcpy_82_bad : public CWE126_Buffer_Overread__new_wchar_t_memcpy_82_base { public: void action(wchar_t * data); }; #endif /* OMITBAD */ #ifndef OMITGOOD class CWE126_Buffer_Overread__new_wchar_t_memcpy_82_goodG2B : public CWE126_Buffer_Overread__new_wchar_t_memcpy_82_base { public: void action(wchar_t * data); }; #endif /* OMITGOOD */ }
[ "65642214+Anzsley@users.noreply.github.com" ]
65642214+Anzsley@users.noreply.github.com
a2165b042e749a5013aa346e480bec5efd86edaa
74a82c80e5361cb51175ffbed0d778ccd4295c21
/include/stb_imageUtils.h
ec18c5ed59a623b74f6bf8204e488c34b573b25f
[]
no_license
amauryTCassola/Projeto-FCG
fac26a9e9acc8b520814a2e4a47c4d043ee42e71
0f9d511ae539742ff37dcb0a83e41a558ca5511c
refs/heads/master
2020-05-30T17:51:36.450509
2019-06-24T01:37:47
2019-06-24T01:37:47
189,884,106
0
0
null
null
null
null
ISO-8859-1
C++
false
false
731
h
#include <cmath> #include <cstdio> #include <cstdlib> // Headers abaixo são específicos de C++ #include <map> #include <stack> #include <string> #include <vector> #include <limits> #include <fstream> #include <sstream> #include <stdexcept> #include <algorithm> // Headers das bibliotecas OpenGL #include <glad/glad.h> // Criação de contexto OpenGL 3.3 #include <GLFW/glfw3.h> // Criação de janelas do sistema operacional // Headers da biblioteca GLM: criação de matrizes e vetores. #include <glm/mat4x4.hpp> #include <glm/vec4.hpp> #include <glm/gtc/type_ptr.hpp> struct Image{ unsigned char* data; int width, height, channels; }; Image LoadImageFromDisc(const char* filename); void DestroyImg(Image img);
[ "amaury_cassola@yahoo.com.br" ]
amaury_cassola@yahoo.com.br
ad1ed8f35f4df5507af661d7263375aa4c7a4b12
725d0a71ad9d385eacca64aa1b9ad52234238519
/include/Game/Orders/Move.hpp
002015cb85b51d1fcfe24a3b7dbf984a026985e3
[]
no_license
ganzf/AgeOfLazies
42cd24f64e2503a545ec68725f9a46c0b12c859b
f92af05b2493961172b28376e2e01d2463004a19
refs/heads/master
2021-03-24T13:00:27.661347
2017-06-23T13:14:50
2017-06-23T13:14:50
94,310,589
0
0
null
null
null
null
UTF-8
C++
false
false
561
hpp
#ifndef MOVE_HPP_ # define MOVE_HPP_ # include "Game/Orders/Order.hpp" namespace AoL { namespace Game { class Unit; class Entity; namespace Orders { class Move : public AOrder { AoL::Game::Unit &parent; AoL::Game::Entity *target; irr::core::vector2df const *dest; bool toFree; public: Move(AoL::Game::Unit &parent, AoL::Game::Entity *target); Move(AoL::Game::Unit &parent, irr::core::vector2df const *pos); ~Move(); virtual bool apply(irr::f32 elapsedTime); }; } } } #endif /* !MOVE_HPP_ */
[ "felix.ganz@epitech.eu" ]
felix.ganz@epitech.eu
afcabe0d88f6ef5ab47cb8e943aa94f502f30171
1c803d259e1f459426fdd62b5399f4c3a65a5291
/3/inheritance.cpp
1426e569170ed49599d3dd32fe3a897e70f06eec
[]
no_license
CIS190/spring2020
3c13816718116b333d8ec9744fc19cde3e7661db
3d58cefae7051e0adfa7159f6a83e439fe96bb14
refs/heads/master
2021-08-05T22:10:37.891693
2020-12-18T20:46:53
2020-12-18T20:46:53
230,176,647
7
5
null
null
null
null
UTF-8
C++
false
false
749
cpp
#include <iostream> using namespace std; class animal { protected: string name; public: animal(string name) : name {name} {} virtual void pet() const = 0; }; class dog : public animal { public: dog(string name) : animal {name} {} void pet() const override { cout << name << " wags its tail."; } }; class cat : public animal { public: cat(string name) : animal {name} {} void pet() const override { cout << name << " purrs."; } }; void petLots(const animal & a) { for (int i {0}; i < 10; ++i) { a.pet(); cout << "\n"; } } void test(cat c) { } int main() { dog d {"Rover"}; cat c {"Strawberry"}; petLots(d); petLots(c); }
[ "paulhe@seas.upenn.edu" ]
paulhe@seas.upenn.edu
c2b301ef9bc3e2957737c61508b7e1c18f638869
a368b5cb07481385f301bf070d9870907c51ea13
/pybind/pyVO.cpp
68d398d454802f06097cc1f147346ef654d5aea0
[]
no_license
Xbbei/pyVO
cf4b157f0eaa67992243c1c6d41ed8268bb57d68
c6651c227c9dc77ba08e4d4edca304de02df8f0c
refs/heads/master
2023-02-23T00:48:49.533876
2021-01-22T03:07:13
2021-01-22T03:07:13
327,804,618
5
1
null
null
null
null
UTF-8
C++
false
false
952
cpp
//base #include "pybind/base/homography_matrix.h" #include "pybind/base/pose.h" // estimator #include "pybind/estimator/essential_matrix.h" #include "pybind/estimator/fundamental_matrix.h" #include "pybind/estimator/homography_matrix.h" // optim #include "pybind/optim/random_sampler.h" #include "pybind/optim/support_measurement.h" // feature #include "pybind/feature/sift.h" #include "pybind/feature/orb.h" #include "pybind/feature/types.h" #include "pybind/feature/matcher.h" PYBIND11_MODULE(pyVO, m) { // base pybind_base_homography_matrix(m); pybind_base_pose(m); // estimator pybind_estimator_essential_matrix(m); pybind_estimator_fundamental_matrix(m); pybind_estimator_homography_matrix(m); // optim pybind_optim_random_sampler(m); pybind_optim_support_measurement(m); // feature pybind_feature_sift(m); pybind_feature_types(m); pybind_feature_orb(m); pybind_feature_matcher(m); }
[ "565702745@qq.com" ]
565702745@qq.com
1d173311f2d888dc263d2ff875e040f5e39ff6a1
97529d623e1df1c716e1570b98d0f090e736c238
/qt/qtsqlface/database.h
794eb95448b4c2e9c9e63f2650014e6fdf0211e0
[]
no_license
leilei-help/code
2f83e9a01b3ccb84625b1c8b3e43a07939785dd1
3244703afb4eb99ef6e2d77edbd346b3405f64f7
refs/heads/master
2022-01-27T00:47:16.339792
2018-04-20T12:25:06
2018-04-20T12:25:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
420
h
#ifndef INIDB_H #define INIDB_H // it can include qtsql only set Qt += sql in .pro #include <QtSql> #include <sqlite3.h> class PersonDatabase { public: sqlite3 *db; sqlite3_stmt *stmt; PersonDatabase(); ~PersonDatabase(); void addFeature(const int &id, const std::string &name, const float *feature); void deleteFeature(const int &id); QSqlError getConnection(); }; #endif // INIDB_H
[ "1208266117@qq.com" ]
1208266117@qq.com
58c953bbf7f4c39d244543a107d947fa36fbac70
f9f6fc36564d9c53a36b6f64677350ac3dad9351
/cpp_practice/test_stack.cpp
af103add9479fc81ebd2be15d8278807eadff5a2
[]
no_license
a358003542/cpp_practice
023efbf319a3560267e37e630602800fd9e084eb
813241137a13cdae666a11b59204bcd53d09cbff
refs/heads/master
2023-02-18T03:47:10.773212
2021-01-18T03:14:45
2021-01-18T03:14:45
257,798,370
0
0
null
null
null
null
UTF-8
C++
false
false
904
cpp
#include <iostream> #include "stack.h" #include <cctype> //int main() { int main45(){ using namespace std; Stack st; char ch; unsigned long po; cout << "Please enter A to add a purchase order,\n" << "P to process a PO, or Q to quit.\n"; while (cin >> ch && toupper(ch) != 'Q') { while (cin.get() != '\n') { continue; } if (!isalpha(ch)) { cout << '\a'; continue; } switch (ch){ case 'A': case 'a': cout << "Enter a PO number to add: "; cin >> po; if (st.isfull()) { cout << "stack already full\n"; } else { st.push(po); } break; case 'p': case 'P': if (st.isempty()) { cout << "stack already empty\n"; } else { st.pop(po); cout << "PO #" << po << " popped\n"; } break; } cout << "Please enter A to add a purchase order,\n" << "P to process a PO, or Q to quit.\n"; } cout << "Bye\n"; return 0; }
[ "a358003542@gmail.com" ]
a358003542@gmail.com
b61c2c2d47137d93a6781b442361f66d4570b545
3df19976f5b2ab687d74e00de2b2c5a7f4bca69d
/nclgl/Light.cpp
ee9e0d1f7ac58f9737a8622548cce9e9fc9258dd
[]
no_license
ltarne/NCLGL-Coursework
f9b5196f246c29058959f3626dce8626d7a53c7f
d705f68fbba8ab8af6a3544587a70b2bcf95a750
refs/heads/master
2021-11-23T19:13:44.997386
2018-02-06T22:26:37
2018-02-06T22:26:37
110,580,788
0
0
null
null
null
null
UTF-8
C++
false
false
538
cpp
#include "Light.h" //Light::Light(Vector3 position, Vector4 colour, float radius, Shader * shader, Mesh * mesh) // : SceneNode(shader, mesh, colour) { // this->position = position; // this->transform = Matrix4::Translation(position); // this->colour = colour; // this->radius = radius; //} // //void Light::Draw(const OGLRenderer & renderer) { // LoadUniforms(); // if (!depthTest) { // glDisable(GL_DEPTH_TEST); // } // // // if (mesh != nullptr) { // mesh->Draw(); // } // // if (!depthTest) { // glEnable(GL_DEPTH_TEST); // } //}
[ "lhburton23@gmail.com" ]
lhburton23@gmail.com
25b42986b123cac69aa460577efbd44560a74e45
4a25c45fea5aedbd5846893669526f33274ee41f
/src/waypoints.cpp
3f94b696d38ed1187e39eaa38ad91779228a8634
[]
no_license
Aand1/CarND-MPC-Project
2eb40495d31c0416f5df3c822c4dd1c98ebf9c57
c1eb997d7fb10effe120bed2022534dc2f571ee4
refs/heads/master
2021-01-02T08:29:28.952960
2017-05-25T20:28:46
2017-05-25T20:28:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,526
cpp
#include "waypoints.h" #include <Eigen/QR> using Eigen::ArrayXd; using Eigen::Map; using Eigen::MatrixXd; Waypoints local(double px, double py, double ph, const Waypoints &global) { vector<double> lx; vector<double> ly; double cos_h = cos(ph); double sin_h = sin(ph); auto &gx = global[0]; auto &gy = global[1]; for (int i = 0, n = gx.size(); i < n; ++i) { double xt = gx[i] - px; double yt = gy[i] - py; double xi = xt * cos_h + yt * sin_h; double yi = yt * cos_h - xt * sin_h; lx.push_back(xi); ly.push_back(yi); } return {lx, ly}; } Waypoints perform(double dt, double v0, const vector<double> &actuations) { double x = 0; double y = 0; double h = 0; double v = v0; Waypoints waypoints(2); auto a = actuations.begin(); auto d = a + 1; for (auto n = actuations.end(); a != n; a += 2, d += 2) { v += *a * dt; h += *d * dt; x += cos(h) * v * dt; y += sin(h) * v * dt; waypoints[0].push_back(x); waypoints[1].push_back(y); } return waypoints; } VectorXd polyfit(const Waypoints &waypoints, int order) { int rows = waypoints[0].size(); Map<const ArrayXd> xvals(waypoints[0].data(), rows); Map<const VectorXd> yvals(waypoints[1].data(), rows); MatrixXd A(rows, order + 1); A.block(0, 0, rows, 1).fill(1.0); for (int j = 0; j < order; j++) { auto Aj = A.block(0, j, rows, 1).array(); A.block(0, j + 1, rows, 1) = Aj * xvals; } auto Q = A.householderQr(); auto result = Q.solve(yvals); return result; }
[ "mail@xperroni.me" ]
mail@xperroni.me
4e6adc4026631f15d603ca77f2ca70dd00fbde38
8f856432e98231e79d1f49a46aefd014599bf708
/CC & AO/C & A/Main.cpp
698305573ab5fc8209bd5d23d871cc4f49b85eb1
[]
no_license
akash0395/uniquerepo
e01529504926ac3afdc04d6e19437b3eb99a0d83
188843f6fec9c6277486768afd869ce644146743
refs/heads/master
2020-09-23T22:09:37.210794
2019-12-03T15:29:46
2019-12-03T15:29:46
225,598,933
0
0
null
null
null
null
UTF-8
C++
false
false
455
cpp
#include"ABC.h" int main() { ABC a(10,"hellooo");; a.display(); ABC b(132,"thereeee"); b.display(); ABC d(664,(char *)"Assignment operator check"); d.display(); printf("----assignment operator ------\n"); b.operator=(d);//b=d and b.operator=(d) both are same; b.display(); printf("------+operator-------\n"); ABC e; e=a+b; e.display(); printf("--------copy constructor-------\n"); ABC c(a); c.display(); return 0; }
[ "akashmane1434@gmail.com" ]
akashmane1434@gmail.com
996fdd2c096232f4ce5f4312d197212a97847610
671b33372cd8eaf6b63284b03b94fbaf5eb8134e
/protocols/pbft/replica/PBFT_R_Pre_prepare_info.h
78cb3a170176ba7da9b3fe003712e51be6297bf1
[ "MIT" ]
permissive
LPD-EPFL/consensusinside
41f0888dc7c0f9bd25f1ff75781e7141ffa21894
4ba9c5274a9ef5bd5f0406b70d3a321e7100c8ac
refs/heads/master
2020-12-24T15:13:51.072881
2014-11-30T11:27:41
2014-11-30T11:27:41
23,539,134
5
2
null
null
null
null
UTF-8
C++
false
false
2,972
h
#ifndef _PBFT_R_Pre_prepare_info_h #define _PBFT_R_Pre_prepare_info_h 1 #include "types.h" #include "PBFT_R_Pre_prepare.h" class PBFT_R_Pre_prepare_info { // // Holds information about a pre-prepare and matching big requests. // public: PBFT_R_Pre_prepare_info(); // Effects: Creates an empty object. ~PBFT_R_Pre_prepare_info(); // Effects: Discard this and any pre-prepare message it may contain. void add(PBFT_R_Pre_prepare* p); // Effects: Adds "p" to this. void add_complete(PBFT_R_Pre_prepare* p); // Effects: Adds "p" to this and records that all the big reqs it // refers to are cached. void add(Digest &rd, int i); // Effects: If there is a pre-prepare in this and its i-th reference // to a big request is for the request with digest rd record that // this digest is cached. PBFT_R_Pre_prepare* pre_prepare() const; // Effects: If there is a pre-prepare message in this returns // it. Otherwise, returns 0. BR_map missing_reqs() const; // Effects: Returns a bit map with the indices of missing requests. bool is_complete() const; // Effects: Returns true iff this contains a pre-prepare and all the // big requests it references are cached. void clear(); // Effects: Makes this empty and deletes any pre-prepare in it. void zero(); // Effects: Makes this empty without deleting any contained // pre-prepare. class BRS_iter { // An iterator for yielding the requests in ppi that are missing // in mrmap. public: BRS_iter(PBFT_R_Pre_prepare_info const *p, BR_map m); // Effects: Return an iterator for the missing requests in mrmap bool get(PBFT_R_Request*& r); // Effects: Sets "r" to the next request in this that is missing // in mrmap, and returns true. Unless there are no more missing // requests in this, in which case it returns false. private: PBFT_R_Pre_prepare_info const * ppi; BR_map mrmap; int next; }; friend class BRS_iter; bool encode(FILE* o); bool decode(FILE* i); // Effects: Encodes and decodes object state from stream. Return // true if successful and false otherwise. private: PBFT_R_Pre_prepare* pp; short mreqs; // Number of missing requests BR_map mrmap; // PBFT_R_Bitmap with bit reset for every missing request }; inline PBFT_R_Pre_prepare_info::PBFT_R_Pre_prepare_info() { pp = 0; } inline void PBFT_R_Pre_prepare_info::zero() { pp = 0; } inline void PBFT_R_Pre_prepare_info::add_complete(PBFT_R_Pre_prepare* p) { th_assert(pp == 0, "Invalid state"); pp = p; mreqs = 0; mrmap = ~0; } inline PBFT_R_Pre_prepare* PBFT_R_Pre_prepare_info::pre_prepare() const { return pp; } inline BR_map PBFT_R_Pre_prepare_info::missing_reqs() const { return mrmap; } inline void PBFT_R_Pre_prepare_info::clear() { delete pp; pp = 0; } inline bool PBFT_R_Pre_prepare_info::is_complete() const { return pp != 0 && mreqs == 0; } #endif //_PBFT_R_Pre_prepare_info_h
[ "tudor.david@gmail.com" ]
tudor.david@gmail.com
482902068957fcbbdd2ec65c447bd19f5f2cff8c
316fb44f366c4af023695d1062e37faafd8e6072
/Source/Qt/Display404.cpp
d02d95a4fa39b675977253c9c9f91216c1d20c85
[ "BSD-2-Clause" ]
permissive
Megatokio/Z80EMUF
a4f869400531801a13bfbe22d7c560a3c861154d
3bb4e0417a19d33b1c3eafc15c6828310854edca
refs/heads/master
2021-08-17T00:31:18.742222
2020-09-05T10:57:55
2020-09-05T10:57:55
218,489,044
2
1
null
null
null
null
UTF-8
C++
false
false
3,985
cpp
/* Copyright (c) Günter Woigk 2013 - 2019 mailto:kio@little-bat.de This file is free software. Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appears in all copies and that both that copyright notice, this permission notice and the following disclaimer appear in supporting documentation. THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT ANY WARRANTY, NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE AND IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DAMAGES ARISING FROM THE USE OF THIS SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. */ #include "kio/kio.h" #include "Display404.h" #include "Display404Font.h" #include <QBitmap> #include <QPainter> #include <QColor> #include <QPen> #include <QPixmap> #include <QTransform> //#include "Sio.h" static const int zoom = 3; // 2 static const int hpadding = 6; static const int hspacing = 1; static const int width = (40*5 + 39*hspacing + 2*hpadding) * zoom; static const int vpadding = 6; static const int vspacing = 3; static const int height = (4*8 + 3*vspacing + 2*vpadding ) * zoom; static const QColor bgcolor(0x66,0x88,0x00,0xff); // rgba static const QColor fgcolor(0x11,0x33,0x00,0xff); // rgba Display404::Display404 (QWidget* parent) : QWidget(parent) { setFixedWidth(::width); setFixedHeight(::height); //QWidget::setEnabled(true); // enable mouse & kbd events (true=default) setFocusPolicy(Qt::StrongFocus); // sonst kriegt das Toolwindow manchmal keine KeyEvents //setAttribute(Qt::WA_OpaquePaintEvent,on); // wir malen alle Pixel. Qt muss nicht vorher löschen. x=y=0; canvas = new QPixmap(width(),height()/*,QImage::Format_RGB32*/); painter = new QPainter(canvas); painter->setBackground(QBrush(bgcolor)); painter->setPen(Qt::NoPen); painter->setBrush(fgcolor); painter->setWorldTransform(QTransform::fromScale(zoom,zoom)); painter->eraseRect(canvas->rect()); print("1234567890123456789012345678901234567890"); print("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmn"); //print("This is the 404 Display!\n\r"); } Display404::~Display404() { delete painter; delete canvas; } void Display404::scrollUp() { int y0 = vpadding*zoom; int lh = 8*zoom; // line height int ls = vspacing*zoom; // line separation int dy = lh+ls; int bh = 3*lh + 2*ls; // moving block height QTransform trans; painter->setWorldTransform(trans); painter->drawPixmap(QPoint(0,y0),canvas->copy(0, y0+dy, width(), bh)); painter->eraseRect(0,y0+bh+ls, width(),lh); update(rect()); trans.scale(zoom,zoom); painter->setWorldTransform(trans); } void Display404::printAt (int x, int y, uchar c) { int x0 = hpadding + x * (5+hspacing); int y0 = vpadding + y * (8+vspacing); uint8* q = font_data + c*8; uint8 m; painter->eraseRect(x0,y0, 5,8); for (y = y0; y < y0+8; y++) { if ((c = *q++)) { for (x = x0, m = 0x10; m; x++, m>>=1) { if (c & m) painter->drawRect(x,y,1,1); } } } update(x, y, 5*zoom, 8*zoom); } void Display404::print (uchar c) { if (c>=' ') { if (x>=40) { x%=40; y++; } if (y>=4) { scrollUp(); y=3; } printAt(x,y,c); x++; } else { switch (c) { case 10: y++; break; case 13: x=0; break; default: break; } } } void Display404::print (cstr s) { while(*s) print(uchar(*s++)); } void Display404::paintEvent (QPaintEvent*) { QPainter painter(this); painter.drawPixmap(0,0,*canvas); if(hasFocus()) { painter.setPen(QPen(QColor(0x88,0xff,0x00,0x88),6)); //painter.setCompositionMode(QPainter::CompositionMode_Darken); painter.drawRect(rect()); } } void Display404::focusInEvent (QFocusEvent* e) { update(rect()); QWidget::focusInEvent(e); emit focusChanged(1); } void Display404::focusOutEvent (QFocusEvent* e) { update(rect()); QWidget::focusOutEvent(e); emit focusChanged(0); }
[ "kio@little-bat.de" ]
kio@little-bat.de
37465da9025436e89f3bf59a732cd8f31f3d9fa4
af0ecafb5428bd556d49575da2a72f6f80d3d14b
/CodeJamCrawler/dataset/14_20459_55.cpp
e9b064c96f1fc0dfe8ac85dbf0b517cb69764be0
[]
no_license
gbrlas/AVSP
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
e259090bf282694676b2568023745f9ffb6d73fd
refs/heads/master
2021-06-16T22:25:41.585830
2017-06-09T06:32:01
2017-06-09T06:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,269
cpp
#include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <vector> #include <queue> #include <stack> #include <list> #include <map> #include <set> #include <bitset> #include <string> #include <iostream> #include <cassert> using namespace std; typedef long long ll; const double PI = acos(-1); const double EPS = 1e-7; #define PB push_back #define MP make_pair #define FOR(_i, _from, _to) for (int (_i) = (_from), (_batas) = (_to); (_i) <= (_batas); (_i)++) #define REP(_i, _n) for (int (_i) = 0, (_batas) = (_n); (_i) < (_batas); (_i)++) #define SZ(_x) ((int)(_x).size()) const int RC = 4; int grid[RC + 5][RC + 5]; int possible[20]; void solve(int tc) { memset(possible, 0, sizeof possible); int ans; scanf("%d", &ans); REP(i, RC) REP(j, RC) scanf("%d", &grid[i][j]); REP(j, RC) possible[grid[ans-1][j]]++; scanf("%d", &ans); REP(i, RC) REP(j, RC) scanf("%d", &grid[i][j]); REP(j, RC) possible[grid[ans-1][j]]++; vector<int> twice; FOR(i, 1, 16) if (possible[i] == 2) twice.PB(i); printf("Case #%d: ", tc); if (SZ(twice) == 1) printf("%d\n", twice[0]); else if (SZ(twice) == 0) puts("Volunteer cheated!"); else puts("Bad magician!"); } int main() { int T; scanf("%d", &T); REP(i, T) solve(i+1); return 0; }
[ "nikola.mrzljak@fer.hr" ]
nikola.mrzljak@fer.hr
87ec7c40f0e864b9ac5ad0d543f54cd412e2b70d
666d89b913442892d1fd7b4b7285a14a870dfa6b
/Client/src/GameModel/Commands/ListConnectedPlayersCommand.cpp
5b36ea8204248485bdb1302645e4396f6dd83f49
[ "MIT" ]
permissive
mauro7x/argentum
9a7624d74cd12966ec95a8b6a06360c525f57e70
10c1a49c929d00ab7e5b5d93ec4e415bba40c713
refs/heads/master
2022-11-27T21:55:53.658345
2020-07-31T07:20:50
2020-07-31T07:20:50
266,701,581
14
2
null
2020-07-31T07:16:28
2020-05-25T06:30:23
C++
UTF-8
C++
false
false
881
cpp
#include "../../../includes/GameModel/Commands/ListConnectedPlayersCommand.h" //----------------------------------------------------------------------------- // Métodos privados //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // API Pública ListConnectedPlayersCommand::ListConnectedPlayersCommand() : Command() {} bool ListConnectedPlayersCommand::send(const SocketWrapper& socket) { // Enviamos el comando según el protocolo if (!(socket << (uint8_t)COMMAND_OPCODE)) { return false; } if (!(socket << (uint8_t)LIST_CONNECTED_PLAYERS_CMD)) { return false; } return true; } ListConnectedPlayersCommand::~ListConnectedPlayersCommand() {} //-----------------------------------------------------------------------------
[ "mparafati@fi.uba.ar" ]
mparafati@fi.uba.ar
5551ac98cbbc2cd2e2045a78e35847b30e194c05
93b06d4544dcf22162e8581200e34faea8766859
/Source Code/OpenGLObjects/OpenGLTunnels.cpp
7d0c0aa976bf6d67dcc79710bd47d54f26e9ef1f
[]
no_license
PsyPhy/GRASP-on-ISS-Corrupted
752e7645a6f72f56f5a3a6afa20cf034a324ac13
e120e80197b1e8ad9b93256421ef864584afdf5f
refs/heads/master
2020-05-02T13:31:02.996804
2016-03-25T08:19:32
2016-03-25T08:19:32
49,293,644
0
0
null
null
null
null
ISO-8859-1
C++
false
false
14,555
cpp
//--------------------------------------------------------------------------- /********************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <windows.h> #include <mmsystem.h> #include <gl/gl.h> #include <gl/glu.h> #include "../Useful/Useful.h" #include "OpenGLObjects.h" #include "OpenGLColors.h" #include "OpenGLUseful.h" #include "OpenGlTunnels.h" // Couloir #define RSEG 10.0 // Laisser le ".0" pour forcer le type float #define LSEG 66.0 #define NSLICES 16 #define NSTACKS 16 #define SREP 1 #define TREP 1 // Par segment // Deplacement #define ANTICIPATION 16 // Comparable à LSEG /******************************************************************************************/ ///////////////////////// // Cylinder's definition ///////////////////////// TunnelSegment::TunnelSegment( float length, float radius ) { this->length = length; this->radius = radius; OpenGLObject(); // Do what every OpenGlObject does at creation. } void TunnelSegment::Draw( void ) { GLfloat x, y, z, new_z; GLfloat nX, nY; GLfloat S, T, Tnew; int stack, slice; float teta; if ( ! enabled ) return; PrepDraw(); if ( list < 0 ) { glNewList( list = 1, GL_COMPILE ); z = 0; T = 0; for( stack=0 ; stack < NSTACKS ; stack++ ) { Tnew = T + (double) SREP / (double) NSTACKS; glBegin( GL_QUAD_STRIP ); S = 0; new_z = z + length / NSTACKS; for( teta = 0, slice = 0 ; slice <= NSLICES ; slice++ ) { nX = cos( teta ); nY = sin( teta ); x = radius * cos( teta ); y = radius * sin( teta ); glNormal3f( nX, nY, 0.0 ); glTexCoord2f( S, T ); glVertex3f( x, y, z ); glNormal3f( nX, nY, 0.0 ); glTexCoord2f( S, Tnew ); glVertex3f( x, y, new_z ); // 1er segment est -z teta += 2.0 * pi / (double) NSLICES; S += (double) SREP / (double) NSLICES; } glEnd(); z = new_z; T =Tnew; } glEndList(); } else glCallList( list ); FinishDraw(); } /******************************************************************************************/ ///////////////////////// // Junction's definition ///////////////////////// void TunnelJunction::Draw( void ) { GLfloat *T; GLfloat dT; GLfloat Xold[NSLICES+1], Yold[NSLICES+1], Zold[NSLICES+1]; GLfloat x, y, z; GLfloat nXold[NSLICES+1], nYold[NSLICES+1], nZold[NSLICES+1], nX, nY, nZ; GLfloat S, Tnew; int stack, slice; float teta, phi; if ( ! enabled ) return; PrepDraw(); // Initialisation des Xolds (premier cercle de pts, phi=0) for(teta=0, slice=0 ; slice<=NSLICES ; slice++) { nXold[slice] = sin( teta ); nYold[slice] = - cos( teta ); nZold[slice] = 0; Xold[slice] = RSEG * sin( teta ); Yold[slice] = - RSEG * cos( teta ); Zold[slice] = 0; teta += 2.0 * pi / NSLICES; } phi = pi / 2.0 / NSTACKS; for(stack=0 ; stack<NSTACKS ; stack++) { glBegin(GL_QUAD_STRIP); Tnew = *T + dT * pi * RSEG / NSTACKS; S = 0; for( teta=0, slice=0; slice <= NSLICES ; slice++ ) { nX = sin(teta); nY = - cos( teta ) * cos( phi ); nZ = - cos( teta )* sin( phi ); x = RSEG * sin( teta ); y = - RSEG * ( cos( phi ) * ( 1.0 + cos(teta) ) - 1.0); z = - RSEG * sin( phi ) * ( 1.0 + cos( teta ) ); glNormal3f( nXold[slice], nYold[slice], nZold[slice] ); glTexCoord2f(S, *T); glVertex3f( Xold[slice], Yold[slice], Zold[slice] ); glNormal3f( nX, nY, nZ ); glTexCoord2f( S, Tnew ); glVertex3f( x, y, z ); nXold[slice] = nX; nYold[slice] = nY; nZold[slice] = nZ; Xold[slice] = x; Yold[slice] = y; Zold[slice] = z; S += (GLfloat) SREP / NSLICES; teta += 2.0 * pi / NSLICES; } glEnd(); phi += 90.0/NSTACKS; *T = Tnew; } FinishDraw(); } /******************************************************************************************/ ///////////////////////// // Cylinder's definition ///////////////////////// Tunnel::Tunnel( void ) { texture = new Texture( "Lime.bmp" ); OpenGLObject(); // Do what every OpenGlObject does at creation. } #if 0 ////////////////////////////////// // Camera's position calculation ////////////////////////////////// void __fastcall Tunnel::CameraPosition( GLfloat t ) { GLfloat N[3]; GLfloat tmp[3], tmp2[3]; double r, teta; ////////////////// // Position keys ////////////////// if(t >= PosKeyTime[NextPosKey]) { if(NextPosKey == nPosKey) // fin d'animation : quite return(false); else { LastPosKey++; NextPosKey++; } } if(Compare(PosKeyDir[LastPosKey], PosKeyDir[NextPosKey])) { // Segment de droite r = (t - PosKeyTime[LastPosKey])/(PosKeyTime[NextPosKey] - PosKeyTime[LastPosKey]); Scal(tmp, (GLfloat) LSEG*r, PosKeyDir[LastPosKey]); Add(View, tmp, PosKey[LastPosKey]); } else { // Arc de cercle teta = M_PI_2 * (t - PosKeyTime[LastPosKey])/(PosKeyTime[NextPosKey] - PosKeyTime[LastPosKey]); Scal(tmp, (GLfloat) RSEG*sin(teta), PosKeyDir[LastPosKey]); Scal(tmp2, (GLfloat) -RSEG*cos(teta), PosKeyDir[NextPosKey]); Add(View, tmp, tmp2); Scal(tmp, (GLfloat) RSEG, PosKeyDir[NextPosKey]); Add(View, View, tmp); Add(View, View, PosKey[LastPosKey]); } ////////////////// // Rotation keys ////////////////// if(t >= RotKeyTime[NextRotKey]) { if(NextRotKey == nRotKey) // fin d'animation : quite return(false); else { LastRotKey++; NextRotKey++; } // Initialisations de keyframe au cas ou pas de rotation envisagée Affect(ViewDir, RotKeyDir[LastRotKey]); Affect(ViewUp, RotKeyUp[LastRotKey]); } r = (t - RotKeyTime[LastRotKey])/(RotKeyTime[NextRotKey] - RotKeyTime[LastRotKey]); if(! Compare(RotKeyUp[LastRotKey], RotKeyUp[NextRotKey])) Interpolate(ViewUp, r, RotKeyUp[LastRotKey], RotKeyUp[NextRotKey]); if(! Compare(RotKeyDir[LastRotKey], RotKeyDir[NextRotKey])) Interpolate(ViewDir, r, RotKeyDir[LastRotKey], RotKeyDir[NextRotKey]); #ifdef FPS_DEBUG frames++; if(frames >= 10) { char str[40]; sprintf(str, "Navigation 3D (%.2ffps)", 10000/(t-oldt)); fprintf(fdebug, "\n%.2ffps", 10000/(t-oldt)); // SetWindowText(GLwin.hWnd, str); oldt = t; frames = 0; } #endif // Calcule Ref à partir de viewdir Add(Ref, View, ViewDir); return(true); } ////////////////////////////////////////// // Creates a direction array // for MakeKeyFrames() and MakeCouloir() ////////////////////////////////////////// void __fastcall Tunnel::MakeDir( char *nom, short nseg, GLfloat dir[10][3] ) { short i, sig; // Pour le bon fonctionnement de la rotation dir[0][0] = 0; dir[0][1] = -1; dir[0][2] = 0; for(i=1 ; i<=nseg ; i++) { sig = (nom[2*(i-1)] == '+')? 1 : -1; switch(nom[2*(i-1)+1]) { case 'x' : dir[i][0] = 1.0*sig; dir[i][1] = 0; dir[i][2] = 0; break; case 'y' : dir[i][1] = 1.0*sig; dir[i][0] = 0; dir[i][2] = 0; break; case 'z' : dir[i][2] = 1.0*sig; dir[i][0] = 0; dir[i][1] = 0; break; } } } /////////////////////////////////////// // KeyFrames for camera's position /////////////////////////////////////// void __fastcall Tunnel::MakeKeyFrames( char *nom, short nseg, short condition ) { short i, k; GLfloat tmp[3]; GLfloat dir[10][3]; MakeDir(nom, nseg, dir); /////////////////////// // Position KeyFrames /////////////////////// // 1st PosKey[0][0] = PosKey[0][1] = PosKey[0][2] = 0; Affect(PosKeyDir[0], dir[1]); PosKeyTime[0] = 0; // 2st Scal(PosKey[1], LSEG, dir[1]); Affect(PosKeyDir[1], dir[1]); PosKeyTime[1] = (double) LSEG / SPEED; for(k=2, i=2 ; i<=nseg ; i++) { // k-ieme Add(tmp, dir[i-1], dir[i]); Scal(tmp, RSEG, tmp); Add(PosKey[k], PosKey[k-1], tmp); Affect(PosKeyDir[k], dir[i]); PosKeyTime[k] = PosKeyTime[k-1] + (double) M_PI_2 * RSEG / SPEED; k++; // k-ieme (+1) Scal(tmp, LSEG, dir[i]); Add(PosKey[k], PosKey[k-1], tmp); Affect(PosKeyDir[k], dir[i]); PosKeyTime[k] = PosKeyTime[k-1] + (double) LSEG / SPEED; k++; } nPosKey = k-1; LastPosKey = 0; NextPosKey = 1; //////////////////////////////////////////////// // Rotation KeyFrames, fonction des conditions //////////////////////////////////////////////// if(condition == 1) { // 1st Affect(RotKeyDir[0], dir[1]); RotKeyUp[0][0] = RotKeyUp[0][2] = 0; RotKeyUp[0][1] = 1; RotKeyTime[0] = PosKeyTime[0]; for(k=1, i=1 ; i<nseg ; ) { // k-ieme Affect(RotKeyDir[k], dir[i]); Affect(RotKeyUp[k], RotKeyUp[k-1]); // Meme que précédement RotKeyTime[k] = PosKeyTime[k] - (double) ANTICIPATION/SPEED; k++; i++; // k-ieme +1 Affect(RotKeyDir[k], dir[i]); Cross(tmp, RotKeyDir[k-1], RotKeyDir[k]); if(CompareAbs(tmp, RotKeyUp[k-1])) // Si rotation autour de RotKeyUp Affect(RotKeyUp[k], RotKeyUp[k-1]); else // Sinon applique la rotation à RotKeyUp Cross(RotKeyUp[k], tmp, RotKeyUp[k-1]); RotKeyTime[k] = PosKeyTime[k]; k++; } // dernier Affect(RotKeyDir[k], dir[i]); Affect(RotKeyUp[k], RotKeyUp[k-1]); // Meme que précédement RotKeyTime[k] = PosKeyTime[k]; nRotKey = k; LastRotKey = 0; NextRotKey = 1; } else if(condition == 2) { // 1st Affect(RotKeyDir[0], dir[1]); RotKeyUp[0][0] = RotKeyUp[0][2] = 0; RotKeyUp[0][1] = 1; RotKeyTime[0] = PosKeyTime[0]; for(k=1, i=1 ; i<nseg ; ) { // k-ieme Affect(RotKeyDir[k], dir[i]); Affect(RotKeyUp[k], RotKeyUp[k-1]); // Meme que précédement RotKeyTime[k] = PosKeyTime[k] - (double) ANTICIPATION/SPEED; k++; i++; // k-ieme +1 Affect(RotKeyDir[k], dir[i]); Cross(tmp, RotKeyDir[k-1], RotKeyDir[k]); if(CompareAbs(tmp, RotKeyUp[k-1])) // Si rotation autour de RotKeyUp Affect(RotKeyUp[k], RotKeyUp[0]); else // Sinon applique la rotation à RotKeyUp Cross(RotKeyUp[k], tmp, RotKeyUp[k-1]); RotKeyTime[k] = PosKeyTime[k]; k++; } // dernier Affect(RotKeyDir[k], dir[i]); Affect(RotKeyUp[k], RotKeyUp[k-1]); // Meme que précédement RotKeyTime[k] = PosKeyTime[k]; nRotKey = k; LastRotKey = 0; NextRotKey = 1; } else if(condition == 3) { // 1st Affect(RotKeyDir[0], dir[1]); RotKeyUp[0][0] = RotKeyUp[0][2] = 0; RotKeyUp[0][1] = 1; RotKeyTime[0] = PosKeyTime[0]; for(k=1, i=1 ; i<nseg ; ) { // k-ieme Affect(RotKeyDir[k], RotKeyDir[k-1]); Affect(RotKeyUp[k], RotKeyUp[0]); // Meme que précédement RotKeyTime[k] = PosKeyTime[k] - (double) ANTICIPATION/SPEED; k++; i++; // k-ieme +1 if(dir[i][1] == 1 || dir[i][1] == -1) // si segment vertical { if(i+1 <= nseg) Affect(RotKeyDir[k], dir[i+1]); else Affect(RotKeyDir[k], RotKeyDir[k-1]); } else Affect(RotKeyDir[k], dir[i]); Affect(RotKeyUp[k], RotKeyUp[0]); RotKeyTime[k] = PosKeyTime[k]; k++; } // dernier if(dir[i][1] == 1 || dir[i][1] == -1) // si segment vertical Affect(RotKeyDir[k], RotKeyDir[k-1]); else Affect(RotKeyDir[k], dir[i]); Affect(RotKeyUp[k], RotKeyUp[0]); // Meme que précédement RotKeyTime[k] = PosKeyTime[k]; nRotKey = k; LastRotKey = 0; NextRotKey = 1; } } #endif ///////////////////////// // Couloir's definition ///////////////////////// #if 0 void __fastcall Tunnel::MakeCouloir( GLuint listNb, char *nom ) { short i; GLfloat prod[3]; GLfloat T, dT; GLfloat dir[10][3]; short nseg = strlen(nom)/2; // MakeDir(nom, nseg, dir); T = 0; dT = (GLfloat) (TREP / (LSEG + (1.0 - 1.0/nseg) * PI * RSEG )); /////////////////////// // Couloir's list /////////////////////// glNewList(listNb, GL_COMPILE); // Cylindre 1 MakeCylinder(&T, dT); glTranslatef(0, 0, -LSEG); for(i=2 ; i<=nseg ; i++) { // Rotation initiale pour s'aligner avec la definition de la jonction Cross(prod, dir[i-2], dir[i]); if(Compare(prod, Vnul)) { if(Compare(dir[i-2], dir[i])) glRotatef(180, 0, 0, 1); } else { if(Compare(prod, dir[i-1])) glRotatef(90, 0, 0, 1); else glRotatef(-90, 0, 0, 1); } // Jonction i MakeJunction(&T, dT); // Translation & rotation glTranslatef(0, RSEG, -RSEG); // remise en position glRotatef(90, 1, 0, 0); // rotation d'axe x // Cylindre i+1 MakeCylinder(&T, dT); // Translation glTranslatef(0, 0, -LSEG); } glEndList(); } #endif
[ "psyphy@comcast.net" ]
psyphy@comcast.net
b308ff72b939d26f5a77750d5783939dd423d4e4
6bac07ceda232029b6a9ea0144ad261311348699
/plugin_sa/game_sa/CDamageAtomicModelInfo.h
5c2a00d30dab0320b2705f5f1c1c551f88f0ec0f
[ "Zlib" ]
permissive
DK22Pac/plugin-sdk
ced6dc734846f33113e3596045b58febb7eb083c
b0ebc6e4f44c2d5f768b36c6a7a2a688e7e2b9d3
refs/heads/master
2023-08-17T06:36:25.363361
2023-08-10T05:19:16
2023-08-10T05:19:20
17,803,683
445
221
Zlib
2023-08-13T04:34:28
2014-03-16T16:40:08
C++
UTF-8
C++
false
false
465
h
/* Plugin-SDK (Grand Theft Auto San Andreas) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #pragma once #include "PluginBase.h" #include "CAtomicModelInfo.h" class CDamageAtomicModelInfo : public CAtomicModelInfo { public: RpAtomic* m_pDamagedAtomic; static bool& ms_bCreateDamagedVersion; }; VALIDATE_SIZE(CDamageAtomicModelInfo, 0x24);
[ "gennariarmando@outlook.com" ]
gennariarmando@outlook.com
cbe6c2f853c96fc58e64b44c7e1fae6b0be5d5e6
6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849
/sstd_boost/sstd/boost/pending/disjoint_sets.hpp
d2fdf7bdde07be793403897419db6d2597f276f1
[ "BSL-1.0" ]
permissive
KqSMea8/sstd_library
9e4e622e1b01bed5de7322c2682539400d13dd58
0fcb815f50d538517e70a788914da7fbbe786ce1
refs/heads/master
2020-05-03T21:07:01.650034
2019-04-01T00:10:47
2019-04-01T00:10:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,585
hpp
// //======================================================================= // Copyright 1997, 1998, 1999, 2000 University of Notre Dame. // Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek // // 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) //======================================================================= // #ifndef BOOST_DISJOINT_SETS_HPP #define BOOST_DISJOINT_SETS_HPP #include <vector> #include <sstd/boost/graph/properties.hpp> #include <sstd/boost/pending/detail/disjoint_sets.hpp> namespace boost { struct find_with_path_halving { template <class ParentPA, class Vertex> Vertex operator()(ParentPA p, Vertex v) { return detail::find_representative_with_path_halving(p, v); } }; struct find_with_full_path_compression { template <class ParentPA, class Vertex> Vertex operator()(ParentPA p, Vertex v){ return detail::find_representative_with_full_compression(p, v); } }; // This is a generalized functor to provide disjoint sets operations // with "union by rank" and "path compression". A disjoint-set data // structure maintains a collection S={S1, S2, ..., Sk} of disjoint // sets. Each set is identified by a representative, which is some // member of of the set. Sets are represented by rooted trees. Two // heuristics: "union by rank" and "path compression" are used to // speed up the operations. // Disjoint Set requires two vertex properties for internal use. A // RankPA and a ParentPA. The RankPA must map Vertex to some Integral type // (preferably the size_type associated with Vertex). The ParentPA // must map Vertex to Vertex. template <class RankPA, class ParentPA, class FindCompress = find_with_full_path_compression > class disjoint_sets { typedef disjoint_sets self; inline disjoint_sets() {} public: inline disjoint_sets(RankPA r, ParentPA p) : rank(r), parent(p) {} inline disjoint_sets(const self& c) : rank(c.rank), parent(c.parent) {} // Make Set -- Create a singleton set containing vertex x template <class Element> inline void make_set(Element x) { put(parent, x, x); typedef typename property_traits<RankPA>::value_type R; put(rank, x, R()); } // Link - union the two sets represented by vertex x and y template <class Element> inline void link(Element x, Element y) { detail::link_sets(parent, rank, x, y, rep); } // Union-Set - union the two sets containing vertex x and y template <class Element> inline void union_set(Element x, Element y) { link(find_set(x), find_set(y)); } // Find-Set - returns the Element representative of the set // containing Element x and applies path compression. template <class Element> inline Element find_set(Element x) { return rep(parent, x); } template <class ElementIterator> inline std::size_t count_sets(ElementIterator first, ElementIterator last) { std::size_t count = 0; for ( ; first != last; ++first) if (get(parent, *first) == *first) ++count; return count; } template <class ElementIterator> inline void normalize_sets(ElementIterator first, ElementIterator last) { for (; first != last; ++first) detail::normalize_node(parent, *first); } template <class ElementIterator> inline void compress_sets(ElementIterator first, ElementIterator last) { for (; first != last; ++first) detail::find_representative_with_full_compression(parent, *first); } protected: RankPA rank; ParentPA parent; FindCompress rep; }; template <class ID = identity_property_map, class InverseID = identity_property_map, class FindCompress = find_with_full_path_compression > class disjoint_sets_with_storage { typedef typename property_traits<ID>::value_type Index; typedef std::vector<Index> ParentContainer; typedef std::vector<unsigned char> RankContainer; public: typedef typename ParentContainer::size_type size_type; disjoint_sets_with_storage(size_type n = 0, ID id_ = ID(), InverseID inv = InverseID()) : id(id_), id_to_vertex(inv), rank(n, 0), parent(n) { for (Index i = 0; i < n; ++i) parent[i] = i; } // note this is not normally needed template <class Element> inline void make_set(Element x) { parent[x] = x; rank[x] = 0; } template <class Element> inline void link(Element x, Element y) { extend_sets(x,y); detail::link_sets(&parent[0], &rank[0], get(id,x), get(id,y), rep); } template <class Element> inline void union_set(Element x, Element y) { Element rx = find_set(x); Element ry = find_set(y); link(rx, ry); } template <class Element> inline Element find_set(Element x) { return id_to_vertex[rep(&parent[0], get(id,x))]; } template <class ElementIterator> inline std::size_t count_sets(ElementIterator first, ElementIterator last) { std::size_t count = 0; for ( ; first != last; ++first) if (parent[*first] == *first) ++count; return count; } template <class ElementIterator> inline void normalize_sets(ElementIterator first, ElementIterator last) { for (; first != last; ++first) detail::normalize_node(&parent[0], *first); } template <class ElementIterator> inline void compress_sets(ElementIterator first, ElementIterator last) { for (; first != last; ++first) detail::find_representative_with_full_compression(&parent[0], *first); } const ParentContainer& parents() { return parent; } protected: template <class Element> inline void extend_sets(Element x, Element y) { Index needed = get(id,x) > get(id,y) ? get(id,x) + 1 : get(id,y) + 1; if (needed > parent.size()) { rank.insert(rank.end(), needed - rank.size(), 0); for (Index k = parent.size(); k < needed; ++k) parent.push_back(k); } } ID id; InverseID id_to_vertex; RankContainer rank; ParentContainer parent; FindCompress rep; }; } // namespace boost #endif // BOOST_DISJOINT_SETS_HPP
[ "zhaixueqiang@hotmail.com" ]
zhaixueqiang@hotmail.com
f8c11f68747883a6042d06a7d4901b54e73976f1
7dedb11bd6620b14004d2fead3d0d47daf2b98bf
/CodeForces/cf-632c.cpp
e1d63fca2f38fbe977e7e8dc61fbfd35bf224812
[]
no_license
nickzuck/Competitive-Programming
2899d6601e2cfeac919276e437a77697ac9be922
5abb02a527dd4cc379bb48061f60501fc22da476
refs/heads/master
2021-01-15T09:19:34.607887
2016-06-01T20:38:45
2016-06-01T20:38:45
65,146,214
1
0
null
2016-08-07T17:44:47
2016-08-07T17:44:44
null
UTF-8
C++
false
false
1,260
cpp
#include <iostream> #include <cstdio> #include <string> #include <sstream> #include <vector> #include <list> #include <set> #include <map> #include <queue> #include <stack> #include <bitset> #include <numeric> #include <iterator> #include <algorithm> #include <cmath> #include <chrono> #include <cassert> using namespace std; using ll = long long; using ld = long double; using ii = pair<ll, ll>; using vi = vector<ll>; using vb = vector<bool>; using vvi = vector<vi>; using vii = vector<ii>; using vvii = vector<vii>; const int INF = 2000000000; const ll LLINF = 9000000000000000000; int main() { ios::sync_with_stdio(false); cin.tie(NULL); int N; cin >> N; vector<string> A(N, ""); vector<int> v; for (int i = 0; i < N; ++i) cin >> A[i], v.push_back(i); sort(v.begin(), v.end(), [&A, &N](int l, int r) { int sm = 0, al = A[l].size(), ar = A[r].size(); for (size_t i = 0; i < al + ar; ++i) if (A[i < al ? l : r][i < al ? i : i - al] == A[i < ar ? r : l][i < ar ? i : i - ar]) continue; else { sm = (A[i < al ? l : r][i < al ? i : i - al] < A[i < ar ? r : l][i < ar ? i : i - ar]) ? -1 : 1; break; } return (sm == -1); }); for (int i = 0; i < N; ++i) cout << A[v[i]]; cout << endl; return 0; }
[ "timonknigge@live.nl" ]
timonknigge@live.nl
1cd16ade021874faebdcd5d690a1b17877df222d
078b8a32aebdfc7bad3bcd182b87e48650b53fa9
/WarShooter/WarShooter/Shooter.h
c41a2d4fd66faa6e91ae7034d91884777f8d3b97
[]
no_license
puzatkin-ivan/sfml-war-shooter
dc347205ff9f97068f3102b6a498ea35db56a30e
53735f9cbb257ce070bf40180f35ab144dccf9b9
refs/heads/master
2021-09-01T05:36:54.099157
2017-11-09T07:04:25
2017-11-09T07:04:25
105,128,220
0
1
null
null
null
null
UTF-8
C++
false
false
795
h
#pragma once #include "sheet.h" #include "Assets.h" class Shooter { public: Shooter(CAssets & assets); void Draw(sf::RenderWindow & window); void Update(float dt, const KeyMap & keyMap); sf::Vector2f GetPosition() const; unsigned GetIp() const; sf::Vector2f GetSize() const; private: void UpdatePosition(float dt); void UpdatePositionX(float deltaMove); void UpdatePositionY(float deltaMove); void UpdateDirection(const KeyMap & keyMap); void UpdateDirectionX(bool isLeft, bool isRight); void UpdateDirectionY(bool isUp, bool isDown); void SetTexture(const sf::Texture & texture); unsigned m_ip = 10; CAssets m_assets; sf::Sprite m_body; sf::Vector2f m_position = INITIAL_POSITION; Direction m_directionX = Direction::None; Direction m_directionY = Direction::None; };
[ "puzatkin1998@gmail.com" ]
puzatkin1998@gmail.com
20c88d3cbdc510fd1abc7c01065289eaa12951f0
f2723b5c578548bbff10340c168c88b95d909515
/BinaryTreeLevelOrderTraversal2.cpp
42baaff99c9bcbe9ef54ed96d87a556ba1be2011
[]
no_license
fenganli/Leetcode
20718b4820f8ccb69d842e475add4c0edcf2797e
d66bf923636125c642aa800961be1609e843264a
refs/heads/master
2021-05-28T07:09:48.872845
2014-10-18T22:58:00
2014-10-18T22:58:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
819
cpp
class Solution { public: vector<vector<int> > levelOrderBottom(TreeNode * root) { if (root == NULL) { vector<vector<int> > vec; return vec; } queue<TreeNode *> queue; queue.push(root); queue.push(NULL); vector<vector<int> > returnVec; vector<int> vec; while (!queue.empty()) { TreeNode * node = queue.front(); queue.pop(); if (node == NULL) { returnVec.push_back(vec); if (!queue.empty()) queue.push(NULL); vec.clear(); } else { vec.push_back(node -> val); if (node -> left != NULL) queue.push(node -> left); if (node -> right != NULL) queue.push(node -> right); } } vector<vector<int> > retVec; int size = returnVec.size(); for (int i = size - 1; i >= 0; i--) retVec.push_back(returnVec[i]); return retVec; } };
[ "leo.pku.cs@gmail.com" ]
leo.pku.cs@gmail.com