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
97ab97cfaabef22394492759ea90f78bf982f165
84d99cf96e02161c25c6617af715b1789cd0fc65
/Seance4/E4fy/main.cpp
0a4de5d60abf2a26cf3001962a297a8616c3019e
[]
no_license
HunterKruger/learnCPP
f6e03926f060e903346c1a508907c4bfe2d7a1dd
e34aa7873fdabf048be1e59b3cc7b6c9f08a215d
refs/heads/master
2020-07-03T11:38:29.669362
2019-10-27T12:02:06
2019-10-27T12:02:06
201,893,425
0
0
null
null
null
null
UTF-8
C++
false
false
978
cpp
#include <iostream> #include "string.h" #include "compte.h" using namespace std; int main() { String str1("Bonjour"); str1.display();cout<<endl; String str2(str1); str2.display();cout<<endl; str1.toUpper(); cout<<str1.isEqual(str2)<<endl; str2.toUpper(); cout<<str1.isEqual(str2)<<endl; Compte *compte1=new Compte("aa",1200); compte1->display(); compte1->verse(800); compte1->display(); compte1->update(); compte1->display(); Compte compte2("bb",1000); compte2.display(); Compte::modifyTax(5.0); compte2.update(); compte2.display(); Compte *compte3=new Compte("cc",600); compte3->display(); Compte compte4("dd",26); compte4.display(); Compte *compte5=new Compte("ee"); compte5->display(); Compte::modifyTax(10.0); Compte::updateAll(); Compte::displayAll(); delete compte1; delete compte5; delete compte3; Compte::displayAll(); return 0; }
[ "793264282@qq.com" ]
793264282@qq.com
a7df99260f301c8f5fb0497398e65c7aa4e33917
7e327b39be61b1d2494227a6e936a12bedc15b70
/1292 - Laser Shot.cpp
4c3601938152ef19b65c7a6d3bb20a4a8aad1782
[]
no_license
abinashkg/LightOJ
6f237581c77ce0139668ffc547bade9398c9c12d
5f03096ba5c64ebe7b6bdb9572a3a2844718fa60
refs/heads/master
2020-12-24T11:46:26.006012
2016-11-06T19:26:37
2016-11-06T19:26:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,554
cpp
//Abinash Ghosh(Om) #include <cstdio> #include <cstdlib> #include <cctype> #include <cmath> #include <cstring> #include <climits> #include <iostream> #include <iomanip> #include <vector> #include <list> #include <stack> #include <queue> #include <map> #include <set> #include <string> #include <utility> #include <sstream> #include <algorithm> using namespace std; #define PI acos(-1.0) #define MAX 10000007 #define EPS 1e-9 #define mem(a,b) memset(a,b,sizeof(a)) #define gcd(a,b) __gcd(a,b) #define pb push_back #define mp make_pair #define x first #define y second #define Sort(x) sort(x.begin(),x.end()) #define FOR(i, b, e) for(int i = b; i <= e; i++) #define pr(x) cout<<x<<"\n" #define pr2(x,y) cout<<x<<" "<<y<<"\n" #define READ(f) freopen(f, "r", stdin) #define WRITE(f) freopen(f, "w", stdout) typedef long long ll; typedef pair <int, int> pii; typedef pair <double , double> pdd; typedef pair <ll , ll > pll; typedef vector <int> vi; typedef vector <pii> vpii; typedef vector <ll > vl; //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 const int NN = 705; int cases, caseno, n; pair <int, int> P[NN], Q[NN]; int main() { scanf("%d", &cases); while( cases-- ) { scanf("%d", &n); for( int i = 0; i < n; i++ ) scanf("%d %d", &P[i].first, &P[i].second); int res = 0; for( int i = 0; i < n; i++ ) { int k = 0; for( int j = i + 1; j < n; j++ ) { Q[k].first = P[j].first - P[i].first; Q[k].second = P[j].second - P[i].second; int d = __gcd( abs(Q[k].first), abs(Q[k].second) ); Q[k].first /= d; Q[k].second /= d; if( Q[k].first < 0 ) { Q[k].first *= -1; Q[k].second *= -1; } if( Q[k].first == 0 && Q[k].second < 0 ) Q[k].second *= -1; k++; } int mx = 0; sort( Q, Q + k ); for( int x = 0, y; x < k; x++ ) { for( y = x; y < k; y++ ) if( Q[x] != Q[y] ) break; mx = max( mx, y - x ); x = y - 1; } res = max( res, mx + 1 ); } printf("Case %d: %d\n", ++caseno, res); } return 0; }
[ "noreply@github.com" ]
noreply@github.com
391ccc2b1437724f4666368690a1565f69a6b967
6adaf5286b0d72fa4f0df4aa9abddccc4cdfd1c1
/customtower/customtower/code/game/battle/character/characterParameter.h
880ec61443cc3754ac14d36167d692e0d2c3e5c4
[ "MIT" ]
permissive
myumoon/customtower
34b00212b7b3308b0b86b90ae04e94a7b87ac1af
85980f5aea1f8b869069ed1da3a14491e2dc8968
refs/heads/master
2021-01-25T05:09:58.140180
2017-06-06T13:02:43
2017-06-06T13:02:43
93,515,235
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,564
h
//============================================================================= /*! @file characterParameter.h @brief パラメーター設定 @author ryunosuke ide @date 2013.07.06 */ //============================================================================= #ifndef __CHARACTER_PARAMETER_H__ #define __CHARACTER_PARAMETER_H__ #include <vector> namespace game { namespace battle { //============================================================================= /*! パラメーター */ //============================================================================= struct CharacterParameter { //! パーツ enum PARTS { PARTS_NONE, //!< 無し PARTS_MAX, //!< パーツ数 }; //! パーツ struct PartsParam { static const u32 CHILDREN_SIZE = 32; PARTS type; PartsParam* children[CHILDREN_SIZE]; //! コンストラクタ PartsParam( void ) { for( u32 i = 0; i < CHILDREN_SIZE; ++i ) { children[i] = NULL; } } //! デストラクタ ~PartsParam( void ) { for( u32 i = 0; i < CHILDREN_SIZE; ++i ) { nk::SafeDelete( children[i] ); } } //! 追加 void AppendParts( PARTS type ) { for( u32 i = 0; i < CHILDREN_SIZE; ++i ) { if( children[i] == NULL ) { children[i] = new PartsParam(); children[i]->type = type; } } } }; //-------------コンストラクタ・デストラクタ-------------- CharacterParameter() { } virtual~CharacterParameter() { } }; } // namespace battle } // namespace game #endif // __CHARACTER_PARAMETER_H__
[ "ryumyu0120@gmail.com" ]
ryumyu0120@gmail.com
ee1b77a89d6d6615910ffb5013df62a7c02d3a07
22b87f3243e58fbb6ed4661909d8544c7c255a56
/utils.hpp
c4196cca04bda5aac6853a63a42c8a045dba0ea5
[ "Apache-2.0" ]
permissive
TheHolyJoker/Pocket-Dictionaries-Benchmarks
57297e7ecb02404f0f0ab406732688c8fa322235
f651d1082c277e539964e831a526e9404c623a44
refs/heads/master
2022-12-18T14:57:43.928812
2020-09-20T16:29:52
2020-09-20T16:29:52
294,442,063
0
0
null
null
null
null
UTF-8
C++
false
false
573
hpp
#ifndef BENCH_UTILS_HPP #define BENCH_UTILS_HPP #include <functional> #include <iostream> #include <set> #include <vector> // #include "pd320.hpp" #include "pd512.hpp" #include <chrono> using ns = std::chrono::nanoseconds; // typedef chrono::nanoseconds ns; void set_pd(__m512i *pd, size_t quot_range, size_t capacity); __attribute__((always_inline)) inline uint16_t reduce16(uint16_t hash, uint16_t n) { // http://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/ return (uint16_t)(((uint32_t) hash * n) >> 16); } #endif//BENCH_UTILS_HPP
[ "tomereven@mail.tau.ac.il" ]
tomereven@mail.tau.ac.il
3aa8b70ca6c6ff13874906e7a58a4eeef085474e
6acaf6553d71582f3807ad89cc5927070b70569f
/src/player/AssemblyAIPlayer/core.h
06b50994d84e76f6b673f666f287bbf50eae57a4
[ "BSD-3-Clause" ]
permissive
Top-Ranger/android-reversi
581f90650c6ba64a6cc6afa8ecdf4e308ecdde04
c56a948f6b0f749d172f54a61882366326cdc5be
refs/heads/master
2021-01-17T13:52:58.675781
2016-06-19T16:53:36
2016-06-19T16:53:36
21,957,215
0
0
null
null
null
null
UTF-8
C++
false
false
2,676
h
/* Copyright (C) 2014,2016 Marcus Soll All rights reserved. You may use this file under the terms of BSD license as follows: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Jolla Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CORE_H #define CORE_H #include "../../core/gameboard.h" #include <QString> class Core { public: Core(); virtual ~Core(); virtual bool retirement(Gameboard board, int player) = 0; virtual int mistrust(float const* const* const vote, Gameboard board, int player) = 0; virtual void propose(float ** const vote, Gameboard board, int player) = 0; virtual void correct(float ** const vote, Gameboard board, int player) = 0; virtual QString name() const = 0; protected: static constexpr float _factorSmall = 1.1; static constexpr float _factorLarge = 1.2; static const int _mistrustSmall = 1; static const int _mistrustLarge = 3; static const int _mistrustEmergency = 100; static const int _noMistrust = 0; }; // Two cores are the same if they have the same name. As there should only be one core of every type in AssemblyAIPlayer, this is a easy and cheap way of comparing cores. inline bool operator==(const Core& core1, const Core& core2) {return core1.name() == core2.name();} #endif // CORE_H
[ "Superschlumpf@web.de" ]
Superschlumpf@web.de
78a357ba0cf09f01218990d987e939defb9e3442
fd9f5186fa5d19db077dbf302fe9c940cb42e82f
/src/meta/processors/job/StorageJobExecutor.cpp
1d179fa4e8b15166ba7606fcde767d592530b215
[ "Apache-2.0" ]
permissive
vesoft-inc/nebula
a0b9af548e124e59ecbfb0c5152098a1020b621c
7c32088dec1891870a24aaa37ee5818e69f5ad6d
refs/heads/master
2023-08-17T00:00:29.022525
2023-08-16T04:02:03
2023-08-16T04:02:03
146,459,443
11,007
1,220
Apache-2.0
2023-09-05T05:48:16
2018-08-28T14:25:09
C++
UTF-8
C++
false
false
9,417
cpp
/* Copyright (c) 2019 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License. */ #include "meta/processors/job/StorageJobExecutor.h" #include "common/network/NetworkUtils.h" #include "common/utils/MetaKeyUtils.h" #include "common/utils/Utils.h" #include "interface/gen-cpp2/common_types.h" #include "meta/ActiveHostsMan.h" #include "meta/processors/Common.h" #include "meta/processors/admin/AdminClient.h" #include "meta/processors/job/BalanceJobExecutor.h" #include "meta/processors/job/CompactJobExecutor.h" #include "meta/processors/job/FlushJobExecutor.h" #include "meta/processors/job/RebuildEdgeJobExecutor.h" #include "meta/processors/job/RebuildFTJobExecutor.h" #include "meta/processors/job/RebuildTagJobExecutor.h" #include "meta/processors/job/StatsJobExecutor.h" #include "meta/processors/job/TaskDescription.h" DECLARE_int32(heartbeat_interval_secs); DECLARE_uint32(expired_time_factor); namespace nebula { namespace meta { ErrOrHosts StorageJobExecutor::getTargetHost(GraphSpaceID spaceId) { std::unique_ptr<kvstore::KVIterator> iter; const auto& partPrefix = MetaKeyUtils::partPrefix(spaceId); auto retCode = kvstore_->prefix(kDefaultSpaceId, kDefaultPartId, partPrefix, &iter); if (retCode != nebula::cpp2::ErrorCode::SUCCEEDED) { LOG(INFO) << "Fetch Parts Failed, error: " << apache::thrift::util::enumNameSafe(retCode); return retCode; } // use vector instead of set because this can convenient for next step std::unordered_map<HostAddr, std::vector<PartitionID>> hostAndPart; std::vector<std::pair<HostAddr, std::vector<PartitionID>>> hosts; while (iter->valid()) { auto part = MetaKeyUtils::parsePartKeyPartId(iter->key()); auto targets = MetaKeyUtils::parsePartVal(iter->val()); for (auto& target : targets) { hostAndPart[target].emplace_back(part); } iter->next(); } for (auto it = hostAndPart.begin(); it != hostAndPart.end(); it++) { hosts.emplace_back(std::pair(it->first, it->second)); } return hosts; } ErrOrHosts StorageJobExecutor::getLeaderHost(GraphSpaceID space) { const auto& hostPrefix = MetaKeyUtils::leaderPrefix(space); std::unique_ptr<kvstore::KVIterator> leaderIter; auto retCode = kvstore_->prefix(kDefaultSpaceId, kDefaultPartId, hostPrefix, &leaderIter); if (retCode != nebula::cpp2::ErrorCode::SUCCEEDED) { LOG(INFO) << "Get space " << space << "'s part failed, error: " << apache::thrift::util::enumNameSafe(retCode); return retCode; } std::vector<std::pair<HostAddr, std::vector<PartitionID>>> hosts; HostAddr host; nebula::cpp2::ErrorCode code; for (; leaderIter->valid(); leaderIter->next()) { auto spaceAndPart = MetaKeyUtils::parseLeaderKeyV3(leaderIter->key()); auto partId = spaceAndPart.second; std::tie(host, std::ignore, code) = MetaKeyUtils::parseLeaderValV3(leaderIter->val()); if (code != nebula::cpp2::ErrorCode::SUCCEEDED) { continue; } auto it = std::find_if(hosts.begin(), hosts.end(), [&](auto& item) { return item.first == host; }); if (it == hosts.end()) { hosts.emplace_back(std::make_pair(host, std::vector<PartitionID>{partId})); } else { it->second.emplace_back(partId); } } // If storage has not report leader distribution to meta and we don't report error here, // JobMananger will think of the job consists of 0 task, and the task will not send to any // storage. And the job will always be RUNNING. if (hosts.empty()) { return nebula::cpp2::ErrorCode::E_JOB_HAS_NO_TARGET_STORAGE; } return hosts; } ErrOrHosts StorageJobExecutor::getListenerHost(GraphSpaceID space, cpp2::ListenerType type) { const auto& prefix = MetaKeyUtils::listenerPrefix(space, type); std::unique_ptr<kvstore::KVIterator> iter; auto ret = kvstore_->prefix(kDefaultSpaceId, kDefaultPartId, prefix, &iter); if (ret != nebula::cpp2::ErrorCode::SUCCEEDED) { LOG(INFO) << "Get space " << space << "'s listener failed, error: " << apache::thrift::util::enumNameSafe(ret); return ret; } auto activeHostsRet = ActiveHostsMan::getActiveHosts(kvstore_, FLAGS_heartbeat_interval_secs * FLAGS_expired_time_factor, cpp2::HostRole::STORAGE_LISTENER); if (!nebula::ok(activeHostsRet)) { return nebula::error(activeHostsRet); } auto activeHosts = std::move(nebula::value(activeHostsRet)); std::vector<std::pair<HostAddr, std::vector<PartitionID>>> hosts; while (iter->valid()) { auto host = MetaKeyUtils::deserializeHostAddr(iter->val()); auto part = MetaKeyUtils::parseListenerPart(iter->key()); if (std::find(activeHosts.begin(), activeHosts.end(), host) == activeHosts.end()) { LOG(INFO) << "Invalid host : " << network::NetworkUtils::toHostsStr({host}); return nebula::cpp2::ErrorCode::E_INVALID_HOST; } auto it = std::find_if( hosts.begin(), hosts.end(), [&host](auto& item) { return item.first == host; }); if (it == hosts.end()) { hosts.emplace_back(std::make_pair(host, std::vector<PartitionID>{part})); } else { it->second.emplace_back(part); } iter->next(); } if (hosts.empty()) { return nebula::cpp2::ErrorCode::E_LISTENER_NOT_FOUND; } return hosts; } folly::Future<nebula::cpp2::ErrorCode> StorageJobExecutor::execute() { ErrOrHosts addressesRet; isRunning_.store(true); switch (toHost_) { case TargetHosts::LEADER: { addressesRet = getLeaderHost(space_); break; } case TargetHosts::LISTENER: { addressesRet = getListenerHost(space_, cpp2::ListenerType::ELASTICSEARCH); break; } case TargetHosts::DEFAULT: { addressesRet = getTargetHost(space_); break; } } if (!nebula::ok(addressesRet)) { LOG(INFO) << "Can't get hosts"; return nebula::error(addressesRet); } std::vector<PartitionID> parts; auto addresses = nebula::value(addressesRet); // write all tasks first. std::vector<kvstore::KV> data; std::vector<TaskDescription> allTasks; for (auto i = 0U; i != addresses.size(); ++i) { TaskDescription task(space_, jobId_, i, addresses[i].first); auto taskKey = MetaKeyUtils::taskKey(task.getSpace(), task.getJobId(), task.getTaskId()); auto taskVal = MetaKeyUtils::taskVal(task.getHost(), task.getStatus(), task.getStartTime(), task.getStopTime(), task.getErrorCode()); allTasks.emplace_back(std::move(task)); data.emplace_back(std::move(taskKey), std::move(taskVal)); } folly::Baton<true, std::atomic> baton; auto rc = nebula::cpp2::ErrorCode::SUCCEEDED; kvstore_->asyncMultiPut( kDefaultSpaceId, kDefaultPartId, std::move(data), [&](nebula::cpp2::ErrorCode code) { rc = code; baton.post(); }); baton.wait(); if (rc != nebula::cpp2::ErrorCode::SUCCEEDED) { LOG(INFO) << "write to kv store failed, error: " << apache::thrift::util::enumNameSafe(rc); return rc; } std::vector<folly::SemiFuture<Status>> futures; futures.reserve(addresses.size()); for (auto& address : addresses) { // Will convert StorageAddr to AdminAddr in AdminClient futures.emplace_back(executeInternal(std::move(address.first), std::move(address.second))); } auto tries = folly::collectAll(std::move(futures)).get(); std::vector<TaskDescription> failedTasks; for (size_t i = 0; i < tries.size(); i++) { auto getFaildTask = [&](size_t taskId, nebula::cpp2::ErrorCode ec) { auto task = allTasks[taskId]; task.setStatus(cpp2::JobStatus::FAILED); task.setErrorCode(ec); return task; }; // taks id have the same index with address and futures. if (tries[i].hasException()) { LOG(INFO) << tries[i].exception().what(); rc = nebula::cpp2::ErrorCode::E_RPC_FAILURE; failedTasks.emplace_back(getFaildTask(i, rc)); continue; } if (!tries[i].value().ok()) { LOG(INFO) << tries[i].value().toString(); rc = nebula::cpp2::ErrorCode::E_RPC_FAILURE; failedTasks.emplace_back(getFaildTask(i, rc)); continue; } } if (!failedTasks.empty()) { // write all tasks first. std::vector<kvstore::KV> faildKV; for (auto task : failedTasks) { auto taskKey = MetaKeyUtils::taskKey(task.getSpace(), task.getJobId(), task.getTaskId()); auto taskVal = MetaKeyUtils::taskVal(task.getHost(), task.getStatus(), task.getStartTime(), task.getStopTime(), task.getErrorCode()); faildKV.emplace_back(std::move(taskKey), std::move(taskVal)); } baton.reset(); kvstore_->asyncMultiPut( kDefaultSpaceId, kDefaultPartId, std::move(faildKV), [&](nebula::cpp2::ErrorCode code) { if (code != nebula::cpp2::ErrorCode::SUCCEEDED) { LOG(INFO) << "Some task is failed, but failed to set task status due to kv error:" << apache::thrift::util::enumNameSafe(code); } baton.post(); }); baton.wait(); } return rc; } } // namespace meta } // namespace nebula
[ "noreply@github.com" ]
noreply@github.com
e6ebf108789c9e0b966fcb248e93768bc9dde286
3475c2efae2cdb0ce452bc16dd7809e086cc2ec3
/potd-q25/Queue.cpp
a176ac2c69965629af11abc2450997b293a913ea
[]
no_license
QianhaoIan/cs225_potd
72903a60a33e8988036429d1f498b0f17bb3903a
f0650ef8041eac3bdcc5288ec012cc2770f22c9d
refs/heads/master
2020-08-27T13:26:27.982351
2019-11-19T20:13:53
2019-11-19T20:13:53
217,387,455
0
0
null
null
null
null
UTF-8
C++
false
false
1,658
cpp
#include "Queue.h" #include <iostream> using namespace std; // Queue::Queue(){} Queue::~Queue() { Node* temp = head_; while(head_ != NULL){ temp = head_; head_ = head_->next; delete temp; } } // `int size()` - returns the number of elements in the stack (0 if empty) int Queue::size() const { int count = 0; Node* cur_node = head_; while(cur_node != NULL){ cur_node = cur_node->next; count++; } return count; } // `bool isEmpty()` - returns if the list has no elements, else false bool Queue::isEmpty() const { if (head_ == NULL) return true; else return false; } // `void enqueue(int val)` - enqueue an item to the queue in O(1) time void Queue::enqueue(int value) { Node* new_node = new Node(); if (head_ == NULL) { head_ = new_node; tail_ = new_node; new_node->prev = NULL; new_node->next = NULL; new_node->elem = value; return; } new_node->next = NULL; new_node->prev = tail_; new_node->elem = value; tail_->next = new_node; tail_ = new_node; } // `int dequeue()` - removes an item off the queue and returns the value in O(1) time int Queue::dequeue() { // if (head_ == NULL) return -1; // if (head_ == tail_) tail_ = NULL; // int value = head_->elem; // Node* temp = head_; // if (head_->next != NULL) head_->next->prev = NULL; // head_ = head_->next; // delete temp; // return value; int value = 0; Node* temp = head_; if (head_ == NULL) return -1; if (head_ == tail_){ value = head_->elem; head_ = NULL; tail_ = NULL; delete temp; return value; } value = head_->elem; head_ = head_->next; delete head_->prev; head_->prev = NULL; // delete temp; return value; }
[ "ww6652890@gmail.com" ]
ww6652890@gmail.com
082ce942a0d6e3be078ce848cd334944bfc68924
59ab06a7204cbea2122d87b88cab4090e73b9afb
/WallFollowHeadingTest1/WallFollowHeadingTest1.ino
e66eab458f229f81476c043e538f0ae1f1b3a670
[]
no_license
masterford/AutonomousRobots
f585e06394cfc9c0cd5ba395883cf9d8977c6dd4
70398884cec4f12c7c52bd2d6ef6eb61a0e715cd
refs/heads/master
2020-08-30T14:10:58.163655
2019-11-07T15:16:43
2019-11-07T15:16:43
218,405,058
1
0
null
null
null
null
UTF-8
C++
false
false
11,163
ino
// WallFollowHeadingTest1.ino // BDK:ESE421:2019C // Motor PWM control // Using SN754410 Dual H-Bridge // Servo steering // 3 Ping Sensors // IMU // #include <Servo.h> #include <SPI.h> #include <Adafruit_LSM9DS1.h> #include <Adafruit_Sensor.h> // // all of the pins are defined here // #define SERVOPIN 7 #define SERVOPOT A7 #define SERVOSCALEUS 10 #define SERVOMAXUS 400 #define FORWARDPIN 8 // HIGH for FWD; LOW for REV #define REVERSEPIN 9 // LOW for FWD; HIGH for REV #define LEFTMOTORPIN 10 // Left Motor Speed Control #define RIGHTMOTORPIN 11 // Right Motor Speed Control #define MOTORPOT A8 #define SETUP 0 // do initial setup stuff #define ADJUST 1 // adjust the settings #define NOOP 2 // do nothing; return latest status #define NORMAL 3 // do usual task #define LEFT 0 #define CENTER 1 #define RIGHT 2 #define PINGDMAX 100 #define PINGDADJUST 50 #define PINGDMIN 2 #define PINGTRIGPINS {23, 22, 6} // ping sensor trigger pin (output from Arduino) #define PINGECHOPINS {25, 24, 5} // ping sensor echo pin (input to Arduino) #define PINGEGRNDPINS {27, 26, 4} // ping sensor ground pin (use digital pin as ground) #define WALLDISTCMD 30.0 #define WALLDISTLOST 60.0 #define STEERMAXDEG 25.0 #define KPSI 2.0 #define KY 0.5 #define CMDPSIMAX 10.0 #define OMGPSI 0.25 // // IMU uses SPI -- here are the pins on the Mega // (Pins 49 & 47 are user selection) // #define LSM9DS1_SCK 52 //BDK-mega #define LSM9DS1_MISO 50 //BDK-mega #define LSM9DS1_MOSI 51 //BDK-mega #define LSM9DS1_XGCS 49 //BDK-mega #define LSM9DS1_MCS 47 //BDK-mega #define AX 0 #define AY 1 #define AZ 2 #define OMEGAX 3 #define OMEGAY 4 #define OMEGAZ 5 #define AZBIAS 6 void setup() { Serial.begin(115200); // for sending info to the terminal Serial.println("WallFollowHeadingTest1"); getPingDistance(LEFT,SETUP); getPingDistance(CENTER,SETUP); getPingDistance(RIGHT,SETUP); setServoAngle(0.0,SETUP); setMotorCommand(0.0,SETUP); getIMU(OMEGAZ,SETUP); Serial.println("Setup Complete."); } ////////////////////////////////////////////////////////////////// void loop() { ////////////////////////////////////////////////////////////////// // put all static variables at the top // static double hatPsiDEG = 0.0; static double microsLast = micros(); double dTus = micros() - microsLast; microsLast = micros(); ////////////////////////////////////////////////////////////////// // go into adjustment mode whenever we encounter a forward obstacle // if (getPingDistance(CENTER,NORMAL) < PINGDADJUST) { Serial.println("ADJUST"); setMotorCommand(0.0,ADJUST); setServoAngle(0.0,ADJUST); getIMU(OMEGAZ,ADJUST); Serial.println(); delay(50); microsLast = micros(); hatPsiDEG = 0.0; // reset heading when holding return; } ////////////////////////////////////////////////////////////////// // drive at nominal speed // setMotorCommand(50.0,NORMAL); ////////////////////////////////////////////////////////////////// // update heading estimate with integral of yaw rate // double rateYawDPS = getIMU(OMEGAZ,NORMAL); hatPsiDEG += -rateYawDPS * 0.000001 * dTus; ////////////////////////////////////////////////////////////////// // steer to fixed distance from right wall when visible // otherwise hold heading at zero // double rightWallDistCM = getPingDistance(RIGHT,NORMAL); double cmdPsiDEG = 0.0; if (rightWallDistCM < WALLDISTLOST) { cmdPsiDEG = constrain(KY*(rightWallDistCM - WALLDISTCMD),-CMDPSIMAX,CMDPSIMAX); // // assume feedback is working and push estimated heading toward zero // hatPsiDEG += OMGPSI*(0.0 - hatPsiDEG) * 0.000001 * dTus; } double steeringDeg = constrain(KPSI*(cmdPsiDEG - hatPsiDEG),-STEERMAXDEG,STEERMAXDEG); setServoAngle(steeringDeg,NORMAL); Serial.println(steeringDeg); } //////////////////////////////////////////////////////////// // IMU Sensor -- read accel [m/s^2] and angular velocity [dps] //////////////////////////////////////////////////////////// double getIMU(byte signalFlag, byte actionFlag) { static Adafruit_LSM9DS1 myIMU; static double dataIMU[] = {0, 0, 0, 0, 0, 0, 10.0}; static double biasIMU[] = {0, 0, 10.0, 0, 0, 0, 0}; if (actionFlag == NOOP) { // do nothing--return requested value return dataIMU[signalFlag]-biasIMU[signalFlag]; } else if (actionFlag == SETUP) { // setup = connect pins & set ranges myIMU = Adafruit_LSM9DS1(LSM9DS1_XGCS, LSM9DS1_MCS); delay(1000); if (!myIMU.begin()) { Serial.println("IMU Setup Failure..."); while (1); } else { Serial.println("IMU Setup Complete"); } myIMU.setupAccel(myIMU.LSM9DS1_ACCELRANGE_2G); myIMU.setupMag(myIMU.LSM9DS1_MAGGAIN_4GAUSS); myIMU.setupGyro(myIMU.LSM9DS1_GYROSCALE_245DPS); } else if (actionFlag == ADJUST) { // update biases myIMU.read(); /* ask it to read in the data */ sensors_event_t a, m, g, temp; myIMU.getEvent(&a, &m, &g, &temp); const double bandwidthLP = 0.05; Serial.print(" IMU BIAS: "); biasIMU[AX] += bandwidthLP*(a.acceleration.x-biasIMU[AX]); Serial.print(biasIMU[AX]); biasIMU[AY] += bandwidthLP*(a.acceleration.y-biasIMU[AY]); Serial.print(" "); Serial.print(biasIMU[AY]); biasIMU[AZ] += bandwidthLP*(a.acceleration.z-biasIMU[AZ]); Serial.print(" "); Serial.print(biasIMU[AZ]); biasIMU[OMEGAX] += bandwidthLP*(g.gyro.x-biasIMU[OMEGAX]); Serial.print(" "); Serial.print(biasIMU[OMEGAX]); biasIMU[OMEGAY] += bandwidthLP*(g.gyro.y-biasIMU[OMEGAY]); Serial.print(" "); Serial.print(biasIMU[OMEGAY]); biasIMU[OMEGAZ] += bandwidthLP*(g.gyro.z-biasIMU[OMEGAZ]); Serial.print(" "); Serial.print(biasIMU[OMEGAZ]); biasIMU[AZBIAS] = 0.0; } else if (actionFlag == NORMAL) { // normal = new reading & return chosen signal } myIMU.read(); /* ask it to read in the data */ sensors_event_t a, m, g, temp; myIMU.getEvent(&a, &m, &g, &temp); dataIMU[AX] = a.acceleration.x; dataIMU[AY] = a.acceleration.y; dataIMU[AZ] = a.acceleration.z; dataIMU[OMEGAX] = g.gyro.x; dataIMU[OMEGAY] = g.gyro.y; dataIMU[OMEGAZ] = g.gyro.z; dataIMU[AZBIAS] = biasIMU[AZ]; return dataIMU[signalFlag]; } //////////////////////////////////////////////////////////// // Motor Command -- set Motor Speed (in percent) //////////////////////////////////////////////////////////// byte setMotorCommand(double speedPct, byte actionFlag){ static byte motorPWM = 0; static byte biasPWM = 0; pinMode(LEFTMOTORPIN,OUTPUT); analogWrite(LEFTMOTORPIN,motorPWM); pinMode(RIGHTMOTORPIN,OUTPUT); analogWrite(RIGHTMOTORPIN,motorPWM); if (actionFlag == NOOP) { // do nothing--return most recent value return motorPWM; } else if (actionFlag == SETUP) { // setup = set pin modes & initial values Serial.println("Motor Setup"); pinMode(FORWARDPIN,OUTPUT); digitalWrite(FORWARDPIN,1); pinMode(REVERSEPIN,OUTPUT); digitalWrite(REVERSEPIN,0); pinMode(LEFTMOTORPIN,OUTPUT); pinMode(RIGHTMOTORPIN,OUTPUT); delay(1000); } else if (actionFlag == ADJUST) { // adjust = read bias from pot; speedPct = 0.0; biasPWM = constrain(0.25*analogRead(MOTORPOT),0,100); Serial.print(" Motor Bias PWM = "); Serial.print(biasPWM); } else if (actionFlag == NORMAL) { // nothing special needed for normal operation } // // determine direction and PWM command // byte directionFlag = (speedPct >= 0); digitalWrite(FORWARDPIN,directionFlag); digitalWrite(REVERSEPIN,!directionFlag); speedPct = abs(speedPct); motorPWM = constrain(1.0*biasPWM+0.01*(255-biasPWM)*speedPct,0,255); analogWrite(LEFTMOTORPIN,motorPWM); analogWrite(RIGHTMOTORPIN,motorPWM); return motorPWM; } //////////////////////////////////////////////////////////// // Servo Actuator -- set wheel steering angle //////////////////////////////////////////////////////////// double setServoAngle(double sDeg, byte actionFlag){ static double t_us = 0.0; static double servoCenter_us = 1350.0; // default value can be changed in SETUP static Servo steeringServo; if (actionFlag == NOOP) { // do nothing--return most recent value return t_us; } else if (actionFlag == SETUP) { // setup = attach & center the servo Serial.println("Servo Setup"); steeringServo.attach(SERVOPIN); delay(1000); } else if (actionFlag == ADJUST) { servoCenter_us = 800.0 + analogRead(SERVOPOT); Serial.print(" Servo Center us = "); Serial.print(servoCenter_us); } else if (actionFlag == NORMAL) { // nothing special needed for normal operation } t_us = constrain(servoCenter_us + SERVOSCALEUS * sDeg, servoCenter_us-SERVOMAXUS, servoCenter_us+SERVOMAXUS); steeringServo.writeMicroseconds(t_us); return t_us; } //////////////////////////////////////////////////////////// // Ping Sensor -- perform action on selected distance sensor //////////////////////////////////////////////////////////// double getPingDistance(byte iPing, byte actionFlag) { static double pingDistanceCM[] = {0.0, 0.0, 0.0}; byte trigPins[] = PINGTRIGPINS; byte echoPins[] = PINGECHOPINS; byte grndPins[] = PINGEGRNDPINS; if (actionFlag == NOOP) { // do nothing--return most recent value return pingDistanceCM[iPing]; } else if (actionFlag == SETUP) { // setup = initial pins then read sensor Serial.println("Ping Setup"); delay(1000); pinMode(grndPins[iPing],OUTPUT); digitalWrite(grndPins[iPing],LOW); pinMode(trigPins[iPing],OUTPUT); pinMode(echoPins[iPing],INPUT); } else if (actionFlag == NORMAL) { // nothing special needed for normal operation } // digitalWrite(trigPins[iPing], LOW); delayMicroseconds(2); digitalWrite(trigPins[iPing], HIGH); delayMicroseconds(5); digitalWrite(trigPins[iPing], LOW); // // The echo pin is used to read the signal from the PING))): a HIGH // pulse whose duration is the time (in microseconds) from the sending // of the ping to the reception of its echo off of an object. // 10000 us timeout implies maximum distance is ~85cm // long timeout_us = 120*PINGDMAX; unsigned long echo_time; echo_time = pulseIn(echoPins[iPing], HIGH, timeout_us); if (echo_time == 0) { return 2*PINGDMAX; } else { pingDistanceCM[iPing] = constrain(0.017*echo_time,PINGDMIN,PINGDMAX); } // // return the distance in centimeters // distance = (10^-6) * (echo_time_us) * (speed of sound m/s) * (100 cm/m) / 2 // divide by 2 because we measure "round trip" time for echo // (0.000001 * echo_time_us * 340.0 * 100.0 / 2.0) // = 0.017*echo_time // return pingDistanceCM[iPing]; }
[ "ransford@seas.upenn.edu" ]
ransford@seas.upenn.edu
b38caf59f481293b9f6d00fa6d231752a06795bb
c4b7aa6c17b14eb742d5a8c42cd2e3eba7ad9354
/Problem Solutions/C++/prob5.cc
2c6b8c8f79592851d5e4f6044248a151c3b01a3c
[]
no_license
marcus-yeagle/Project-Euler
120bd945ae137a2b496edda559b8ff04660d2e32
9ab8bfa3a7478f6c900f5ef066a2b111e4d2b49d
refs/heads/master
2022-03-14T16:47:36.541153
2019-11-26T02:48:22
2019-11-26T02:48:22
25,888,204
0
0
null
null
null
null
UTF-8
C++
false
false
613
cc
/* Project Euler Problem 5: What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? Marcus Yeagle - marcusnyeagle@gmail.com */ #include <iostream> using namespace std; bool isDiv(int n); int main(){ int n = 1; while (!isDiv(n)) ++n; return 0; } // This function checks whether an integer is divisible by all integers up to 20 // If it is divisible for all ints then it prints out the original test integer // and returns true // bool isDiv(int n){ for (int i = 1; i < 21; ++i){ if (n % i != 0) return false; } cout << n << endl; return true; }
[ "marcus.yeagle@gmail.com" ]
marcus.yeagle@gmail.com
50d80be6e1fd6eb2e1dcaf2d52f446afcb763824
b73a46dcf05ab7ba0f079779dcae7b428b76c546
/C++/1139第一次接触.cpp
e5c398336751698c23c18948053a41b431ad45d1
[]
no_license
vei123/PATTestAdvanced
1a665f278e8cc88c4342ed8e8bd489530ca9ba69
222f6e8efa45fadd3a432ba88475d9476591aba8
refs/heads/main
2023-07-28T12:47:55.908453
2021-09-09T10:21:06
2021-09-09T10:21:06
392,303,394
0
0
null
null
null
null
UTF-8
C++
false
false
1,620
cpp
#include<iostream> #include<string> #include<vector> #include<unordered_set> #include<unordered_map> #include<algorithm> #define int long long using namespace std; /* 有很多坑点的题,在PAT上比较简单,在AcWing上坑点很多... */ int n, m, k; vector<vector<int>> ans; unordered_set<int> rels; unordered_map<int, vector<int>> fris; bool cmp(const vector<int>& a, const vector<int>& b) { if (a[0] != b[0]) return a[0] < b[0]; else return a[1] < b[1]; } inline bool find(int i, int j) { return rels.count(100000 * i + j); } inline bool samesymbol(int i, int j) { return (i / 10000) == (j / 10000); } signed main() { scanf("%lld%lld", &n, &m); for (int i = 0; i < m; i++) { string s, t; cin >> s >> t; int u = abs(stoi(s)), v = abs(stoi(t)); if (s[0] != '-') u += 10000; if (t[0] != '-') v += 10000; rels.insert(100000 * u + v); rels.insert(100000 * v + u); if (!fris.count(u)) fris[u] = vector<int>(); fris[u].emplace_back(v); if (!fris.count(v)) fris[v] = vector<int>(); fris[v].emplace_back(u); } scanf("%lld", &k); while (k--) { string s, t; cin >> s >> t; int u = abs(stoi(s)), v = abs(stoi(t)); if (s[0] != '-') u += 10000; if (t[0] != '-') v += 10000; ans.clear(); for (int i : fris[u]) { if (!samesymbol(i, u) || i == v || i == u) continue; for (int j : fris[i]) { if (samesymbol(j, v) && find(j, v) && j != u && j != v) ans.emplace_back(vector<int>{i, j}); } } sort(ans.begin(), ans.end(), cmp); printf("%lld\n", ans.size()); for (auto& p : ans) printf("%04lld %04lld\n", p[0] % 10000, p[1] % 10000); } return 0; }
[ "noreply@github.com" ]
noreply@github.com
429ca6340f88a0d953e581e7789448ec4aa79623
b8b77b4ca4d27b0071fc4be90a485e657d8a129a
/Arduino/Gyro_XBee_Smooth/Gyro_XBee_Smooth.ino
e5476e0422601ac345ea6af0e16d4ff933bd6e7e
[]
no_license
ryanmaksymic/Dissolving_Self
c332396ba9abda1ed29a7576f949f9a78c056a2b
9bc60ea1f47500bfb87780a5f02fc78c69fcb4df
refs/heads/master
2020-05-30T11:36:32.967613
2014-04-22T22:37:07
2014-04-22T22:37:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,004
ino
/* Gyro XBee March 14, 2013 Wiring: * GND = GND * VCC = 3.3 V * SCL = A5 * SDA = A4 * SDO = GND * CS = 3.3 V * INT2 = NC * INT1 = NC */ #include <Wire.h> #define CTRL_REG1 0x20 #define CTRL_REG2 0x21 #define CTRL_REG3 0x22 #define CTRL_REG4 0x23 #define CTRL_REG5 0x24 int L3G4200D_Address = 0b1101000; // L3G4200D's I2C address int x; int y; int z; int temp; const int numReadings = 35; int readings[numReadings]; // the readings from the analog input int index = 0; // the index of the current reading int total = 0; // the running total int average = 0; // the average void setup() { Wire.begin(); // join the I2C bus as master Serial.begin(115200); // open serial port for (int thisReading = 0; thisReading < numReadings; thisReading++) { readings[thisReading] = 0; } //Serial.println("Starting up L3G4200D..."); setupL3G4200D(2000); // configure L3G4200 at 250, 500, or 2000 degrees per second delay(2000); // wait for the sensor to be ready } void loop() { getGyroValues(); // update x, y, and z with new values Serial.println(x); // send it to the computer as ASCII digits } void loopAlt() { getGyroValues(); // update x, y, and z with new values total = total - readings[index]; // subtract the last reading readings[index] = x; // read from the sensor total = total + readings[index]; // add the reading to the total index++; // advance to the next position in the array if (index >= numReadings) // if we're at the end of the array, { index = 0; // wrap around to the beginning } average = total / numReadings; // calculate the average Serial.println(average); // send it to the computer as ASCII digits delay(1); } void getGyroValues() { byte xMSB = readRegister(L3G4200D_Address, 0x29); byte xLSB = readRegister(L3G4200D_Address, 0x28); x = ((xMSB << 8) | xLSB); byte yMSB = readRegister(L3G4200D_Address, 0x2B); byte yLSB = readRegister(L3G4200D_Address, 0x2A); y = ((yMSB << 8) | yLSB); byte zMSB = readRegister(L3G4200D_Address, 0x2D); byte zLSB = readRegister(L3G4200D_Address, 0x2C); z = ((zMSB << 8) | zLSB); } int setupL3G4200D(int scale) // From Jim Lindblom's (Sparkfun) code { // Enable x, y, z, and turn off power down: writeRegister(L3G4200D_Address, CTRL_REG1, 0b00001111); // If you'd like to adjust/use the HPF, you can edit the line below to configure CTRL_REG2: writeRegister(L3G4200D_Address, CTRL_REG2, 0b00000000); // Configure CTRL_REG3 to generate data ready interrupt on INT2 // No interrupts used on INT1, if you'd like to configure INT1 // or INT2 otherwise, consult the datasheet: writeRegister(L3G4200D_Address, CTRL_REG3, 0b00001000); // CTRL_REG4 controls the full-scale range, among other things: if(scale == 250) { writeRegister(L3G4200D_Address, CTRL_REG4, 0b00000000); } else if(scale == 500) { writeRegister(L3G4200D_Address, CTRL_REG4, 0b00010000); } else { writeRegister(L3G4200D_Address, CTRL_REG4, 0b00110000); } // CTRL_REG5 controls high-pass filtering of outputs, use it // if you'd like: writeRegister(L3G4200D_Address, CTRL_REG5, 0b00000010); } void writeRegister(int deviceAddress, byte address, byte val) { Wire.beginTransmission(deviceAddress); // start transmission to device Wire.write(address); // send register address Wire.write(val); // send value to write Wire.endTransmission(); // end transmission } int readRegister(int deviceAddress, byte address) { int v; Wire.beginTransmission(deviceAddress); Wire.write(address); // register to read Wire.endTransmission(); Wire.requestFrom(deviceAddress, 1); // request one byte from slave while(!Wire.available()) // wait until one byte is received { } v = Wire.read(); // store received byte return v; }
[ "ryanmaksymic@gmail.com" ]
ryanmaksymic@gmail.com
ffe7a6538a61690dd3a920e40d488961a8b9436f
9a134f9e6f92da5bba20e8bf76ba18f6e0bc3842
/BuilderTile.h
c0cba388bab44d6b8bb56c5f2509b745d1bece37
[]
no_license
clay3075/SFMLTilemap
fbe2087f0597b44b1d3bc0a7787b72b3f9f4964c
ae7591cce5d486822f886f89ad3c6741197168aa
refs/heads/master
2023-03-04T21:04:32.884477
2021-02-15T02:34:48
2021-02-15T02:34:48
333,276,941
0
0
null
null
null
null
UTF-8
C++
false
false
1,284
h
// // Created by Clay Reddick on 2/7/21. // #ifndef SFMLTILEMAP_BUILDERTILE_H #define SFMLTILEMAP_BUILDERTILE_H #include <SFML/Graphics.hpp> #include "UI/Point.h" #include "UI/Dimensions.h" class BuilderTile : public sf::Drawable { public: explicit BuilderTile(UI::Dimensions dim, UI::Point point) { _dimensions = dim; _point = point; _sprite.setFillColor(sf::Color::Black); } void setCollision(bool collision); void setTexture(sf::Texture* texture); void draw(sf::RenderTarget& target, sf::RenderStates states) const override; void mouseEnter(sf::Texture* texture); void mouseExit(); void update(sf::RenderWindow* window, sf::Texture* texture); void setOnTextureChanged(std::function<void(BuilderTile*, sf::Texture*)> onTextureChanged) { _onTextureChanged = onTextureChanged; } UI::Point getPosition() { return _point; } private: bool _collision = false; bool _textureChanged = false; bool _mouseCaptured = false; sf::RectangleShape _sprite; UI::Dimensions _dimensions; UI::Point _point; sf::Texture* _oldTexture = nullptr; sf::Texture* _currentTexture = nullptr; std::function<void(BuilderTile*, sf::Texture*)> _onTextureChanged = nullptr; }; #endif //SFMLTILEMAP_BUILDERTILE_H
[ "cjreddick96@gmail.com" ]
cjreddick96@gmail.com
9597cf00972113930aed9297641093000041ba4f
612325535126eaddebc230d8c27af095c8e5cc2f
/src/net/http2/hpack/decoder/hpack_string_collector.h
00ab2cd5770779eec8d36d134aa19d151bc69fad
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/proto-quic_1V94
1a3a03ac7a08a494b3d4e9857b24bb8f2c2cd673
feee14d96ee95313f236e0f0e3ff7719246c84f7
refs/heads/master
2023-04-01T14:36:53.888576
2019-10-17T02:23:04
2019-10-17T02:23:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,823
h
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NET_HTTP2_HPACK_DECODER_HPACK_STRING_COLLECTOR_H_ #define NET_HTTP2_HPACK_DECODER_HPACK_STRING_COLLECTOR_H_ // Supports tests of decoding HPACK strings. #include <stddef.h> #include <iosfwd> #include <string> #include "base/strings/string_piece.h" #include "net/http2/hpack/decoder/hpack_string_decoder_listener.h" #include "testing/gtest/include/gtest/gtest.h" namespace net { namespace test { // Records the callbacks associated with a decoding a string; must // call Clear() between decoding successive strings. struct HpackStringCollector : public HpackStringDecoderListener { enum CollectorState { kGenesis, kStarted, kEnded, }; HpackStringCollector(); HpackStringCollector(const std::string& str, bool huffman); void Clear(); bool IsClear() const; bool IsInProgress() const; bool HasEnded() const; void OnStringStart(bool huffman, size_t length) override; void OnStringData(const char* data, size_t length) override; void OnStringEnd() override; ::testing::AssertionResult Collected(base::StringPiece str, bool is_huffman_encoded) const; std::string ToString() const; std::string s; size_t len; bool huffman_encoded; CollectorState state; }; bool operator==(const HpackStringCollector& a, const HpackStringCollector& b); bool operator!=(const HpackStringCollector& a, const HpackStringCollector& b); std::ostream& operator<<(std::ostream& out, const HpackStringCollector& v); } // namespace test } // namespace net #endif // NET_HTTP2_HPACK_DECODER_HPACK_STRING_COLLECTOR_H_
[ "2100639007@qq.com" ]
2100639007@qq.com
22434d1f7e4b3f1f6516bc15cd8ee0c49ef1f963
2f943e6bd6caf6890d0fc74dd35dd523e95481d8
/Project/cpu.cpp
fb1b2a9dcf416ea4e5890aef9da28abbdfa87ad5
[ "MIT" ]
permissive
JonnyPugh/Battleship
596619b6c0ee5466f3f141a27f24bd8ce4ce7216
4ff20bc9806224487a7ab413e695298bd330568e
refs/heads/master
2021-01-11T15:51:32.386501
2017-01-24T19:00:42
2017-01-24T19:00:42
79,943,160
0
0
null
null
null
null
UTF-8
C++
false
false
877
cpp
#include "cpu.h" #include <string> #include <random> #include <chrono> #include <functional> using std::uniform_int_distribution; using std::bind; using namespace std::chrono; unsigned int cpu_num = 1; std::default_random_engine generator(duration_cast<milliseconds>( system_clock::now().time_since_epoch()).count()); uniform_int_distribution<unsigned int> random_row_col(0, 9); uniform_int_distribution<unsigned int> random_bool(0, 1); auto get_row_col = bind(random_row_col, generator); auto get_bool = bind(random_bool, generator); std::string cpu::get_name() const { return "CPU" + std::to_string(cpu_num++); } void cpu::place_ship(unsigned int length) { unsigned int column = get_row_col(); unsigned int row = get_row_col(); bool vertical = get_bool(); map.place(row, column, length, vertical); } bool cpu::make_shot() { return enemy_map->optimal_shot(); }
[ "jpugh@umich.edu" ]
jpugh@umich.edu
17b8087b6e3da709e72376284b1cbb287c39bd81
a8a29de75dd6ad07dd75c4e3ffa2d3da807d4250
/test/scratch/test.scratch.sinks.shim_string/implicit_link.cpp
b50afd12342fd1cc1998ac06f8525232b50ed0af
[ "BSD-2-Clause" ]
permissive
moteus/FastFormat
3dbcdc33359f0d68db3db9f50f56b3f5d9296cdc
acd894848a5c4a6f9f21ccdd15aa80cc0a079496
refs/heads/master
2021-01-17T17:12:18.812317
2015-09-28T12:15:05
2015-09-28T12:15:05
63,425,872
1
1
null
2016-07-15T13:58:11
2016-07-15T13:58:10
null
UTF-8
C++
false
false
968
cpp
/* ///////////////////////////////////////////////////////////////////////// * File: implicit_link.cpp * * Purpose: Implicit link file for the test.scratch.sinks.shim_string project. * * Created: 12th November 2008 * Updated: 26th September 2015 * * Status: Wizard-generated * * License: (Licensed under the Synesis Software Open License) * * Copyright (c) 2008-2015, Synesis Software Pty Ltd. * All rights reserved. * * www: http://www.synesis.com.au/software * * ////////////////////////////////////////////////////////////////////// */ /* FastFormat header files */ #include <fastformat/implicit_link.h> /* UNIXem header files */ #include <platformstl/platformstl.h> #if defined(PLATFORMSTL_OS_IS_UNIX) && \ defined(_WIN32) # include <unixem/implicit_link.h> #endif /* operating system */ /* ///////////////////////////// end of file //////////////////////////// */
[ "matthew@synesis.com.au" ]
matthew@synesis.com.au
17e2a780b38da25a9c42cab55eb5e935e75941d6
ad944cc08416482a61ec66ae06b9df9b691699c2
/edge_detect_test.cpp
b13731bc528fed20a4e30039d9d84fefb12bfb79
[ "MIT" ]
permissive
OhmVikrant/Sobel_edge_detection
692c893622c16d1e3f42295cf96ceaea43bb1ccc
7980ea20887bf7186335591d46f6e71cd03d0d75
refs/heads/master
2022-11-20T23:38:53.919898
2020-07-10T05:54:58
2020-07-10T05:54:58
278,550,652
1
0
MIT
2020-07-10T05:55:09
2020-07-10T05:55:08
null
UTF-8
C++
false
false
379
cpp
#include "edge_detect.h" #include "hls_opencv.h" int main() { int const rows = MAX_HEIGHT; int const cols = MAX_WIDTH; cv::Mat src = cv::imread(INPUT_IMAGE); cv::Mat dst = src; stream_t stream_in, stream_out; cvMat2AXIvideo(src, stream_in); edge_detect(stream_in, stream_out); AXIvideo2cvMat(stream_out, dst); cv::imwrite(OUTPUT_IMAGE, dst); return 0; }
[ "psomvanshi167@gmail.com" ]
psomvanshi167@gmail.com
2ec8bf18d24e848fb4f37dec4de60b3a6efab603
effe8b4a2028776f6f79171aebbe2181fa183542
/BFS/test_BFSPlanner.cpp
aa540f9078d2fc46f30c123243d94ac75e8c5edf
[]
no_license
Cornelius-Leary-III/graph_search
754ff158c94e49dccec8a300b4f9bee14b80ac9e
7135c25ce127fe9c6e6339038993e5b5d265357e
refs/heads/master
2021-06-20T03:07:33.336835
2021-02-18T04:34:36
2021-02-18T04:34:36
168,218,103
1
0
null
null
null
null
UTF-8
C++
false
false
5,981
cpp
// // Created by carpenter on 2/1/19. // #include <gtest/gtest.h> #include "BFS_Planner.h" TEST(BFS_Planner_ctor, successful_planner_creation) { BFS_Planner planner; EXPECT_TRUE(planner.getStartNode().empty()); EXPECT_TRUE(planner.getGoalNode().empty()); EXPECT_EQ(planner.getInputTotalNumberOfNodes(), 0); EXPECT_EQ(planner.getSizeOfAdjList(), 0); EXPECT_FALSE(planner.hasGoalBeenReached()); } TEST(BFS_Planner_set_start_node, empty_name) { BFS_Planner planner; planner.setStartNode(""); EXPECT_TRUE(planner.getStartNode().empty()); } TEST(BFS_Planner_set_start_node, actual_name) { BFS_Planner planner; planner.setStartNode("10"); EXPECT_EQ(planner.getStartNode(), "10"); } TEST(BFS_Planner_set_goal_node, empty_name) { BFS_Planner planner; planner.setGoalNode(""); EXPECT_TRUE(planner.getGoalNode().empty()); } TEST(BFS_Planner_set_goal_node, actual_name) { BFS_Planner planner; planner.setGoalNode("100"); EXPECT_EQ(planner.getGoalNode(), "100"); } TEST(BFS_Planner_process_setup_header, no_file_given) { BFS_Planner planner; planner.processGraphSetupHeaderOnly(""); EXPECT_EQ(planner.getInputTotalNumberOfNodes(), 0); EXPECT_TRUE(planner.getStartNode().empty()); EXPECT_TRUE(planner.getGoalNode().empty()); } TEST(BFS_Planner_process_setup_header, empty_file) { BFS_Planner planner; planner.processGraphSetupHeaderOnly("tests/empty_test_file.txt"); EXPECT_EQ(planner.getInputTotalNumberOfNodes(), 0); EXPECT_TRUE(planner.getStartNode().empty()); EXPECT_TRUE(planner.getGoalNode().empty()); } TEST(BFS_Planner_process_setup_header, missing_start_and_goal_nodes) { BFS_Planner planner; planner.processGraphSetupHeaderOnly("tests/missing_start_and_goal.txt"); EXPECT_NE(planner.getInputTotalNumberOfNodes(), 0); EXPECT_TRUE(planner.getStartNode().empty()); EXPECT_TRUE(planner.getGoalNode().empty()); } TEST(BFS_Planner_process_setup_header, missing_goal_node) { BFS_Planner planner; planner.processGraphSetupHeaderOnly("tests/missing_goal.txt"); EXPECT_NE(planner.getInputTotalNumberOfNodes(), 0); EXPECT_FALSE(planner.getStartNode().empty()); EXPECT_TRUE(planner.getGoalNode().empty()); } TEST(BFS_Planner_process_setup_header, all_setup_info_present) { BFS_Planner planner; planner.processGraphSetupHeaderOnly("tests/input1.txt"); EXPECT_NE(planner.getInputTotalNumberOfNodes(), 0); EXPECT_FALSE(planner.getStartNode().empty()); EXPECT_FALSE(planner.getGoalNode().empty()); } TEST(BFS_Planner_import_graph_to_adj_list, no_file_given) { BFS_Planner planner; planner.importGraphToAdjList(""); EXPECT_EQ(planner.getInputTotalNumberOfNodes(), 0); EXPECT_TRUE(planner.getStartNode().empty()); EXPECT_TRUE(planner.getGoalNode().empty()); EXPECT_EQ(planner.getSizeOfAdjList(), 0); } TEST(BFS_Planner_import_graph_to_adj_list, empty_file) { BFS_Planner planner; planner.importGraphToAdjList("tests/empty_test_file.txt"); EXPECT_EQ(planner.getInputTotalNumberOfNodes(), 0); EXPECT_TRUE(planner.getStartNode().empty()); EXPECT_TRUE(planner.getGoalNode().empty()); EXPECT_EQ(planner.getSizeOfAdjList(), 0); } TEST(BFS_Planner_import_graph_to_adj_list, missing_start_and_goal_nodes) { BFS_Planner planner; planner.importGraphToAdjList("tests/missing_start_and_goal.txt"); EXPECT_NE(planner.getInputTotalNumberOfNodes(), 0); EXPECT_TRUE(planner.getStartNode().empty()); EXPECT_TRUE(planner.getGoalNode().empty()); EXPECT_EQ(planner.getSizeOfAdjList(), 2); } TEST(BFS_Planner_import_graph_to_adj_list, missing_goal_node) { BFS_Planner planner; planner.importGraphToAdjList("tests/missing_goal.txt"); EXPECT_NE(planner.getInputTotalNumberOfNodes(), 0); EXPECT_FALSE(planner.getStartNode().empty()); EXPECT_TRUE(planner.getGoalNode().empty()); EXPECT_EQ(planner.getSizeOfAdjList(), 3); } TEST(BFS_Planner_import_graph_to_adj_list, only_header_no_edges) { BFS_Planner planner; planner.importGraphToAdjList("tests/setup_info_only.txt"); EXPECT_NE(planner.getInputTotalNumberOfNodes(), 0); EXPECT_FALSE(planner.getStartNode().empty()); EXPECT_FALSE(planner.getGoalNode().empty()); EXPECT_EQ(planner.getSizeOfAdjList(), 0); } TEST(BFS_Planner_search_for_goal, no_graph_imported) { BFS_Planner planner; planner.processGraphSetupHeaderOnly("tests/input1.txt"); EXPECT_FALSE(planner.searchForGoal()); } TEST(BFS_Planner_search_for_goal, only_2_nodes_start_and_goal) { BFS_Planner planner; planner.importGraphToAdjList("tests/only_2_nodes_no_path_to_goal_in_graph.txt"); EXPECT_EQ(planner.getSizeOfAdjList(), 2); EXPECT_FALSE(planner.searchForGoal()); } TEST(BFS_Planner_search_for_goal, import_and_search_graph) { BFS_Planner planner; string inputFile = "tests/input1.txt"; BFS_Planner testHeaderImport; testHeaderImport.processGraphSetupHeaderOnly(inputFile); int testNumNodes = testHeaderImport.getInputTotalNumberOfNodes(); planner.importGraphToAdjList(inputFile); EXPECT_EQ(planner.getSizeOfAdjList(), testNumNodes); EXPECT_EQ(planner.getStartNode(), testHeaderImport.getStartNode()); EXPECT_EQ(planner.getGoalNode(), testHeaderImport.getGoalNode()); EXPECT_TRUE(planner.searchForGoal()); } TEST(BFSPlanner_class, import_and_search_weighted_graph) { BFS_Planner planner; EXPECT_FALSE(planner.hasGoalBeenReached()); EXPECT_EQ(planner.getSizeOfAdjList(), 0); string inputFile = "tests/input2.txt"; BFS_Planner testHeaderImport; testHeaderImport.processGraphSetupHeaderOnly(inputFile); int testNumNodes = testHeaderImport.getInputTotalNumberOfNodes(); planner.importGraphToAdjList(inputFile); EXPECT_EQ(planner.getSizeOfAdjList(), testNumNodes); EXPECT_EQ(planner.getStartNode(), testHeaderImport.getStartNode()); EXPECT_EQ(planner.getGoalNode(), testHeaderImport.getGoalNode()); EXPECT_TRUE(planner.searchForGoal()); }
[ "celeary3@vt.edu" ]
celeary3@vt.edu
8ddfdd7c253d2dd7b81c39fa80648980e35e9fd0
e763b855be527d69fb2e824dfb693d09e59cdacb
/aws-cpp-sdk-apigateway/source/model/CreateDeploymentRequest.cpp
4ea963a1f9e59fc5db673352c90fda541d353b61
[ "MIT", "Apache-2.0", "JSON" ]
permissive
34234344543255455465/aws-sdk-cpp
47de2d7bde504273a43c99188b544e497f743850
1d04ff6389a0ca24361523c58671ad0b2cde56f5
refs/heads/master
2023-06-10T16:15:54.618966
2018-05-07T23:32:08
2018-05-07T23:32:08
132,632,360
1
0
Apache-2.0
2023-06-01T23:20:47
2018-05-08T15:56:35
C++
UTF-8
C++
false
false
2,315
cpp
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/apigateway/model/CreateDeploymentRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::APIGateway::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; CreateDeploymentRequest::CreateDeploymentRequest() : m_restApiIdHasBeenSet(false), m_stageNameHasBeenSet(false), m_stageDescriptionHasBeenSet(false), m_descriptionHasBeenSet(false), m_cacheClusterEnabled(false), m_cacheClusterEnabledHasBeenSet(false), m_cacheClusterSize(CacheClusterSize::NOT_SET), m_cacheClusterSizeHasBeenSet(false), m_variablesHasBeenSet(false), m_canarySettingsHasBeenSet(false) { } Aws::String CreateDeploymentRequest::SerializePayload() const { JsonValue payload; if(m_stageNameHasBeenSet) { payload.WithString("stageName", m_stageName); } if(m_stageDescriptionHasBeenSet) { payload.WithString("stageDescription", m_stageDescription); } if(m_descriptionHasBeenSet) { payload.WithString("description", m_description); } if(m_cacheClusterEnabledHasBeenSet) { payload.WithBool("cacheClusterEnabled", m_cacheClusterEnabled); } if(m_cacheClusterSizeHasBeenSet) { payload.WithString("cacheClusterSize", CacheClusterSizeMapper::GetNameForCacheClusterSize(m_cacheClusterSize)); } if(m_variablesHasBeenSet) { JsonValue variablesJsonMap; for(auto& variablesItem : m_variables) { variablesJsonMap.WithString(variablesItem.first, variablesItem.second); } payload.WithObject("variables", std::move(variablesJsonMap)); } if(m_canarySettingsHasBeenSet) { payload.WithObject("canarySettings", m_canarySettings.Jsonize()); } return payload.WriteReadable(); }
[ "henso@amazon.com" ]
henso@amazon.com
e78c467880188dd144e283589a2c35b29d14b9a4
b3c47795e8b6d95ae5521dcbbb920ab71851a92f
/POJ/2/2431.cc
b6c46108942d7ffe791c0741b21c2aa07668e0b0
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
Wizmann/ACM-ICPC
6afecd0fd09918c53a2a84c4d22c244de0065710
7c30454c49485a794dcc4d1c09daf2f755f9ecc1
refs/heads/master
2023-07-15T02:46:21.372860
2023-07-09T15:30:27
2023-07-09T15:30:27
3,009,276
51
23
null
null
null
null
UTF-8
C++
false
false
1,393
cc
//Result: wizmann 2431 Accepted 860K 32MS G++ 1337B 2014-06-30 22:24:23 #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> #include <queue> using namespace std; #define print(x) cout << x << endl #define input(x) cin >> x const int SIZE = 12345; struct Station { int pos, fuel; Station(){} Station(int ipos, int ifuel): pos(ipos), fuel(ifuel) {} friend bool operator < (const Station& a, const Station& b) { return a.pos < b.pos; } }; Station gas[SIZE]; int n, L, P; int main() { freopen("input.txt", "r", stdin); int a, b; input(n); for (int i = 1; i <= n; i++) { scanf("%d%d", &a, &b); gas[i] = Station(a, b); } input(L >> P); for (int i = 1; i <= n; i++) { gas[i].pos = L - gas[i].pos; } gas[0] = Station(0, P); n++; gas[n] = Station(L, 0); n++; sort(gas, gas + n); int now = 0, ans = 0; priority_queue<int> pq; for (int i = 0; i + 1 < n; i++) { pq.push(gas[i].fuel); now -= gas[i + 1].pos - gas[i].pos; while (now < 0 && !pq.empty()) { now += pq.top(); pq.pop(); ans++; } if (now < 0) { break; } } if (now >= 0) { print(--ans); } else { print(-1); } return 0; }
[ "mail.kuuy@gmail.com" ]
mail.kuuy@gmail.com
ae817fc452b01e880e5ad6d4688a76eaf2d227d0
49f88ff91aa582e1a9d5ae5a7014f5c07eab7503
/gen/third_party/blink/renderer/core/events/progress_event_init.cc
a2c949dd7adef2c9d323c6a09725d0ba9f5cf0ee
[]
no_license
AoEiuV020/kiwibrowser-arm64
b6c719b5f35d65906ae08503ec32f6775c9bb048
ae7383776e0978b945e85e54242b4e3f7b930284
refs/heads/main
2023-06-01T21:09:33.928929
2021-06-22T15:56:53
2021-06-22T15:56:53
379,186,747
0
1
null
null
null
null
UTF-8
C++
false
false
893
cc
// Copyright 2014 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. // This file has been auto-generated from the Jinja2 template // third_party/blink/renderer/bindings/templates/dictionary_impl.cpp.tmpl // by the script code_generator_v8.py. // DO NOT MODIFY! // clang-format off #include "third_party/blink/renderer/core/events/progress_event_init.h" namespace blink { ProgressEventInit::ProgressEventInit() { setLengthComputable(false); setLoaded(0); setTotal(0); } ProgressEventInit::~ProgressEventInit() {} ProgressEventInit::ProgressEventInit(const ProgressEventInit&) = default; ProgressEventInit& ProgressEventInit::operator=(const ProgressEventInit&) = default; void ProgressEventInit::Trace(blink::Visitor* visitor) { EventInit::Trace(visitor); } } // namespace blink
[ "aoeiuv020@gmail.com" ]
aoeiuv020@gmail.com
944f1eef7597180f9ef4517be9cbf9aeae5df7b7
549243b0ca2a23432389529149ffb2b9cbd65bb2
/src/nvmath/Vector.h
329531ab238b46724b137f5908ab9a797cf1fd09
[]
no_license
castano/nvidia-oss
bb025c248ac6490673e9b11f544bed70119421dc
91f2030e33ae542005768b1181b2538c37171468
refs/heads/master
2023-07-12T18:12:08.858663
2009-11-05T19:08:45
2009-11-05T19:08:45
32,236,993
2
0
null
null
null
null
UTF-8
C++
false
false
18,661
h
// This code is in the public domain -- castanyo@yahoo.es #ifndef NV_MATH_VECTOR_H #define NV_MATH_VECTOR_H #include <nvmath/nvmath.h> #include <nvcore/Algorithms.h> // min, max namespace nv { enum zero_t { zero }; enum identity_t { identity }; // I should probably use templates. typedef float scalar; class NVMATH_CLASS Vector2 { public: typedef Vector2 const & Arg; Vector2(); explicit Vector2(zero_t); explicit Vector2(scalar f); Vector2(scalar x, scalar y); Vector2(Vector2::Arg v); const Vector2 & operator=(Vector2::Arg v); void setComponent(uint idx, scalar f); scalar x() const; scalar y() const; scalar component(uint idx) const; const scalar * ptr() const; void set(scalar x, scalar y); Vector2 operator-() const; void operator+=(Vector2::Arg v); void operator-=(Vector2::Arg v); void operator*=(scalar s); void operator*=(Vector2::Arg v); friend bool operator==(Vector2::Arg a, Vector2::Arg b); friend bool operator!=(Vector2::Arg a, Vector2::Arg b); private: scalar m_x, m_y; }; class NVMATH_CLASS Vector3 { public: typedef Vector3 const & Arg; Vector3(); explicit Vector3(zero_t); Vector3(scalar x, scalar y, scalar z); Vector3(Vector2::Arg v, scalar z); Vector3(Vector3::Arg v); const Vector3 & operator=(Vector3::Arg v); scalar x() const; scalar y() const; scalar z() const; const Vector2 & xy() const; scalar component(uint idx) const; void setComponent(uint idx, scalar f); const scalar * ptr() const; void set(scalar x, scalar y, scalar z); Vector3 operator-() const; void operator+=(Vector3::Arg v); void operator-=(Vector3::Arg v); void operator*=(scalar s); void operator/=(scalar s); void operator*=(Vector3::Arg v); friend bool operator==(Vector3::Arg a, Vector3::Arg b); friend bool operator!=(Vector3::Arg a, Vector3::Arg b); private: scalar m_x, m_y, m_z; }; class NVMATH_CLASS Vector4 { public: typedef Vector4 const & Arg; Vector4(); explicit Vector4(zero_t); Vector4(scalar x, scalar y, scalar z, scalar w); Vector4(Vector2::Arg v, scalar z, scalar w); Vector4(Vector3::Arg v, scalar w); Vector4(Vector4::Arg v); // Vector4(const Quaternion & v); const Vector4 & operator=(Vector4::Arg v); scalar x() const; scalar y() const; scalar z() const; scalar w() const; const Vector2 & xy() const; const Vector3 & xyz() const; scalar component(uint idx) const; void setComponent(uint idx, scalar f); const scalar * ptr() const; void set(scalar x, scalar y, scalar z, scalar w); Vector4 operator-() const; void operator+=(Vector4::Arg v); void operator-=(Vector4::Arg v); void operator*=(scalar s); void operator*=(Vector4::Arg v); friend bool operator==(Vector4::Arg a, Vector4::Arg b); friend bool operator!=(Vector4::Arg a, Vector4::Arg b); private: scalar m_x, m_y, m_z, m_w; }; // Vector2 inline Vector2::Vector2() {} inline Vector2::Vector2(zero_t) : m_x(0.0f), m_y(0.0f) {} inline Vector2::Vector2(scalar f) : m_x(f), m_y(f) {} inline Vector2::Vector2(scalar x, scalar y) : m_x(x), m_y(y) {} inline Vector2::Vector2(Vector2::Arg v) : m_x(v.x()), m_y(v.y()) {} inline const Vector2 & Vector2::operator=(Vector2::Arg v) { m_x = v.x(); m_y = v.y(); return *this; } inline scalar Vector2::x() const { return m_x; } inline scalar Vector2::y() const { return m_y; } inline scalar Vector2::component(uint idx) const { nvDebugCheck(idx < 2); if (idx == 0) return x(); if (idx == 1) return y(); nvAssume(false); return 0.0f; } inline void Vector2::setComponent(uint idx, float f) { nvDebugCheck(idx < 2); if (idx == 0) m_x = f; else if (idx == 1) m_y = f; } inline const scalar * Vector2::ptr() const { return &m_x; } inline void Vector2::set(scalar x, scalar y) { m_x = x; m_y = y; } inline Vector2 Vector2::operator-() const { return Vector2(-m_x, -m_y); } inline void Vector2::operator+=(Vector2::Arg v) { m_x += v.m_x; m_y += v.m_y; } inline void Vector2::operator-=(Vector2::Arg v) { m_x -= v.m_x; m_y -= v.m_y; } inline void Vector2::operator*=(scalar s) { m_x *= s; m_y *= s; } inline void Vector2::operator*=(Vector2::Arg v) { m_x *= v.m_x; m_y *= v.m_y; } inline bool operator==(Vector2::Arg a, Vector2::Arg b) { return a.m_x == b.m_x && a.m_y == b.m_y; } inline bool operator!=(Vector2::Arg a, Vector2::Arg b) { return a.m_x != b.m_x || a.m_y != b.m_y; } // Vector3 inline Vector3::Vector3() {} inline Vector3::Vector3(zero_t) : m_x(0.0f), m_y(0.0f), m_z(0.0f) {} inline Vector3::Vector3(scalar x, scalar y, scalar z) : m_x(x), m_y(y), m_z(z) {} inline Vector3::Vector3(Vector2::Arg v, scalar z) : m_x(v.x()), m_y(v.y()), m_z(z) {} inline Vector3::Vector3(Vector3::Arg v) : m_x(v.x()), m_y(v.y()), m_z(v.z()) {} inline const Vector3 & Vector3::operator=(Vector3::Arg v) { m_x = v.m_x; m_y = v.m_y; m_z = v.m_z; return *this; } inline scalar Vector3::x() const { return m_x; } inline scalar Vector3::y() const { return m_y; } inline scalar Vector3::z() const { return m_z; } inline const Vector2 & Vector3::xy() const { return *(Vector2 *)this; } inline scalar Vector3::component(uint idx) const { nvDebugCheck(idx < 3); if (idx == 0) return m_x; if (idx == 1) return m_y; if (idx == 2) return m_z; nvAssume(false); return 0.0f; } inline void Vector3::setComponent(uint idx, float f) { nvDebugCheck(idx < 3); if (idx == 0) m_x = f; else if (idx == 1) m_y = f; else if (idx == 2) m_z = f; } inline const scalar * Vector3::ptr() const { return &m_x; } inline void Vector3::set(scalar x, scalar y, scalar z) { m_x = x; m_y = y; m_z = z; } inline Vector3 Vector3::operator-() const { return Vector3(-m_x, -m_y, -m_z); } inline void Vector3::operator+=(Vector3::Arg v) { m_x += v.m_x; m_y += v.m_y; m_z += v.m_z; } inline void Vector3::operator-=(Vector3::Arg v) { m_x -= v.m_x; m_y -= v.m_y; m_z -= v.m_z; } inline void Vector3::operator*=(scalar s) { m_x *= s; m_y *= s; m_z *= s; } inline void Vector3::operator/=(scalar s) { float is = 1.0f / s; m_x *= is; m_y *= is; m_z *= is; } inline void Vector3::operator*=(Vector3::Arg v) { m_x *= v.m_x; m_y *= v.m_y; m_z *= v.m_z; } inline bool operator==(Vector3::Arg a, Vector3::Arg b) { return a.m_x == b.m_x && a.m_y == b.m_y && a.m_z == b.m_z; } inline bool operator!=(Vector3::Arg a, Vector3::Arg b) { return a.m_x != b.m_x || a.m_y != b.m_y || a.m_z != b.m_z; } // Vector4 inline Vector4::Vector4() {} inline Vector4::Vector4(zero_t) : m_x(0.0f), m_y(0.0f), m_z(0.0f), m_w(0.0f) {} inline Vector4::Vector4(scalar x, scalar y, scalar z, scalar w) : m_x(x), m_y(y), m_z(z), m_w(w) {} inline Vector4::Vector4(Vector2::Arg v, scalar z, scalar w) : m_x(v.x()), m_y(v.y()), m_z(z), m_w(w) {} inline Vector4::Vector4(Vector3::Arg v, scalar w) : m_x(v.x()), m_y(v.y()), m_z(v.z()), m_w(w) {} inline Vector4::Vector4(Vector4::Arg v) : m_x(v.x()), m_y(v.y()), m_z(v.z()), m_w(v.w()) {} inline const Vector4 & Vector4::operator=(const Vector4 & v) { m_x = v.m_x; m_y = v.m_y; m_z = v.m_z; m_w = v.m_w; return *this; } inline scalar Vector4::x() const { return m_x; } inline scalar Vector4::y() const { return m_y; } inline scalar Vector4::z() const { return m_z; } inline scalar Vector4::w() const { return m_w; } inline const Vector2 & Vector4::xy() const { return *(Vector2 *)this; } inline const Vector3 & Vector4::xyz() const { return *(Vector3 *)this; } inline scalar Vector4::component(uint idx) const { nvDebugCheck(idx < 4); if (idx == 0) return x(); if (idx == 1) return y(); if (idx == 2) return z(); if (idx == 3) return w(); nvAssume(false); return 0.0f; } inline void Vector4::setComponent(uint idx, float f) { nvDebugCheck(idx < 4); if (idx == 0) m_x = f; else if (idx == 1) m_y = f; else if (idx == 2) m_z = f; else if (idx == 3) m_w = f; } inline const scalar * Vector4::ptr() const { return &m_x; } inline void Vector4::set(scalar x, scalar y, scalar z, scalar w) { m_x = x; m_y = y; m_z = z; m_w = w; } inline Vector4 Vector4::operator-() const { return Vector4(-m_x, -m_y, -m_z, -m_w); } inline void Vector4::operator+=(Vector4::Arg v) { m_x += v.m_x; m_y += v.m_y; m_z += v.m_z; m_w += v.m_w; } inline void Vector4::operator-=(Vector4::Arg v) { m_x -= v.m_x; m_y -= v.m_y; m_z -= v.m_z; m_w -= v.m_w; } inline void Vector4::operator*=(scalar s) { m_x *= s; m_y *= s; m_z *= s; m_w *= s; } inline void Vector4::operator*=(Vector4::Arg v) { m_x *= v.m_x; m_y *= v.m_y; m_z *= v.m_z; m_w *= v.m_w; } inline bool operator==(Vector4::Arg a, Vector4::Arg b) { return a.m_x == b.m_x && a.m_y == b.m_y && a.m_z == b.m_z && a.m_w == b.m_w; } inline bool operator!=(Vector4::Arg a, Vector4::Arg b) { return a.m_x != b.m_x || a.m_y != b.m_y || a.m_z != b.m_z || a.m_w != b.m_w; } // Functions // Vector2 inline Vector2 add(Vector2::Arg a, Vector2::Arg b) { return Vector2(a.x() + b.x(), a.y() + b.y()); } inline Vector2 operator+(Vector2::Arg a, Vector2::Arg b) { return add(a, b); } inline Vector2 sub(Vector2::Arg a, Vector2::Arg b) { return Vector2(a.x() - b.x(), a.y() - b.y()); } inline Vector2 operator-(Vector2::Arg a, Vector2::Arg b) { return sub(a, b); } inline Vector2 scale(Vector2::Arg v, scalar s) { return Vector2(v.x() * s, v.y() * s); } inline Vector2 scale(Vector2::Arg v, Vector2::Arg s) { return Vector2(v.x() * s.x(), v.y() * s.y()); } inline Vector2 operator*(Vector2::Arg v, scalar s) { return scale(v, s); } inline Vector2 operator*(Vector2::Arg v1, Vector2::Arg v2) { return Vector2(v1.x()*v2.x(), v1.y()*v2.y()); } inline Vector2 operator*(scalar s, Vector2::Arg v) { return scale(v, s); } inline scalar dot(Vector2::Arg a, Vector2::Arg b) { return a.x() * b.x() + a.y() * b.y(); } inline scalar length_squared(Vector2::Arg v) { return v.x() * v.x() + v.y() * v.y(); } inline scalar length(Vector2::Arg v) { return sqrtf(length_squared(v)); } inline scalar inverse_length(Vector2::Arg v) { return 1.0f / sqrtf(length_squared(v)); } inline bool isNormalized(Vector2::Arg v, float epsilon = NV_NORMAL_EPSILON) { return equal(length(v), 1, epsilon); } inline Vector2 normalize(Vector2::Arg v, float epsilon = NV_EPSILON) { float l = length(v); nvDebugCheck(!isZero(l, epsilon)); Vector2 n = scale(v, 1.0f / l); nvDebugCheck(isNormalized(n)); return n; } inline Vector2 normalizeSafe(Vector2::Arg v, Vector2::Arg fallback, float epsilon = NV_EPSILON) { float l = length(v); if (isZero(l, epsilon)) { return fallback; } return scale(v, 1.0f / l); } inline bool equal(Vector2::Arg v1, Vector2::Arg v2, float epsilon = NV_EPSILON) { return equal(v1.x(), v2.x(), epsilon) && equal(v1.y(), v2.y(), epsilon); } inline Vector2 min(Vector2::Arg a, Vector2::Arg b) { return Vector2(min(a.x(), b.x()), min(a.y(), b.y())); } inline Vector2 max(Vector2::Arg a, Vector2::Arg b) { return Vector2(max(a.x(), b.x()), max(a.y(), b.y())); } inline bool isValid(Vector2::Arg v) { return isFinite(v.x()) && isFinite(v.y()); } // Vector3 inline Vector3 add(Vector3::Arg a, Vector3::Arg b) { return Vector3(a.x() + b.x(), a.y() + b.y(), a.z() + b.z()); } inline Vector3 add(Vector3::Arg a, float b) { return Vector3(a.x() + b, a.y() + b, a.z() + b); } inline Vector3 operator+(Vector3::Arg a, Vector3::Arg b) { return add(a, b); } inline Vector3 operator+(Vector3::Arg a, float b) { return add(a, b); } inline Vector3 sub(Vector3::Arg a, Vector3::Arg b) { return Vector3(a.x() - b.x(), a.y() - b.y(), a.z() - b.z()); } inline Vector3 sub(Vector3::Arg a, float b) { return Vector3(a.x() - b, a.y() - b, a.z() - b); } inline Vector3 operator-(Vector3::Arg a, Vector3::Arg b) { return sub(a, b); } inline Vector3 operator-(Vector3::Arg a, float b) { return sub(a, b); } inline Vector3 cross(Vector3::Arg a, Vector3::Arg b) { return Vector3(a.y() * b.z() - a.z() * b.y(), a.z() * b.x() - a.x() * b.z(), a.x() * b.y() - a.y() * b.x()); } inline Vector3 scale(Vector3::Arg v, scalar s) { return Vector3(v.x() * s, v.y() * s, v.z() * s); } inline Vector3 scale(Vector3::Arg v, Vector3::Arg s) { return Vector3(v.x() * s.x(), v.y() * s.y(), v.z() * s.z()); } inline Vector3 operator*(Vector3::Arg v, scalar s) { return scale(v, s); } inline Vector3 operator*(scalar s, Vector3::Arg v) { return scale(v, s); } inline Vector3 operator*(Vector3::Arg v, Vector3::Arg s) { return scale(v, s); } inline Vector3 operator/(Vector3::Arg v, scalar s) { return scale(v, 1.0f/s); } inline Vector3 add_scaled(Vector3::Arg a, Vector3::Arg b, scalar s) { return Vector3(a.x() + b.x() * s, a.y() + b.y() * s, a.z() + b.z() * s); } inline Vector3 lerp(Vector3::Arg v1, Vector3::Arg v2, scalar t) { const scalar s = 1.0f - t; return Vector3(v1.x() * s + t * v2.x(), v1.y() * s + t * v2.y(), v1.z() * s + t * v2.z()); } inline scalar dot(Vector3::Arg a, Vector3::Arg b) { return a.x() * b.x() + a.y() * b.y() + a.z() * b.z(); } inline scalar length_squared(Vector3::Arg v) { return v.x() * v.x() + v.y() * v.y() + v.z() * v.z(); } inline scalar length(Vector3::Arg v) { return sqrtf(length_squared(v)); } inline scalar inverse_length(Vector3::Arg v) { return 1.0f / sqrtf(length_squared(v)); } inline bool isNormalized(Vector3::Arg v, float epsilon = NV_NORMAL_EPSILON) { return equal(length(v), 1, epsilon); } inline Vector3 normalize(Vector3::Arg v, float epsilon = NV_EPSILON) { float l = length(v); nvDebugCheck(!isZero(l, epsilon)); Vector3 n = scale(v, 1.0f / l); nvDebugCheck(isNormalized(n)); return n; } inline Vector3 normalizeSafe(Vector3::Arg v, Vector3::Arg fallback, float epsilon = NV_EPSILON) { float l = length(v); if (isZero(l, epsilon)) { return fallback; } return scale(v, 1.0f / l); } inline bool equal(Vector3::Arg v1, Vector3::Arg v2, float epsilon = NV_EPSILON) { return equal(v1.x(), v2.x(), epsilon) && equal(v1.y(), v2.y(), epsilon) && equal(v1.z(), v2.z(), epsilon); } inline Vector3 min(Vector3::Arg a, Vector3::Arg b) { return Vector3(min(a.x(), b.x()), min(a.y(), b.y()), min(a.z(), b.z())); } inline Vector3 max(Vector3::Arg a, Vector3::Arg b) { return Vector3(max(a.x(), b.x()), max(a.y(), b.y()), max(a.z(), b.z())); } inline Vector3 clamp(Vector3::Arg v, float min, float max) { return Vector3(clamp(v.x(), min, max), clamp(v.y(), min, max), clamp(v.z(), min, max)); } inline bool isValid(Vector3::Arg v) { return isFinite(v.x()) && isFinite(v.y()) && isFinite(v.z()); } /* Vector3 transform(Quaternion, vector3); Vector3 transform_point(matrix34, vector3); Vector3 transform_vector(matrix34, vector3); Vector3 transform_point(matrix44, vector3); Vector3 transform_vector(matrix44, vector3); */ // Vector4 inline Vector4 add(Vector4::Arg a, Vector4::Arg b) { return Vector4(a.x() + b.x(), a.y() + b.y(), a.z() + b.z(), a.w() + b.w()); } inline Vector4 operator+(Vector4::Arg a, Vector4::Arg b) { return add(a, b); } inline Vector4 sub(Vector4::Arg a, Vector4::Arg b) { return Vector4(a.x() - b.x(), a.y() - b.y(), a.z() - b.z(), a.w() - b.w()); } inline Vector4 operator-(Vector4::Arg a, Vector4::Arg b) { return sub(a, b); } inline Vector4 scale(Vector4::Arg v, scalar s) { return Vector4(v.x() * s, v.y() * s, v.z() * s, v.w() * s); } inline Vector4 scale(Vector4::Arg v, Vector4::Arg s) { return Vector4(v.x() * s.x(), v.y() * s.y(), v.z() * s.z(), v.w() * s.w()); } inline Vector4 operator*(Vector4::Arg v, scalar s) { return scale(v, s); } inline Vector4 operator*(scalar s, Vector4::Arg v) { return scale(v, s); } inline Vector4 operator/(Vector4::Arg v, scalar s) { return scale(v, 1.0f/s); } inline Vector4 add_scaled(Vector4::Arg a, Vector4::Arg b, scalar s) { return Vector4(a.x() + b.x() * s, a.y() + b.y() * s, a.z() + b.z() * s, a.w() + b.w() * s); } inline scalar dot(Vector4::Arg a, Vector4::Arg b) { return a.x() * b.x() + a.y() * b.y() + a.z() * b.z() + a.w() * b.w(); } inline scalar length_squared(Vector4::Arg v) { return v.x() * v.x() + v.y() * v.y() + v.z() * v.z() + v.w() * v.w(); } inline scalar length(Vector4::Arg v) { return sqrtf(length_squared(v)); } inline scalar inverse_length(Vector4::Arg v) { return 1.0f / sqrtf(length_squared(v)); } inline bool isNormalized(Vector4::Arg v, float epsilon = NV_NORMAL_EPSILON) { return equal(length(v), 1, epsilon); } inline Vector4 normalize(Vector4::Arg v, float epsilon = NV_EPSILON) { float l = length(v); nvDebugCheck(!isZero(l, epsilon)); Vector4 n = scale(v, 1.0f / l); nvDebugCheck(isNormalized(n)); return n; } inline Vector4 normalizeSafe(Vector4::Arg v, Vector4::Arg fallback, float epsilon = NV_EPSILON) { float l = length(v); if (isZero(l, epsilon)) { return fallback; } return scale(v, 1.0f / l); } inline bool equal(Vector4::Arg v1, Vector4::Arg v2, float epsilon = NV_EPSILON) { return equal(v1.x(), v2.x(), epsilon) && equal(v1.y(), v2.y(), epsilon) && equal(v1.z(), v2.z(), epsilon) && equal(v1.w(), v2.w(), epsilon); } inline Vector4 min(Vector4::Arg a, Vector4::Arg b) { return Vector4(min(a.x(), b.x()), min(a.y(), b.y()), min(a.z(), b.z()), min(a.w(), b.w())); } inline Vector4 max(Vector4::Arg a, Vector4::Arg b) { return Vector4(max(a.x(), b.x()), max(a.y(), b.y()), max(a.z(), b.z()), max(a.w(), b.w())); } inline bool isValid(Vector4::Arg v) { return isFinite(v.x()) && isFinite(v.y()) && isFinite(v.z()) && isFinite(v.w()); } /* vector4 transform(matrix34, vector4); vector4 transform(matrix44, vector4); */ /* Quaternion mul(Quaternion, Quaternion); // rotational composition Quaternion conjugate(Quaternion); Quaternion inverse(Quaternion); Quaternion axis_angle(const Vector3 & v, scalar s); */ /* matrix34 add(matrix34, matrix34); // note: implicit '1' stays as '1' matrix34 operator+(matrix34, matrix34); matrix34 sub(matrix34, matrix34); // note: implicit '1' stays as '1' matrix34 operator-(matrix34, matrix34); matrix34 mul(matrix34, matrix34); matrix34 operator*(matrix34, matrix34); matrix34 mul(matrix34, quaternion4); // rotation multiplication matrix34 operator*(matrix34, quaternion4); // rotation multiplication matrix34 translation(vector3); matrix34 rotation(quaternion4); matrix34 rotation(vector3, scalar); // axis/angle matrix44 add(matrix44, matrix44); matrix44 operator+(matrix44, matrix44); matrix44 sub(matrix44, matrix44); matrix44 operator-(matrix44, matrix44); matrix44 mul(matrix44, matrix44); matrix44 operator*(matrix44, matrix44); matrix44 mul(matrix44, quaternion4); // rotation multiplication matrix44 operator*(matrix44, quaternion4); // rotation multiplication matrix44 invert(matrix34); matrix44 invert(matrix44); matrix44 transpose(matrix34); matrix44 transpose(matrix44); */ } // nv namespace #endif // NV_MATH_VECTOR_H
[ "castano@9a2b036c-014e-11de-8259-6defae454439" ]
castano@9a2b036c-014e-11de-8259-6defae454439
a7529a5b995a7c19dc4ee3f672729055f5d55973
fe7c6ccb491b4203a42f956a67a43c236dc75f11
/platform/android/src/annotation/multi_point.hpp
ce32aec1d518d8f776d4d146190f2ded42ac91ac
[ "Apache-2.0", "BSD-2-Clause" ]
permissive
luyufanzhi/win_mapbox
f571fef859bb39927b6590df606ea37f3eef9d73
4e024cbd35237e4994b65adb61b265bebed41ea9
refs/heads/master
2023-04-14T20:45:09.734962
2020-05-19T11:18:27
2020-05-19T11:18:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
779
hpp
#pragma once #include <mbgl/util/noncopyable.hpp> #include <jni/jni.hpp> #include "../geometry/lat_lng.hpp" #include "../java/util.hpp" namespace mbgl { namespace android { class MultiPoint : protected mbgl::util::noncopyable { protected: template <class Geometry> static Geometry toGeometry(JNIEnv& env, const jni::Object<java::util::List>& pointsList) { auto jarray = java::util::List::toArray<LatLng>(env, pointsList); std::size_t size = jarray.Length(env); Geometry geometry; geometry.reserve(size); for (std::size_t i = 0; i < size; i++) { geometry.push_back(LatLng::getGeometry(env, jarray.Get(env, i))); } return geometry; } }; } // namespace android } // namespace mbgl
[ "machfe@126.com" ]
machfe@126.com
e5a4d74bd6c0eae379f2d76e45900b8dfabb7f26
521685507e5b26ec9be38b39a249bdc1ee638138
/Examples/Plugins/Filter/vtkMyElevationFilter.h
0f841ff09536404d17478235ae7aea180e07804a
[ "LicenseRef-scancode-paraview-1.2" ]
permissive
matthb2/ParaView-beforekitwareswtichedtogit
6ad4662a1ad8c3d35d2c41df209fc4d78b7ba298
392519e17af37f66f6465722930b3705c1c5ca6c
refs/heads/master
2020-04-05T05:11:15.181579
2009-05-26T20:50:10
2009-05-26T20:50:10
211,087
1
2
null
null
null
null
UTF-8
C++
false
false
1,583
h
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile$ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkMyElevationFilter - generate scalars along a specified direction // .SECTION Description // vtkMyElevationFilter is a filter to generate scalar values from a // dataset. The scalar values lie within a user specified range, and // are generated by computing a projection of each dataset point onto // a line. The line can be oriented arbitrarily. A typical example is // to generate scalars based on elevation or height above a plane. #ifndef __vtkMyElevationFilter_h #define __vtkMyElevationFilter_h #include "vtkElevationFilter.h" class VTK_EXPORT vtkMyElevationFilter : public vtkElevationFilter { public: static vtkMyElevationFilter* New(); vtkTypeRevisionMacro(vtkMyElevationFilter, vtkElevationFilter); void PrintSelf(ostream& os, vtkIndent indent); protected: vtkMyElevationFilter(); ~vtkMyElevationFilter(); private: vtkMyElevationFilter(const vtkMyElevationFilter&); // Not implemented. void operator=(const vtkMyElevationFilter&); // Not implemented. }; #endif
[ "clinton@elemtech.com" ]
clinton@elemtech.com
7cdca2bb3d243af015d8390a5593b9bc58443462
b9bafbcc0550b255d2d8aa46a74ebc8007e7d2db
/src/shared/platform_windows.cc
9b2e088c5022d95f65cf44761cc0f42cabdbfe2a
[]
no_license
aam/fletch
1e9aaed0c9fa4ee605c9aedf81e93068dfdc4ec0
846f14b6536fa95cf7ff7ec3ef176d253a3afc15
refs/heads/master
2021-01-15T14:36:16.639992
2016-01-14T15:26:21
2016-01-14T15:26:21
34,838,309
0
0
null
2015-04-30T06:34:36
2015-04-30T06:34:36
null
UTF-8
C++
false
false
7,206
cc
// Copyright (c) 2015, the Fletch project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE.md file. #if defined(FLETCH_TARGET_OS_WIN) #include "src/shared/platform.h" // NOLINT #include <winsock2.h> #include <stdlib.h> #include <malloc.h> #include "src/shared/utils.h" namespace fletch { static uint64 time_launch; void GetPathOfExecutable(char* path, size_t path_length) { HMODULE hModule = GetModuleHandle(NULL); if (hModule != NULL) { DWORD result = GetModuleFileName(hModule, path, path_length); if (result == 0 || result == path_length) { FATAL("GetModuleFileName failed"); } } else { FATAL("GetModuleHandle for exe failed"); } } void Platform::Setup() { time_launch = GetTickCount64(); #if defined(FLETCH_ENABLE_LIVE_CODING) WSADATA wsa_data; int status = WSAStartup(MAKEWORD(2, 2), &wsa_data); if (status != 0) { FATAL1("Unable to initialize Windows Sockets [error #%d].", status); } #endif } void Platform::TearDown() { #if defined(FLETCH_ENABLE_LIVE_CODING) WSACleanup(); #endif } uint64 Platform::GetMicroseconds() { SYSTEMTIME sys_time; FILETIME file_time; ULARGE_INTEGER milliseconds; // On Windows 8+ we could maybe also use GetSystemTimePreciseAsFileTime. GetSystemTime(&sys_time); SystemTimeToFileTime(&sys_time, &file_time); milliseconds.LowPart = file_time.dwLowDateTime; milliseconds.HighPart = file_time.dwHighDateTime; return milliseconds.QuadPart / 10; } uint64 Platform::GetProcessMicroseconds() { // Assume now is past time_launch. return (GetTickCount64() - time_launch) / 10; } int Platform::GetNumberOfHardwareThreads() { static int hardware_threads_cache_ = -1; if (hardware_threads_cache_ = -1) { SYSTEM_INFO info; GetSystemInfo(&info); hardware_threads_cache_ = info.dwNumberOfProcessors; } return hardware_threads_cache_; } // Load file at 'uri'. List<uint8> Platform::LoadFile(const char* name) { // Open the file. HANDLE file = CreateFile(name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); // TODO(herhut): Use FormatMessage to provide proper error messages below. if (file == INVALID_HANDLE_VALUE) { Print::Error("Cannot open file '%s' for reading.\n%d.\n", name, GetLastError()); return List<uint8>(); } // Determine the size of the file. LARGE_INTEGER size; if (!GetFileSizeEx(file, &size)) { Print::Error("Cannot get file size for file '%s'.\n%d.\n", name, GetLastError()); CloseHandle(file); return List<uint8>(); } if (size.HighPart != 0) { Print::Error("File '%s' too big (%l bytes) to read..\n", name, size.QuadPart); CloseHandle(file); return List<uint8>(); } // Read in the entire file. uint8* buffer = static_cast<uint8*>(malloc(size.LowPart)); if (buffer == NULL) { Print::Error("Cannot allocate %d bytes for file '%s'.\n", size.LowPart, name); CloseHandle(file); return List<uint8>(); } DWORD read; bool result = ReadFile(file, buffer, size.LowPart, &read, NULL); CloseHandle(file); if (!result || read != size.LowPart) { Print::Error("Unable to read entire file '%s'.\n%s.\n", name, GetLastError()); return List<uint8>(); } return List<uint8>(buffer, read); } bool Platform::StoreFile(const char* uri, List<uint8> bytes) { // Open the file. // TODO(herhut): Actually handle Uris. HANDLE file = CreateFile(uri, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); // TODO(herhut): Use FormatMessage to provide proper error messages below. if (file == INVALID_HANDLE_VALUE) { Print::Error("Cannot open file '%s' for writing.\n%d.\n", uri, GetLastError()); return false; } DWORD written; bool result = WriteFile(file, bytes.data(), bytes.length(), &written, NULL); CloseHandle(file); if (!result || written != bytes.length()) { Print::Error("Unable to write entire file '%s'.\n%s.\n", uri, GetLastError()); return false; } return true; } bool Platform::WriteText(const char* uri, const char* text, bool append) { // Open the file. // TODO(herhut): Actually handle Uris. HANDLE file = CreateFile(uri, append ? FILE_APPEND_DATA : GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); // TODO(herhut): Use FormatMessage to provide proper error messages below. if (file == INVALID_HANDLE_VALUE) { Print::Error("Cannot open file '%s' for writing.\n%d.\n", uri, GetLastError()); return false; } DWORD written; int length = lstrlen(text); bool result = WriteFile(file, text, length, &written, NULL); CloseHandle(file); if (!result || written != length) { Print::Error("Unable to write text to file '%s'.\n%s.\n", uri, GetLastError()); return false; } return true; } int Platform::GetLocalTimeZoneOffset() { TIME_ZONE_INFORMATION info; DWORD result = GetTimeZoneInformation(&info); LONG bias = info.Bias; if (result == TIME_ZONE_ID_STANDARD) { // Add the standard time bias. bias += info.StandardBias; } else if (result == TIME_ZONE_ID_DAYLIGHT) { // Add the daylight time bias. bias += info.DaylightBias; } // Even if the offset was 24 hours it would still easily fit into 32 bits. // Note that Windows and Dart disagree on the sign. return static_cast<int>(-bias); } const char* Platform::GetTimeZoneName(int64_t seconds_since_epoch) { // TODO(herhut): Not sure how to compute this without implementing it // explicitly. For now, return the name at this point in time. TIME_ZONE_INFORMATION info; static char name[64]; size_t converted; DWORD result = GetTimeZoneInformation(&info); wcstombs_s( &converted, name, 64, result == TIME_ZONE_ID_DAYLIGHT ? info.DaylightName : info.StandardName, _TRUNCATE); return name; } int Platform::GetTimeZoneOffset(int64_t seconds_since_epoch) { // TODO(herhut): There is no API in Windows for this it seems. UNIMPLEMENTED(); return 0; } void Platform::Exit(int exit_code) { exit(exit_code); } void Platform::ScheduleAbort() { static bool failed = false; if (!failed) atexit(abort); failed = true; } void Platform::ImmediateAbort() { abort(); } int Platform::GetPid() { return static_cast<int>(GetCurrentProcessId()); } int Platform::GetLastError() { return GetLastError(); } void Platform::SetLastError(int value) { SetLastError(value); } VirtualMemory::VirtualMemory(int size) : size_(size) { UNIMPLEMENTED(); } VirtualMemory::~VirtualMemory() { UNIMPLEMENTED(); } bool VirtualMemory::IsReserved() const { UNIMPLEMENTED(); return false; } bool VirtualMemory::Commit(uword address, int size, bool executable) { UNIMPLEMENTED(); return false; } bool VirtualMemory::Uncommit(uword address, int size) { UNIMPLEMENTED(); return false; } } // namespace fletch #endif // defined(FLETCH_TARGET_OS_WIN)
[ "herhut@google.com" ]
herhut@google.com
a6f103fee0397bbce3795f647834881df712c86d
a5d00f40c2de5189e82f4fcd779fa7e5d4517cf9
/shovel.cpp
fcaa5b0eade09763547c61790d68ae51b7d577ba
[]
no_license
AymanMagdy/Problem-Solving
f7d018a261ddfdacd48c2c63bb092fe6fd821996
383055a4adc6a008610baed77b2bff3304c153a8
refs/heads/master
2020-05-05T12:30:12.831105
2019-11-21T09:30:19
2019-11-21T09:30:19
180,031,446
0
0
null
null
null
null
UTF-8
C++
false
false
486
cpp
// The problem's name : Shovel // The problem's link : http://codeforces.com/contest/732/problem/A #include<iostream> using namespace std; int main(){ int k, r, sum=1; cin>>k>>r; while(true){ // if the mutplying's 1st digit equals to the givin r || equals to 0; // or if(bill+=k%10) == r || (bill+=k%10) == 0; if((k*sum%10) == r || (k*sum%10) == 0){ cout<<sum<<endl; return 0; } ++sum; } }
[ "magdia883@icloud.com" ]
magdia883@icloud.com
1a9d5a9bcce4c42e56db7b6cee3ab798bb41a708
1a17167c38dc9a12c1f72dd0f3ae7288f5cd7da0
/Source/ThirdParty/angle/third_party/deqp/src/external/vulkancts/modules/vulkan/geometry/vktGeometryLayeredRenderingTests.cpp
d3326dac20484f39929aa11ba7f6f837e2033a55
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause", "Zlib", "LicenseRef-scancode-khronos", "BSL-1.0", "BSD-2-Clause" ]
permissive
elix22/Urho3D
c57c7ecb58975f51fabb95bcc4330bc5b0812de7
99902ae2a867be0d6dbe4c575f9c8c318805ec64
refs/heads/master
2023-06-01T01:19:57.155566
2021-12-07T16:47:20
2021-12-07T17:46:58
165,504,739
21
4
MIT
2021-11-05T01:02:08
2019-01-13T12:51:17
C++
UTF-8
C++
false
false
86,842
cpp
/*------------------------------------------------------------------------ * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2019 Google Inc. * Copyright (c) 2019 The Khronos Group Inc. * Copyright (c) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Geometry shader layered rendering tests *//*--------------------------------------------------------------------*/ #include "vktGeometryLayeredRenderingTests.hpp" #include "vktTestCase.hpp" #include "vktTestCaseUtil.hpp" #include "vktGeometryTestsUtil.hpp" #include "vkPrograms.hpp" #include "vkStrUtil.hpp" #include "vkQueryUtil.hpp" #include "vkMemUtil.hpp" #include "vkRefUtil.hpp" #include "vkBarrierUtil.hpp" #include "vkTypeUtil.hpp" #include "vkImageUtil.hpp" #include "vkBuilderUtil.hpp" #include "vkCmdUtil.hpp" #include "vkObjUtil.hpp" #include "deStringUtil.hpp" #include "deUniquePtr.hpp" #include "tcuTextureUtil.hpp" #include "tcuVectorUtil.hpp" #include "tcuTestLog.hpp" namespace vkt { namespace geometry { namespace { using namespace vk; using de::MovePtr; using de::UniquePtr; using tcu::Vec4; using tcu::IVec3; enum TestType { TEST_TYPE_DEFAULT_LAYER, // !< draw to default layer TEST_TYPE_SINGLE_LAYER, // !< draw to single layer TEST_TYPE_ALL_LAYERS, // !< draw all layers TEST_TYPE_DIFFERENT_CONTENT, // !< draw different content to different layers TEST_TYPE_LAYER_ID, // !< draw to all layers, verify gl_Layer fragment input TEST_TYPE_INVOCATION_PER_LAYER, // !< draw to all layers, one invocation per layer TEST_TYPE_MULTIPLE_LAYERS_PER_INVOCATION, // !< draw to all layers, multiple invocations write to multiple layers TEST_TYPE_LAYERED_READBACK, // !< draw to two layers multiple times TEST_TYPE_SECONDARY_CMD_BUFFER // !< layered rendering using secondary command buffer }; struct ImageParams { VkImageViewType viewType; VkExtent3D size; deUint32 numLayers; }; struct TestParams { TestType testType; ImageParams image; bool inheritFramebuffer; }; const float s_colors[][4] = { { 1.0f, 1.0f, 1.0f, 1.0f }, // white { 1.0f, 0.0f, 0.0f, 1.0f }, // red { 0.0f, 1.0f, 0.0f, 1.0f }, // green { 0.0f, 0.0f, 1.0f, 1.0f }, // blue { 1.0f, 1.0f, 0.0f, 1.0f }, // yellow { 1.0f, 0.0f, 1.0f, 1.0f }, // magenta }; const tcu::Vec4 secondaryCmdBufClearColors[] = { tcu::Vec4(1.0f, 0.0f, 0.0f, 1.0f), tcu::Vec4(0.0f, 1.0f, 0.0f, 1.0f), tcu::Vec4(0.0f, 0.0f, 1.0f, 1.0f), tcu::Vec4(1.0f, 1.0f, 0.0f, 1.0f), tcu::Vec4(0.0f, 1.0f, 1.0f, 1.0f), tcu::Vec4(1.0f, 0.0f, 1.0f, 1.0f) }; tcu::Vec4 scaleColor(const tcu::Vec4& color, float factor) { return tcu::Vec4(color[0] * factor, color[1] * factor, color[2] * factor, color[3]); } deUint32 getTargetLayer (const ImageParams& imageParams) { if (imageParams.viewType == VK_IMAGE_VIEW_TYPE_3D) return imageParams.size.depth / 2; else return imageParams.numLayers / 2; } std::string getShortImageViewTypeName (const VkImageViewType imageViewType) { std::string s(getImageViewTypeName(imageViewType)); return de::toLower(s.substr(19)); } VkImageType getImageType (const VkImageViewType viewType) { switch (viewType) { case VK_IMAGE_VIEW_TYPE_1D: case VK_IMAGE_VIEW_TYPE_1D_ARRAY: return VK_IMAGE_TYPE_1D; case VK_IMAGE_VIEW_TYPE_2D: case VK_IMAGE_VIEW_TYPE_2D_ARRAY: case VK_IMAGE_VIEW_TYPE_CUBE: case VK_IMAGE_VIEW_TYPE_CUBE_ARRAY: return VK_IMAGE_TYPE_2D; case VK_IMAGE_VIEW_TYPE_3D: return VK_IMAGE_TYPE_3D; default: DE_ASSERT(0); return VK_IMAGE_TYPE_LAST; } } VkFormat getStencilBufferFormat(VkFormat depthStencilImageFormat) { const tcu::TextureFormat tcuFormat = mapVkFormat(depthStencilImageFormat); const VkFormat result = (tcuFormat.order == tcu::TextureFormat::S || tcuFormat.order == tcu::TextureFormat::DS) ? VK_FORMAT_S8_UINT : VK_FORMAT_UNDEFINED; DE_ASSERT(result != VK_FORMAT_UNDEFINED); return result; } inline bool isCubeImageViewType (const VkImageViewType viewType) { return viewType == VK_IMAGE_VIEW_TYPE_CUBE || viewType == VK_IMAGE_VIEW_TYPE_CUBE_ARRAY; } void checkImageFormatProperties (const InstanceInterface& vki, const VkPhysicalDevice& physDevice, const VkImageType& imageType, const VkImageTiling& imageTiling, const VkImageUsageFlags imageUsageFlags, const VkImageCreateFlags imageCreateFlags, const VkFormat format, const VkExtent3D& requiredSize, const deUint32 requiredLayers) { VkImageFormatProperties imageFormatProperties; VkResult result; deMemset(&imageFormatProperties, 0, sizeof(imageFormatProperties)); result = vki.getPhysicalDeviceImageFormatProperties(physDevice, format, imageType, imageTiling, imageUsageFlags, imageCreateFlags, &imageFormatProperties); if (result != VK_SUCCESS || imageFormatProperties.maxArrayLayers < requiredLayers || imageFormatProperties.maxExtent.height < requiredSize.height || imageFormatProperties.maxExtent.width < requiredSize.width || imageFormatProperties.maxExtent.depth < requiredSize.depth) { TCU_THROW(NotSupportedError, "Depth/stencil format is not supported"); } } VkImageCreateInfo makeImageCreateInfo (const VkImageCreateFlags flags, const VkImageType type, const VkFormat format, const VkExtent3D size, const deUint32 numLayers, const VkImageUsageFlags usage) { const VkImageCreateInfo imageParams = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; flags, // VkImageCreateFlags flags; type, // VkImageType imageType; format, // VkFormat format; size, // VkExtent3D extent; 1u, // deUint32 mipLevels; numLayers, // deUint32 arrayLayers; VK_SAMPLE_COUNT_1_BIT, // VkSampleCountFlagBits samples; VK_IMAGE_TILING_OPTIMAL, // VkImageTiling tiling; usage, // VkImageUsageFlags usage; VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode; 0u, // deUint32 queueFamilyIndexCount; DE_NULL, // const deUint32* pQueueFamilyIndices; VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout initialLayout; }; return imageParams; } Move<VkRenderPass> makeRenderPass (const DeviceInterface& vk, const VkDevice device, const VkFormat colorFormat, const VkFormat dsFormat, const bool useDepthStencil) { return vk::makeRenderPass(vk, device, colorFormat, useDepthStencil ? dsFormat : VK_FORMAT_UNDEFINED, VK_ATTACHMENT_LOAD_OP_LOAD); } Move<VkRenderPass> makeRenderPassWithSelfDependency (const DeviceInterface& vk, const VkDevice device, const VkFormat colorFormat) { const VkAttachmentDescription attachmentDescription = { (VkAttachmentDescriptionFlags)0, // VkAttachmentDescriptionFlags flags colorFormat, // VkFormat format VK_SAMPLE_COUNT_1_BIT, // VkSampleCountFlagBits samples VK_ATTACHMENT_LOAD_OP_CLEAR, // VkAttachmentLoadOp loadOp VK_ATTACHMENT_STORE_OP_STORE, // VkAttachmentStoreOp storeOp VK_ATTACHMENT_LOAD_OP_DONT_CARE, // VkAttachmentLoadOp stencilLoadOp VK_ATTACHMENT_STORE_OP_DONT_CARE, // VkAttachmentStoreOp stencilStoreOp VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout initialLayout VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // VkImageLayout finalLayout }; const VkAttachmentReference colorAttachmentRef = { 0u, // deUint32 attachment VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // VkImageLayout layout }; const VkSubpassDescription subpassDescription = { (VkSubpassDescriptionFlags)0, // VkSubpassDescriptionFlags flags VK_PIPELINE_BIND_POINT_GRAPHICS, // VkPipelineBindPoint pipelineBindPoint 0u, // deUint32 inputAttachmentCount DE_NULL, // const VkAttachmentReference* pInputAttachments 1u, // deUint32 colorAttachmentCount &colorAttachmentRef, // const VkAttachmentReference* pColorAttachments DE_NULL, // const VkAttachmentReference* pResolveAttachments DE_NULL, // const VkAttachmentReference* pDepthStencilAttachment 0u, // deUint32 preserveAttachmentCount DE_NULL // const deUint32* pPreserveAttachments }; const VkSubpassDependency subpassDependency = { 0u, // deUint32 srcSubpass 0u, // deUint32 dstSubpass VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, // VkPipelineStageFlags srcStageMask VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, // VkPipelineStageFlags dstStageMask VK_ACCESS_SHADER_WRITE_BIT, // VkAccessFlags srcAccessMask VK_ACCESS_SHADER_READ_BIT, // VkAccessFlags dstAccessMask 0u, // VkDependencyFlags dependencyFlags }; const VkRenderPassCreateInfo renderPassInfo = { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, // VkStructureType sType DE_NULL, // const void* pNext (VkRenderPassCreateFlags)0, // VkRenderPassCreateFlags flags 1u, // deUint32 attachmentCount &attachmentDescription, // const VkAttachmentDescription* pAttachments 1u, // deUint32 subpassCount &subpassDescription, // const VkSubpassDescription* pSubpasses 1u, // deUint32 dependencyCount &subpassDependency // const VkSubpassDependency* pDependencies }; return createRenderPass(vk, device, &renderPassInfo); } Move<VkPipeline> makeGraphicsPipeline (const DeviceInterface& vk, const VkDevice device, const VkPipelineLayout pipelineLayout, const VkRenderPass renderPass, const VkShaderModule vertexModule, const VkShaderModule geometryModule, const VkShaderModule fragmentModule, const VkExtent2D renderSize, const bool useDepthStencil = false) { const std::vector<VkViewport> viewports (1, makeViewport(renderSize)); const std::vector<VkRect2D> scissors (1, makeRect2D(renderSize)); const VkStencilOpState stencilOpState = makeStencilOpState( VK_STENCIL_OP_KEEP, // stencil fail VK_STENCIL_OP_INCREMENT_AND_CLAMP, // depth & stencil pass VK_STENCIL_OP_KEEP, // depth only fail VK_COMPARE_OP_ALWAYS, // compare op ~0u, // compare mask ~0u, // write mask 0u); // reference const VkPipelineDepthStencilStateCreateInfo pipelineDepthStencilStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, // VkStructureType sType DE_NULL, // const void* pNext (VkPipelineDepthStencilStateCreateFlags)0, // VkPipelineDepthStencilStateCreateFlags flags useDepthStencil ? VK_TRUE : VK_FALSE, // VkBool32 depthTestEnable useDepthStencil ? VK_TRUE : VK_FALSE, // VkBool32 depthWriteEnable VK_COMPARE_OP_LESS, // VkCompareOp depthCompareOp VK_FALSE, // VkBool32 depthBoundsTestEnable useDepthStencil ? VK_TRUE : VK_FALSE, // VkBool32 stencilTestEnable stencilOpState, // VkStencilOpState front stencilOpState, // VkStencilOpState back 0.0f, // float minDepthBounds 1.0f // float maxDepthBounds }; const VkPipelineVertexInputStateCreateInfo vertexInputStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, // VkStructureType sType DE_NULL, // const void* pNext 0u, // VkPipelineVertexInputStateCreateFlags flags 0u, // deUint32 vertexBindingDescriptionCount DE_NULL, // const VkVertexInputBindingDescription* pVertexBindingDescriptions 0u, // deUint32 vertexAttributeDescriptionCount DE_NULL // const VkVertexInputAttributeDescription* pVertexAttributeDescriptions }; return vk::makeGraphicsPipeline(vk, // const DeviceInterface& vk device, // const VkDevice device pipelineLayout, // const VkPipelineLayout pipelineLayout vertexModule, // const VkShaderModule vertexShaderModule DE_NULL, // const VkShaderModule tessellationControlModule DE_NULL, // const VkShaderModule tessellationEvalModule geometryModule, // const VkShaderModule geometryShaderModule fragmentModule, // const VkShaderModule fragmentShaderModule renderPass, // const VkRenderPass renderPass viewports, // const std::vector<VkViewport>& viewports scissors, // const std::vector<VkRect2D>& scissors VK_PRIMITIVE_TOPOLOGY_POINT_LIST, // const VkPrimitiveTopology topology 0u, // const deUint32 subpass 0u, // const deUint32 patchControlPoints &vertexInputStateInfo, // const VkPipelineVertexInputStateCreateInfo* vertexInputStateCreateInfo DE_NULL, // const VkPipelineRasterizationStateCreateInfo* rasterizationStateCreateInfo DE_NULL, // const VkPipelineMultisampleStateCreateInfo* multisampleStateCreateInfo &pipelineDepthStencilStateInfo); // const VkPipelineDepthStencilStateCreateInfo* depthStencilStateCreateInfo } Move<VkFramebuffer> makeFramebuffer (const DeviceInterface& vk, const VkDevice device, const VkRenderPass renderPass, const VkImageView* pAttachments, const deUint32 attachmentsCount, const deUint32 width, const deUint32 height, const deUint32 layers) { const VkFramebufferCreateInfo framebufferInfo = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; (VkFramebufferCreateFlags)0, // VkFramebufferCreateFlags flags; renderPass, // VkRenderPass renderPass; attachmentsCount, // uint32_t attachmentCount; pAttachments, // const VkImageView* pAttachments; width, // uint32_t width; height, // uint32_t height; layers, // uint32_t layers; }; return createFramebuffer(vk, device, &framebufferInfo); } void copyLayeredImageToBuffer(const DeviceInterface& vk, VkCommandBuffer cmdBuffer, VkImage image, VkBuffer buffer, const ImageParams& imageParams) { // Image read barrier { const VkImageSubresourceRange colorSubresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, imageParams.numLayers); const VkImageMemoryBarrier barrier = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // VkStructureType sType DE_NULL, // const void* pNext VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // VkAccessFlags outputMask VK_ACCESS_TRANSFER_READ_BIT, // VkAccessFlags inputMask VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // VkImageLayout oldLayout VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, // VkImageLayout newLayout VK_QUEUE_FAMILY_IGNORED, // deUint32 srcQueueFamilyIndex VK_QUEUE_FAMILY_IGNORED, // deUint32 destQueueFamilyIndex image, // VkImage image colorSubresourceRange // VkImageSubresourceRange subresourceRange }; vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, 1u, &barrier); } // Color image -> host buffer { const VkBufferImageCopy region = { 0ull, // VkDeviceSize bufferOffset 0u, // deUint32 bufferRowLength 0u, // deUint32 bufferImageHeight makeImageSubresourceLayers(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 0u, imageParams.numLayers), // VkImageSubresourceLayers imageSubresource makeOffset3D(0, 0, 0), // VkOffset3D imageOffset imageParams.size // VkExtent3D imageExtent }; vk.cmdCopyImageToBuffer(cmdBuffer, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, buffer, 1u, &region); } // Buffer write barrier { const VkBufferMemoryBarrier barrier = { VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, // VkStructureType sType DE_NULL, // const void* pNext VK_ACCESS_TRANSFER_WRITE_BIT, // VkAccessFlags srcAccessMask VK_ACCESS_HOST_READ_BIT, // VkAccessFlags dstAccessMask VK_QUEUE_FAMILY_IGNORED, // deUint32 srcQueueFamilyIndex VK_QUEUE_FAMILY_IGNORED, // deUint32 dstQueueFamilyIndex buffer, // VkBuffer buffer 0ull, // VkDeviceSize offset VK_WHOLE_SIZE // VkDeviceSize size }; vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0u, 0u, DE_NULL, 1u, &barrier, DE_NULL, 0u); } } //! Convenience wrapper to access 1D, 2D, and 3D image layers/slices in a uniform way. class LayeredImageAccess { public: static LayeredImageAccess create (const VkImageType type, const VkFormat format, const VkExtent3D size, const deUint32 numLayers, const void* pData) { if (type == VK_IMAGE_TYPE_1D) return LayeredImageAccess(format, size.width, numLayers, pData); else return LayeredImageAccess(type, format, size, numLayers, pData); } inline tcu::ConstPixelBufferAccess getLayer (const int layer) const { return tcu::getSubregion(m_wholeImage, 0, (m_1dModifier * layer), ((~m_1dModifier & 1) * layer), m_width, m_height, 1); } inline int getNumLayersOrSlices (void) const { return m_layers; } private: // Specialized for 1D images. LayeredImageAccess (const VkFormat format, const deUint32 width, const deUint32 numLayers, const void* pData) : m_width (static_cast<int>(width)) , m_height (1) , m_1dModifier (1) , m_layers (numLayers) , m_wholeImage (tcu::ConstPixelBufferAccess(mapVkFormat(format), m_width, m_layers, 1, pData)) { } LayeredImageAccess (const VkImageType type, const VkFormat format, const VkExtent3D size, const deUint32 numLayers, const void* pData) : m_width (static_cast<int>(size.width)) , m_height (static_cast<int>(size.height)) , m_1dModifier (0) , m_layers (static_cast<int>(type == VK_IMAGE_TYPE_3D ? size.depth : numLayers)) , m_wholeImage (tcu::ConstPixelBufferAccess(mapVkFormat(format), m_width, m_height, m_layers, pData)) { } const int m_width; const int m_height; const int m_1dModifier; const int m_layers; const tcu::ConstPixelBufferAccess m_wholeImage; }; inline bool compareColors (const Vec4& colorA, const Vec4& colorB, const Vec4& threshold) { return tcu::allEqual( tcu::lessThan(tcu::abs(colorA - colorB), threshold), tcu::BVec4(true, true, true, true)); } bool verifyImageSingleColoredRow (tcu::TestLog& log, const tcu::ConstPixelBufferAccess image, const float rowWidthRatio, const tcu::Vec4& barColor, bool topRightCleared = false, bool bottomRightCleared = false) { DE_ASSERT(rowWidthRatio > 0.0f); const Vec4 black (0.0f, 0.0f, 0.0f, 1.0f); const Vec4 green (0.0f, 1.0f, 0.0f, 1.0f); const Vec4 red (1.0f, 0.0f, 0.0f, 1.0f); const Vec4 brown (0.5f, 0.25f, 0.0f, 1.0f); const Vec4 threshold (0.02f); const int barLength = static_cast<int>(rowWidthRatio * static_cast<float>(image.getWidth())); const int barLengthThreshold = 1; tcu::TextureLevel errorMask (image.getFormat(), image.getWidth(), image.getHeight()); tcu::PixelBufferAccess errorMaskAccess = errorMask.getAccess(); tcu::clear(errorMask.getAccess(), green); log << tcu::TestLog::Message << "Expecting all pixels with distance less or equal to (about) " << barLength << " pixels from left border to be of color " << barColor.swizzle(0, 1, 2) << "." << tcu::TestLog::EndMessage; bool allPixelsOk = true; for (int y = 0; y < image.getHeight(); ++y) for (int x = 0; x < image.getWidth(); ++x) { const Vec4 color = image.getPixel(x, y); const bool isBlack = compareColors(color, black, threshold); const bool isBrown = compareColors(color, brown, threshold); const bool isColor = compareColors(color, barColor, threshold); const bool isOutsideColor = ((topRightCleared && y < image.getHeight() / 2) || (bottomRightCleared && y >= image.getHeight() / 2)) ? isBrown : isBlack; bool isOk; if (x <= barLength - barLengthThreshold) isOk = isColor; else if (x >= barLength + barLengthThreshold) { isOk = isOutsideColor; } else isOk = isColor || isOutsideColor; allPixelsOk &= isOk; if (!isOk) errorMaskAccess.setPixel(red, x, y); } if (allPixelsOk) { log << tcu::TestLog::Message << "Image is valid." << tcu::TestLog::EndMessage << tcu::TestLog::ImageSet("LayerContent", "Layer content") << tcu::TestLog::Image("Layer", "Layer", image) << tcu::TestLog::EndImageSet; return true; } else { log << tcu::TestLog::Message << "Image verification failed. Got unexpected pixels." << tcu::TestLog::EndMessage << tcu::TestLog::ImageSet("LayerContent", "Layer content") << tcu::TestLog::Image("Layer", "Layer", image) << tcu::TestLog::Image("ErrorMask", "Errors", errorMask) << tcu::TestLog::EndImageSet; return false; } log << tcu::TestLog::Image("LayerContent", "Layer content", image); return allPixelsOk; } static bool verifyImageMultipleBars (tcu::TestLog& log, const tcu::ConstPixelBufferAccess image, const float* barWidthRatios, const tcu::Vec4* barValues, const int barsCount, const int numUsedChannels, const std::string& imageTypeName) { const Vec4 green (0.0f, 1.0f, 0.0f, 1.0f); const Vec4 red (1.0f, 0.0f, 0.0f, 1.0f); const Vec4 threshold (0.02f); const tcu::TextureFormat errorMaskFormat (tcu::TextureFormat(tcu::TextureFormat::RGBA, tcu::TextureFormat::UNORM_INT8)); tcu::TextureLevel errorMask (errorMaskFormat, image.getWidth(), image.getHeight()); tcu::PixelBufferAccess errorMaskAccess = errorMask.getAccess(); bool allPixelsOk = true; DE_ASSERT(barsCount > 0); tcu::clear(errorMask.getAccess(), green); // Format information message { int leftBorder = 0; int rightBorder = 0; std::ostringstream str; for (int barNdx = 0; barNdx < barsCount; ++barNdx) { leftBorder = rightBorder; rightBorder = static_cast<int>(barWidthRatios[barNdx] * static_cast<float>(image.getWidth())); DE_ASSERT(leftBorder < rightBorder); str << std::endl << " [" << leftBorder << "," <<rightBorder << "): "; switch (numUsedChannels) { case 1: str << barValues[barNdx][0]; break; case 4: str << barValues[barNdx]; break; default: DE_ASSERT(false); break; } } log << tcu::TestLog::Message << "Expecting " + imageTypeName + " values depending x-axis position to be of following values: " << str.str() << tcu::TestLog::EndMessage; } for (int x = 0; x < image.getWidth(); ++x) { tcu::Vec4 expectedValue = barValues[0]; for (int barNdx = 0; barNdx < barsCount; ++barNdx) { const int rightBorder = static_cast<int>(barWidthRatios[barNdx] * static_cast<float>(image.getWidth())); if (x < rightBorder) { expectedValue = barValues[barNdx]; break; } } for (int y = 0; y < image.getHeight(); ++y) { const tcu::Vec4 realValue = image.getPixel(x, y); bool isOk = false; switch (numUsedChannels) { case 1: isOk = fabs(realValue[0] - expectedValue[0]) < threshold[0]; break; case 4: isOk = compareColors(realValue, expectedValue, threshold); break; default: DE_ASSERT(false); break; } if (!isOk) errorMaskAccess.setPixel(red, x, y); allPixelsOk = allPixelsOk && isOk; } } if (allPixelsOk) { log << tcu::TestLog::Message << "Image is valid." << tcu::TestLog::EndMessage << tcu::TestLog::ImageSet(imageTypeName + "LayerContent", imageTypeName + " Layer Content") << tcu::TestLog::Image("Layer", "Layer", image) << tcu::TestLog::EndImageSet; } else { log << tcu::TestLog::Message << "Image verification failed. Got unexpected pixels." << tcu::TestLog::EndMessage << tcu::TestLog::ImageSet(imageTypeName + "LayerContent", imageTypeName + " Layer Content") << tcu::TestLog::Image("Layer", "Layer", image) << tcu::TestLog::Image("ErrorMask", "Errors", errorMask) << tcu::TestLog::EndImageSet; } return allPixelsOk; } static void convertDepthToColorBufferAccess (const tcu::ConstPixelBufferAccess& inputImage, tcu::PixelBufferAccess& outputImage) { for (int y = 0; y < inputImage.getHeight(); y++) for (int x = 0; x < inputImage.getWidth(); x++) { const float depth = inputImage.getPixDepth(x, y); const tcu::Vec4 color = tcu::Vec4(depth, depth, depth, 1.0f); outputImage.setPixel(color, x, y); } } static void convertStencilToColorBufferAccess (const tcu::ConstPixelBufferAccess& inputImage, tcu::PixelBufferAccess& outputImage, int maxValue) { for (int y = 0; y < inputImage.getHeight(); y++) for (int x = 0; x < inputImage.getWidth(); x++) { const int stencilInt = inputImage.getPixStencil(x, y); const float stencil = (stencilInt < maxValue) ? float(stencilInt) / float(maxValue) : 1.0f; const tcu::Vec4 color = tcu::Vec4(stencil, stencil, stencil, 1.0f); outputImage.setPixel(color, x, y); } } bool verifyEmptyImage (tcu::TestLog& log, const tcu::ConstPixelBufferAccess image) { log << tcu::TestLog::Message << "Expecting empty image" << tcu::TestLog::EndMessage; const Vec4 black (0.0f, 0.0f, 0.0f, 1.0f); const Vec4 threshold (0.02f); for (int y = 0; y < image.getHeight(); ++y) for (int x = 0; x < image.getWidth(); ++x) { const Vec4 color = image.getPixel(x, y); if (!compareColors(color, black, threshold)) { log << tcu::TestLog::Message << "Found (at least) one bad pixel at " << x << "," << y << ". Pixel color is not background color." << tcu::TestLog::EndMessage << tcu::TestLog::ImageSet("LayerContent", "Layer content") << tcu::TestLog::Image("Layer", "Layer", image) << tcu::TestLog::EndImageSet; return false; } } log << tcu::TestLog::Message << "Image is valid" << tcu::TestLog::EndMessage; return true; } bool verifyLayerContent (tcu::TestLog& log, const TestType testType, const tcu::ConstPixelBufferAccess image, const int layerNdx, const int numLayers, const bool depthCheck, const bool stencilCheck) { const Vec4 white (1.0f, 1.0f, 1.0f, 1.0f); const int targetLayer = numLayers / 2; const float variableBarRatio = static_cast<float>(layerNdx) / static_cast<float>(numLayers); switch (testType) { case TEST_TYPE_DEFAULT_LAYER: if (layerNdx == 0) return verifyImageSingleColoredRow(log, image, 0.5f, white); else return verifyEmptyImage(log, image); case TEST_TYPE_SINGLE_LAYER: if (layerNdx == targetLayer) return verifyImageSingleColoredRow(log, image, 0.5f, white); else return verifyEmptyImage(log, image); case TEST_TYPE_ALL_LAYERS: case TEST_TYPE_INVOCATION_PER_LAYER: return verifyImageSingleColoredRow(log, image, 0.5f, s_colors[layerNdx % DE_LENGTH_OF_ARRAY(s_colors)]); case TEST_TYPE_DIFFERENT_CONTENT: case TEST_TYPE_MULTIPLE_LAYERS_PER_INVOCATION: if (layerNdx == 0) return verifyEmptyImage(log, image); else return verifyImageSingleColoredRow(log, image, variableBarRatio, white); case TEST_TYPE_LAYER_ID: { // This code must be in sync with the fragment shader. const tcu::Vec4 layerColor( (layerNdx % 2) == 1 ? 1.0f : 0.5f, ((layerNdx/2) % 2) == 1 ? 1.0f : 0.5f, layerNdx == 0 ? 1.0f : 0.0f, 1.0f); return verifyImageSingleColoredRow(log, image, 0.5f, layerColor); } case TEST_TYPE_LAYERED_READBACK: { const float barWidthRatios[] = { 0.25f, 0.5f, 1.0f }; const int barsCount = DE_LENGTH_OF_ARRAY(barWidthRatios); bool result = false; if (depthCheck) { const std::string checkType = "Depth"; const float pass0depth = static_cast<float>(layerNdx + 1) / static_cast<float>(2 * numLayers); const float pass1depth = static_cast<float>(layerNdx + 0) / static_cast<float>(2 * numLayers); const tcu::Vec4 barDepths[barsCount] = { tcu::Vec4(pass1depth), tcu::Vec4(pass0depth), tcu::Vec4(1.0f) }; tcu::TextureLevel depthAsColorBuffer (tcu::TextureFormat(tcu::TextureFormat::R, tcu::TextureFormat::FLOAT), image.getWidth(), image.getHeight()); tcu::PixelBufferAccess depthAsColor (depthAsColorBuffer); const int numUsedChannels (tcu::getNumUsedChannels(depthAsColor.getFormat().order)); convertDepthToColorBufferAccess(image, depthAsColor); result = verifyImageMultipleBars(log, depthAsColor, barWidthRatios, barDepths, barsCount, numUsedChannels, checkType); } else if (stencilCheck) { const std::string checkType = "Stencil"; const int maxStencilValue = 4; const float pass0stencil = static_cast<float>(1.0f / maxStencilValue); const float pass1stencil = static_cast<float>(2.0f / maxStencilValue); const tcu::Vec4 barStencils[barsCount] = { tcu::Vec4(pass1stencil), tcu::Vec4(pass0stencil), tcu::Vec4(0.0f) }; tcu::TextureLevel stencilAsColorBuffer (tcu::TextureFormat(tcu::TextureFormat::R, tcu::TextureFormat::FLOAT), image.getWidth(), image.getHeight()); tcu::PixelBufferAccess stencilAsColor (stencilAsColorBuffer); const int numUsedChannels (tcu::getNumUsedChannels(stencilAsColor.getFormat().order)); convertStencilToColorBufferAccess(image, stencilAsColor, maxStencilValue); result = verifyImageMultipleBars(log, stencilAsColor, barWidthRatios, barStencils, barsCount, numUsedChannels, checkType); } else { const std::string checkType = "Color"; const tcu::Vec4 baseColor (s_colors[layerNdx % DE_LENGTH_OF_ARRAY(s_colors)]); const tcu::Vec4 barColors[barsCount] = { scaleColor(baseColor, 1.00f), scaleColor(baseColor, 0.50f), scaleColor(baseColor, 0.25f) }; const int numUsedChannels (tcu::getNumUsedChannels(image.getFormat().order)); result = verifyImageMultipleBars(log, image, barWidthRatios, barColors, barsCount, numUsedChannels, checkType); } return result; } case TEST_TYPE_SECONDARY_CMD_BUFFER: { const tcu::Vec4 clearColor = secondaryCmdBufClearColors[layerNdx % DE_LENGTH_OF_ARRAY(secondaryCmdBufClearColors)]; const tcu::Vec4 quadColor = s_colors[layerNdx % DE_LENGTH_OF_ARRAY(s_colors)]; // The first draw: blend clearColor and quadColor const tcu::Vec4 firstDraw = (clearColor + quadColor) * 0.5f; // The second draw: blend previous result and quadColor const tcu::Vec4 secondDraw = (firstDraw + quadColor) * 0.5f; return verifyImageSingleColoredRow(log, image, 0.5f, secondDraw, layerNdx < numLayers / 2, layerNdx >= numLayers / 2); } default: DE_ASSERT(0); return false; }; } std::string getLayerDescription (const VkImageViewType viewType, const int layer) { std::ostringstream str; const int numCubeFaces = 6; if (isCubeImageViewType(viewType)) str << "cube " << (layer / numCubeFaces) << ", face " << (layer % numCubeFaces); else if (viewType == VK_IMAGE_VIEW_TYPE_3D) str << "slice z = " << layer; else str << "layer " << layer; return str.str(); } bool verifyResults (tcu::TestLog& log, const TestParams& params, const VkFormat imageFormat, const void* resultData, const bool depthCheck = false, const bool stencilCheck = false) { const LayeredImageAccess image = LayeredImageAccess::create(getImageType(params.image.viewType), imageFormat, params.image.size, params.image.numLayers, resultData); int numGoodLayers = 0; for (int layerNdx = 0; layerNdx < image.getNumLayersOrSlices(); ++layerNdx) { const tcu::ConstPixelBufferAccess layerImage = image.getLayer(layerNdx); log << tcu::TestLog::Message << "Verifying " << getLayerDescription(params.image.viewType, layerNdx) << tcu::TestLog::EndMessage; if (verifyLayerContent(log, params.testType, layerImage, layerNdx, image.getNumLayersOrSlices(), depthCheck, stencilCheck)) ++numGoodLayers; } return numGoodLayers == image.getNumLayersOrSlices(); } std::string toGlsl (const Vec4& v) { std::ostringstream str; str << "vec4("; for (int i = 0; i < 4; ++i) str << (i != 0 ? ", " : "") << de::floatToString(v[i], 1); str << ")"; return str.str(); } void initPrograms (SourceCollections& programCollection, const TestParams params) { const bool geomOutputColor = (params.testType == TEST_TYPE_ALL_LAYERS || params.testType == TEST_TYPE_INVOCATION_PER_LAYER || params.testType == TEST_TYPE_LAYERED_READBACK || params.testType == TEST_TYPE_SECONDARY_CMD_BUFFER); // Vertex shader { std::ostringstream src; src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n" << "\n" << "void main(void)\n" << "{\n" << "}\n"; programCollection.glslSources.add("vert") << glu::VertexSource(src.str()); } // Geometry shader { const int numLayers = static_cast<int>(params.image.viewType == VK_IMAGE_VIEW_TYPE_3D ? params.image.size.depth : params.image.numLayers); const int maxVertices = (params.testType == TEST_TYPE_DIFFERENT_CONTENT) ? (numLayers + 1) * numLayers : (params.testType == TEST_TYPE_ALL_LAYERS || params.testType == TEST_TYPE_LAYER_ID || params.testType == TEST_TYPE_LAYERED_READBACK || params.testType == TEST_TYPE_SECONDARY_CMD_BUFFER) ? numLayers * 4 : (params.testType == TEST_TYPE_MULTIPLE_LAYERS_PER_INVOCATION) ? 6 : 4; std::ostringstream src; src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n" << "\n"; if (params.testType == TEST_TYPE_LAYERED_READBACK) src << "layout(binding = 0) readonly uniform Input {\n" << " int pass;\n" << "} uInput;\n\n"; if (params.testType == TEST_TYPE_INVOCATION_PER_LAYER || params.testType == TEST_TYPE_MULTIPLE_LAYERS_PER_INVOCATION) src << "layout(points, invocations = " << numLayers << ") in;\n"; else src << "layout(points) in;\n"; src << "layout(triangle_strip, max_vertices = " << maxVertices << ") out;\n" << "\n" << (geomOutputColor ? "layout(location = 0) out vec4 vert_color;\n\n" : "") << "out gl_PerVertex {\n" << " vec4 gl_Position;\n" << "};\n" << "\n" << "void main(void)\n" << "{\n"; std::ostringstream colorTable; { const int numColors = DE_LENGTH_OF_ARRAY(s_colors); colorTable << " const vec4 colors[" << numColors << "] = vec4[" << numColors << "]("; const std::string padding(colorTable.str().length(), ' '); for (int i = 0; i < numColors; ++i) colorTable << (i != 0 ? ",\n" + padding : "") << toGlsl(s_colors[i]); colorTable << ");\n"; } if (params.testType == TEST_TYPE_DEFAULT_LAYER) { src << " gl_Position = vec4(-1.0, -1.0, 0.0, 1.0);\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4(-1.0, 1.0, 0.0, 1.0);\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4( 0.0, -1.0, 0.0, 1.0);\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4( 0.0, 1.0, 0.0, 1.0);\n" << " EmitVertex();\n"; } else if (params.testType == TEST_TYPE_SINGLE_LAYER) { const deUint32 targetLayer = getTargetLayer(params.image); src << " gl_Position = vec4(-1.0, -1.0, 0.0, 1.0);\n" << " gl_Layer = " << targetLayer << ";\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4(-1.0, 1.0, 0.0, 1.0);\n" << " gl_Layer = " << targetLayer << ";\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4( 0.0, -1.0, 0.0, 1.0);\n" << " gl_Layer = " << targetLayer << ";\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4( 0.0, 1.0, 0.0, 1.0);\n" << " gl_Layer = " << targetLayer << ";\n" << " EmitVertex();\n"; } else if (params.testType == TEST_TYPE_ALL_LAYERS || params.testType == TEST_TYPE_SECONDARY_CMD_BUFFER) { src << colorTable.str() << "\n" << " for (int layerNdx = 0; layerNdx < " << numLayers << "; ++layerNdx) {\n" << " const int colorNdx = layerNdx % " << DE_LENGTH_OF_ARRAY(s_colors) << ";\n" << "\n" << " gl_Position = vec4(-1.0, -1.0, 0.0, 1.0);\n" << " gl_Layer = layerNdx;\n" << " vert_color = colors[colorNdx];\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4(-1.0, 1.0, 0.0, 1.0);\n" << " gl_Layer = layerNdx;\n" << " vert_color = colors[colorNdx];\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4( 0.0, -1.0, 0.0, 1.0);\n" << " gl_Layer = layerNdx;\n" << " vert_color = colors[colorNdx];\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4( 0.0, 1.0, 0.0, 1.0);\n" << " gl_Layer = layerNdx;\n" << " vert_color = colors[colorNdx];\n" << " EmitVertex();\n" << " EndPrimitive();\n" << " };\n"; } else if (params.testType == TEST_TYPE_LAYER_ID) { src << " for (int layerNdx = 0; layerNdx < " << numLayers << "; ++layerNdx) {\n" << " gl_Position = vec4(-1.0, -1.0, 0.0, 1.0);\n" << " gl_Layer = layerNdx;\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4(-1.0, 1.0, 0.0, 1.0);\n" << " gl_Layer = layerNdx;\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4( 0.0, -1.0, 0.0, 1.0);\n" << " gl_Layer = layerNdx;\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4( 0.0, 1.0, 0.0, 1.0);\n" << " gl_Layer = layerNdx;\n" << " EmitVertex();\n" << " EndPrimitive();\n" << " };\n"; } else if (params.testType == TEST_TYPE_DIFFERENT_CONTENT) { src << " for (int layerNdx = 0; layerNdx < " << numLayers << "; ++layerNdx) {\n" << " for (int colNdx = 0; colNdx <= layerNdx; ++colNdx) {\n" << " const float posX = float(colNdx) / float(" << numLayers << ") * 2.0 - 1.0;\n" << "\n" << " gl_Position = vec4(posX, 1.0, 0.0, 1.0);\n" << " gl_Layer = layerNdx;\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4(posX, -1.0, 0.0, 1.0);\n" << " gl_Layer = layerNdx;\n" << " EmitVertex();\n" << " }\n" << " EndPrimitive();\n" << " }\n"; } else if (params.testType == TEST_TYPE_INVOCATION_PER_LAYER) { src << colorTable.str() << " const int colorNdx = gl_InvocationID % " << DE_LENGTH_OF_ARRAY(s_colors) << ";\n" << "\n" << " gl_Position = vec4(-1.0, -1.0, 0.0, 1.0);\n" << " gl_Layer = gl_InvocationID;\n" << " vert_color = colors[colorNdx];\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4(-1.0, 1.0, 0.0, 1.0);\n" << " gl_Layer = gl_InvocationID;\n" << " vert_color = colors[colorNdx];\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4( 0.0, -1.0, 0.0, 1.0);\n" << " gl_Layer = gl_InvocationID;\n" << " vert_color = colors[colorNdx];\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4( 0.0, 1.0, 0.0, 1.0);\n" << " gl_Layer = gl_InvocationID;\n" << " vert_color = colors[colorNdx];\n" << " EmitVertex();\n" << " EndPrimitive();\n"; } else if (params.testType == TEST_TYPE_MULTIPLE_LAYERS_PER_INVOCATION) { src << " const int layerA = gl_InvocationID;\n" << " const int layerB = (gl_InvocationID + 1) % " << numLayers << ";\n" << " const float aEnd = float(layerA) / float(" << numLayers << ") * 2.0 - 1.0;\n" << " const float bEnd = float(layerB) / float(" << numLayers << ") * 2.0 - 1.0;\n" << "\n" << " gl_Position = vec4(-1.0, -1.0, 0.0, 1.0);\n" << " gl_Layer = layerA;\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4(-1.0, 1.0, 0.0, 1.0);\n" << " gl_Layer = layerA;\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4(aEnd, -1.0, 0.0, 1.0);\n" << " gl_Layer = layerA;\n" << " EmitVertex();\n" << " EndPrimitive();\n" << "\n" << " gl_Position = vec4(-1.0, 1.0, 0.0, 1.0);\n" << " gl_Layer = layerB;\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4(bEnd, 1.0, 0.0, 1.0);\n" << " gl_Layer = layerB;\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4(bEnd, -1.0, 0.0, 1.0);\n" << " gl_Layer = layerB;\n" << " EmitVertex();\n" << " EndPrimitive();\n"; } else if (params.testType == TEST_TYPE_LAYERED_READBACK) { src << colorTable.str() << " for (int layerNdx = 0; layerNdx < " << numLayers << "; ++layerNdx) {\n" << " const int colorNdx = layerNdx % " << DE_LENGTH_OF_ARRAY(s_colors) << ";\n" << " const vec3 passColor0 = (uInput.pass == 0 ? 0.5 : 1.0) * vec3(colors[colorNdx]);\n" << " const vec4 passColor = vec4(passColor0, 1.0);\n" << " const float posX = (uInput.pass == 0 ? 0.0 : -0.5);\n" << " const float posZ = float(layerNdx + 1 - uInput.pass) / float(" << 2*numLayers << ");\n" << "\n" << " gl_Position = vec4(-1.0, -1.0, posZ, 1.0);\n" << " gl_Layer = layerNdx;\n" << " vert_color = passColor;\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4(-1.0, 1.0, posZ, 1.0);\n" << " gl_Layer = layerNdx;\n" << " vert_color = passColor;\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4(posX, -1.0, posZ, 1.0);\n" << " gl_Layer = layerNdx;\n" << " vert_color = passColor;\n" << " EmitVertex();\n" << "\n" << " gl_Position = vec4(posX, 1.0, posZ, 1.0);\n" << " gl_Layer = layerNdx;\n" << " vert_color = passColor;\n" << " EmitVertex();\n" << "\n" << " EndPrimitive();\n" << " }\n"; } else DE_ASSERT(0); src << "}\n"; // end main programCollection.glslSources.add("geom") << glu::GeometrySource(src.str()); } // Fragment shader { std::string imageViewString; switch (params.image.viewType) { case VK_IMAGE_VIEW_TYPE_1D_ARRAY: imageViewString = "image1DArray"; break; case VK_IMAGE_VIEW_TYPE_2D_ARRAY: imageViewString = "image2DArray"; break; case VK_IMAGE_VIEW_TYPE_CUBE: imageViewString = "imageCube"; break; case VK_IMAGE_VIEW_TYPE_CUBE_ARRAY: imageViewString = "imageCubeArray"; break; default: DE_ASSERT(params.image.viewType == VK_IMAGE_VIEW_TYPE_3D); imageViewString = "image3D"; break; }; std::ostringstream src; src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n" << "\n" << "layout(location = 0) out vec4 o_color;\n" << (geomOutputColor ? "layout(location = 0) in vec4 vert_color;\n" : "") << (params.testType == TEST_TYPE_SECONDARY_CMD_BUFFER ? std::string("layout(set = 0, binding = 0, rgba8) uniform " + imageViewString + " storageImage;\n") : std::string("")) << "\n" << "void main(void)\n" << "{\n"; if (params.testType == TEST_TYPE_LAYER_ID) { // This code must be in sync with verifyLayerContent() src << " o_color = vec4( (gl_Layer % 2) == 1 ? 1.0 : 0.5,\n" << " ((gl_Layer/2) % 2) == 1 ? 1.0 : 0.5,\n" << " gl_Layer == 0 ? 1.0 : 0.0,\n" << " 1.0);\n"; } else if (params.testType == TEST_TYPE_SECONDARY_CMD_BUFFER) { switch (params.image.viewType) { case VK_IMAGE_VIEW_TYPE_1D_ARRAY: src << " ivec2 coord = ivec2(int(gl_FragCoord.x), gl_Layer);\n"; break; default: src << " ivec3 coord = ivec3(int(gl_FragCoord.x), int(gl_FragCoord.y), gl_Layer);\n"; break; }; src << " vec4 src_color = imageLoad(storageImage, coord);\n" << " o_color = (vert_color + src_color) / 2.0;\n" << " imageStore(storageImage, coord, o_color);\n"; } else if (geomOutputColor) src << " o_color = vert_color;\n"; else src << " o_color = vec4(1.0);\n"; src << "}\n"; programCollection.glslSources.add("frag") << glu::FragmentSource(src.str()); } } tcu::TestStatus test (Context& context, const TestParams params) { if (VK_IMAGE_VIEW_TYPE_3D == params.image.viewType && (!isDeviceExtensionSupported(context.getUsedApiVersion(), context.getDeviceExtensions(), "VK_KHR_maintenance1"))) TCU_THROW(NotSupportedError, "Extension VK_KHR_maintenance1 not supported"); const DeviceInterface& vk = context.getDeviceInterface(); const InstanceInterface& vki = context.getInstanceInterface(); const VkDevice device = context.getDevice(); const VkPhysicalDevice physDevice = context.getPhysicalDevice(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkQueue queue = context.getUniversalQueue(); Allocator& allocator = context.getDefaultAllocator(); checkGeometryShaderSupport(vki, physDevice); const VkFormat colorFormat = VK_FORMAT_R8G8B8A8_UNORM; const deUint32 numLayers = (VK_IMAGE_VIEW_TYPE_3D == params.image.viewType ? params.image.size.depth : params.image.numLayers); const Vec4 clearColor = Vec4(0.0f, 0.0f, 0.0f, 1.0f); const VkDeviceSize colorBufferSize = params.image.size.width * params.image.size.height * params.image.size.depth * params.image.numLayers * tcu::getPixelSize(mapVkFormat(colorFormat)); const VkImageCreateFlags imageCreateFlags = (isCubeImageViewType(params.image.viewType) ? VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT : (VkImageCreateFlagBits)0) | (VK_IMAGE_VIEW_TYPE_3D == params.image.viewType ? VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR : (VkImageCreateFlagBits)0); const VkImageViewType viewType = (VK_IMAGE_VIEW_TYPE_3D == params.image.viewType ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : params.image.viewType); const Unique<VkImage> colorImage (makeImage (vk, device, makeImageCreateInfo(imageCreateFlags, getImageType(params.image.viewType), colorFormat, params.image.size, params.image.numLayers, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT))); const UniquePtr<Allocation> colorImageAlloc (bindImage (vk, device, allocator, *colorImage, MemoryRequirement::Any)); const Unique<VkImageView> colorAttachment (makeImageView (vk, device, *colorImage, viewType, colorFormat, makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, numLayers))); const Unique<VkBuffer> colorBuffer (makeBuffer (vk, device, makeBufferCreateInfo(colorBufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT))); const UniquePtr<Allocation> colorBufferAlloc (bindBuffer (vk, device, allocator, *colorBuffer, MemoryRequirement::HostVisible)); const Unique<VkShaderModule> vertexModule (createShaderModule (vk, device, context.getBinaryCollection().get("vert"), 0u)); const Unique<VkShaderModule> geometryModule (createShaderModule (vk, device, context.getBinaryCollection().get("geom"), 0u)); const Unique<VkShaderModule> fragmentModule (createShaderModule (vk, device, context.getBinaryCollection().get("frag"), 0u)); const Unique<VkRenderPass> renderPass (makeRenderPass (vk, device, colorFormat)); const Unique<VkFramebuffer> framebuffer (makeFramebuffer (vk, device, *renderPass, &*colorAttachment, 1u, params.image.size.width, params.image.size.height, numLayers)); const Unique<VkPipelineLayout> pipelineLayout (makePipelineLayout (vk, device)); const Unique<VkPipeline> pipeline (makeGraphicsPipeline (vk, device, *pipelineLayout, *renderPass, *vertexModule, *geometryModule, *fragmentModule, makeExtent2D(params.image.size.width, params.image.size.height))); const Unique<VkCommandPool> cmdPool (createCommandPool (vk, device, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, queueFamilyIndex)); const Unique<VkCommandBuffer> cmdBuffer (allocateCommandBuffer (vk, device, *cmdPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY)); zeroBuffer(vk, device, *colorBufferAlloc, colorBufferSize); beginCommandBuffer(vk, *cmdBuffer); beginRenderPass(vk, *cmdBuffer, *renderPass, *framebuffer, makeRect2D(0, 0, params.image.size.width, params.image.size.height), clearColor); vk.cmdBindPipeline(*cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *pipeline); vk.cmdDraw(*cmdBuffer, 1u, 1u, 0u, 0u); endRenderPass(vk, *cmdBuffer); // Copy color image to buffer copyLayeredImageToBuffer(vk, *cmdBuffer, *colorImage, *colorBuffer, params.image); endCommandBuffer(vk, *cmdBuffer); submitCommandsAndWait(vk, device, queue, *cmdBuffer); invalidateMappedMemoryRange(vk, device, colorBufferAlloc->getMemory(), colorBufferAlloc->getOffset(), colorBufferSize); if (!verifyResults(context.getTestContext().getLog(), params, colorFormat, colorBufferAlloc->getHostPtr())) return tcu::TestStatus::fail("Rendered images are incorrect"); else return tcu::TestStatus::pass("OK"); } tcu::TestStatus testLayeredReadBack (Context& context, const TestParams params) { if (VK_IMAGE_VIEW_TYPE_3D == params.image.viewType && (!isDeviceExtensionSupported(context.getUsedApiVersion(), context.getDeviceExtensions(), "VK_KHR_maintenance1"))) TCU_THROW(NotSupportedError, "Extension VK_KHR_maintenance1 not supported"); const DeviceInterface& vk = context.getDeviceInterface(); const InstanceInterface& vki = context.getInstanceInterface(); const VkDevice device = context.getDevice(); const VkPhysicalDevice physDevice = context.getPhysicalDevice(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkQueue queue = context.getUniversalQueue(); Allocator& allocator = context.getDefaultAllocator(); checkGeometryShaderSupport(vki, physDevice); const size_t passCount = 2; const deUint32 numLayers = (VK_IMAGE_VIEW_TYPE_3D == params.image.viewType ? params.image.size.depth : params.image.numLayers); const VkImageCreateFlags imageCreateFlags = (isCubeImageViewType(params.image.viewType) ? VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT : (VkImageCreateFlagBits)0) | (VK_IMAGE_VIEW_TYPE_3D == params.image.viewType ? VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR : (VkImageCreateFlagBits)0); const VkImageViewType viewType = (VK_IMAGE_VIEW_TYPE_3D == params.image.viewType ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : params.image.viewType); const VkImageType imageType = getImageType(params.image.viewType); const VkExtent2D imageExtent2D = makeExtent2D(params.image.size.width, params.image.size.height); const VkFormat colorFormat = VK_FORMAT_R8G8B8A8_UNORM; const deUint32 colorImagePixelSize = static_cast<deUint32>(tcu::getPixelSize(mapVkFormat(colorFormat))); const VkDeviceSize colorBufferSize = params.image.size.width * params.image.size.height * params.image.size.depth * params.image.numLayers * colorImagePixelSize; const VkImageUsageFlags colorImageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; const bool dsUsed = (VK_IMAGE_VIEW_TYPE_3D != params.image.viewType); const VkFormat dsFormat = VK_FORMAT_D24_UNORM_S8_UINT; const deUint32 dsImagePixelSize = static_cast<deUint32>(tcu::getPixelSize(mapVkFormat(dsFormat))); const VkImageUsageFlags dsImageUsage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; const VkImageAspectFlags dsAspectFlags = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; const VkDeviceSize depthBufferSize = params.image.size.width * params.image.size.height * params.image.size.depth * params.image.numLayers * dsImagePixelSize; const VkFormat stencilBufferFormat = getStencilBufferFormat(dsFormat); const deUint32 stencilPixelSize = static_cast<deUint32>(tcu::getPixelSize(mapVkFormat(stencilBufferFormat))); const VkDeviceSize stencilBufferSize = params.image.size.width * params.image.size.height * params.image.size.depth * params.image.numLayers * stencilPixelSize; checkImageFormatProperties(vki, physDevice, imageType, VK_IMAGE_TILING_OPTIMAL, dsImageUsage, imageCreateFlags, dsFormat, params.image.size, params.image.numLayers); const Unique<VkImage> colorImage (makeImage (vk, device, makeImageCreateInfo(imageCreateFlags, imageType, colorFormat, params.image.size, params.image.numLayers, colorImageUsage))); const UniquePtr<Allocation> colorImageAlloc (bindImage (vk, device, allocator, *colorImage, MemoryRequirement::Any)); const Unique<VkImageView> colorAttachment (makeImageView (vk, device, *colorImage, viewType, colorFormat, makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, numLayers))); const Unique<VkBuffer> colorBuffer (makeBuffer (vk, device, makeBufferCreateInfo(colorBufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT))); const UniquePtr<Allocation> colorBufferAlloc (bindBuffer (vk, device, allocator, *colorBuffer, MemoryRequirement::HostVisible)); const Unique<VkImage> dsImage (makeImage (vk, device, makeImageCreateInfo(imageCreateFlags, imageType, dsFormat, params.image.size, params.image.numLayers, dsImageUsage))); const UniquePtr<Allocation> dsImageAlloc (bindImage (vk, device, allocator, *dsImage, MemoryRequirement::Any)); const Unique<VkImageView> dsAttachment (makeImageView (vk, device, *dsImage, viewType, dsFormat, makeImageSubresourceRange(dsAspectFlags, 0u, 1u, 0u, numLayers))); const Unique<VkBuffer> depthBuffer (makeBuffer (vk, device, makeBufferCreateInfo(depthBufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT))); const UniquePtr<Allocation> depthBufferAlloc (bindBuffer (vk, device, allocator, *depthBuffer, MemoryRequirement::HostVisible)); const Unique<VkBuffer> stencilBuffer (makeBuffer (vk, device, makeBufferCreateInfo(stencilBufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT))); const UniquePtr<Allocation> stencilBufferAlloc (bindBuffer (vk, device, allocator, *stencilBuffer, MemoryRequirement::HostVisible)); const VkImageView attachments[] = {*colorAttachment, *dsAttachment}; const deUint32 attachmentsCount = dsUsed ? DE_LENGTH_OF_ARRAY(attachments) : 1u; const Unique<VkShaderModule> vertexModule (createShaderModule (vk, device, context.getBinaryCollection().get("vert"), 0u)); const Unique<VkShaderModule> geometryModule (createShaderModule (vk, device, context.getBinaryCollection().get("geom"), 0u)); const Unique<VkShaderModule> fragmentModule (createShaderModule (vk, device, context.getBinaryCollection().get("frag"), 0u)); const Unique<VkRenderPass> renderPass (makeRenderPass (vk, device, colorFormat, dsFormat, dsUsed)); const Unique<VkFramebuffer> framebuffer (makeFramebuffer (vk, device, *renderPass, attachments, attachmentsCount, params.image.size.width, params.image.size.height, numLayers)); const Move<VkDescriptorPool> descriptorPool = DescriptorPoolBuilder() .addType(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, passCount) .build(vk, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, passCount); const Move<VkDescriptorSetLayout> descriptorSetLayout = DescriptorSetLayoutBuilder() .addSingleBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_GEOMETRY_BIT) .build(vk, device); const Move<VkDescriptorSet> descriptorSet[] = { makeDescriptorSet(vk, device, *descriptorPool, *descriptorSetLayout), makeDescriptorSet(vk, device, *descriptorPool, *descriptorSetLayout), }; const size_t uniformBufSize = sizeof(deUint32); const VkBufferCreateInfo uniformBufCI = makeBufferCreateInfo(uniformBufSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT); const Move<VkBuffer> uniformBuf[] = { createBuffer(vk, device, &uniformBufCI), createBuffer(vk, device, &uniformBufCI) }; const MovePtr<Allocation> uniformBufAlloc[] = { allocator.allocate(getBufferMemoryRequirements(vk, device, *uniformBuf[0]), MemoryRequirement::HostVisible), allocator.allocate(getBufferMemoryRequirements(vk, device, *uniformBuf[1]), MemoryRequirement::HostVisible), }; const VkDescriptorBufferInfo uniformBufDesc[] = { makeDescriptorBufferInfo(*uniformBuf[0], 0ull, uniformBufSize), makeDescriptorBufferInfo(*uniformBuf[1], 0ull, uniformBufSize), }; const Unique<VkPipelineLayout> pipelineLayout (makePipelineLayout (vk, device, *descriptorSetLayout)); const Unique<VkPipeline> pipeline (makeGraphicsPipeline (vk, device, *pipelineLayout, *renderPass, *vertexModule, *geometryModule, *fragmentModule, imageExtent2D, dsUsed)); const Unique<VkCommandPool> cmdPool (createCommandPool (vk, device, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, queueFamilyIndex)); const Unique<VkCommandBuffer> cmdBuffer (allocateCommandBuffer (vk, device, *cmdPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY)); const VkImageSubresourceRange colorSubresRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, params.image.numLayers); const VkImageSubresourceRange dsSubresRange = makeImageSubresourceRange(dsAspectFlags, 0u, 1u, 0u, params.image.numLayers); const VkImageMemoryBarrier colorPassBarrier = makeImageMemoryBarrier(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, *colorImage, colorSubresRange); const VkImageMemoryBarrier dsPassBarrier = makeImageMemoryBarrier(VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, *dsImage, dsSubresRange); std::string result; beginCommandBuffer(vk, *cmdBuffer); { const VkImageMemoryBarrier colorBarrier = makeImageMemoryBarrier(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, *colorImage, colorSubresRange); const VkImageMemoryBarrier dsBarrier = makeImageMemoryBarrier(VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, *dsImage, dsSubresRange); vk.cmdPipelineBarrier(*cmdBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, 1u, &colorBarrier); if (dsUsed) vk.cmdPipelineBarrier(*cmdBuffer, VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, 1u, &dsBarrier); for (deUint32 layerNdx = 0; layerNdx < numLayers; ++layerNdx) { const deUint32 imageDepth = (VK_IMAGE_VIEW_TYPE_3D == params.image.viewType) ? layerNdx : 0u; const deUint32 layer = (VK_IMAGE_VIEW_TYPE_3D == params.image.viewType) ? 0u : layerNdx; const VkOffset3D imageOffset = makeOffset3D(0u, 0u, imageDepth); const VkExtent3D imageExtent = makeExtent3D(params.image.size.width, params.image.size.height, 1u); // Clear color image with initial value { const tcu::Vec4 clearColor = scaleColor(s_colors[layerNdx % DE_LENGTH_OF_ARRAY(s_colors)], 0.25f); const deUint32 bufferSliceSize = params.image.size.width * params.image.size.height * colorImagePixelSize; const VkDeviceSize bufferOffset = layerNdx * bufferSliceSize; const VkImageSubresourceLayers imageSubresource = makeImageSubresourceLayers(VK_IMAGE_ASPECT_COLOR_BIT, 0u, layer, 1u); const VkBufferImageCopy bufferImageCopyRegion = makeBufferImageCopy(bufferOffset, imageSubresource, imageOffset, imageExtent); fillBuffer(vk, device, *colorBufferAlloc, bufferOffset, bufferSliceSize, colorFormat, clearColor); vk.cmdCopyBufferToImage(*cmdBuffer, *colorBuffer, *colorImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1u, &bufferImageCopyRegion); } // Clear depth image with initial value if (dsUsed) { const float depthValue = 1.0f; const deUint32 bufferSliceSize = params.image.size.width * params.image.size.height * dsImagePixelSize; const VkDeviceSize bufferOffset = layerNdx * bufferSliceSize; const VkImageSubresourceLayers imageSubresource = makeImageSubresourceLayers(VK_IMAGE_ASPECT_DEPTH_BIT, 0u, layer, 1u); const VkBufferImageCopy bufferImageCopyRegion = makeBufferImageCopy(bufferOffset, imageSubresource, imageOffset, imageExtent); fillBuffer(vk, device, *depthBufferAlloc, bufferOffset, bufferSliceSize, dsFormat, depthValue); vk.cmdCopyBufferToImage(*cmdBuffer, *depthBuffer, *dsImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1u, &bufferImageCopyRegion); } // Clear stencil image with initial value if (dsUsed) { const deUint8 stencilValue = 0; const deUint32 bufferSliceSize = params.image.size.width * params.image.size.height * stencilPixelSize; const VkDeviceSize bufferOffset = layerNdx * bufferSliceSize; const VkImageSubresourceLayers imageSubresource = makeImageSubresourceLayers(VK_IMAGE_ASPECT_STENCIL_BIT, 0u, layer, 1u); const VkBufferImageCopy bufferImageCopyRegion = makeBufferImageCopy(bufferOffset, imageSubresource, imageOffset, imageExtent); deUint8* bufferStart = static_cast<deUint8*>((*stencilBufferAlloc).getHostPtr()); deUint8* bufferLayerStart = &bufferStart[bufferOffset]; deMemset(bufferLayerStart, stencilValue, bufferSliceSize); flushMappedMemoryRange(vk, device, stencilBufferAlloc->getMemory(), stencilBufferAlloc->getOffset() + bufferOffset, bufferSliceSize); vk.cmdCopyBufferToImage(*cmdBuffer, *stencilBuffer, *dsImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1u, &bufferImageCopyRegion); } } } // Change images layouts { const VkImageMemoryBarrier colorBarrier = makeImageMemoryBarrier(VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, *colorImage, colorSubresRange); const VkImageMemoryBarrier dsBarrier = makeImageMemoryBarrier(VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, *dsImage, dsSubresRange); vk.cmdPipelineBarrier(*cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, 1u, &colorBarrier); if (dsUsed) vk.cmdPipelineBarrier(*cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, 1u, &dsBarrier); } for (deUint32 pass = 0; pass < passCount; ++pass) { DE_ASSERT(sizeof(pass) == uniformBufSize); VK_CHECK(vk.bindBufferMemory(device, *uniformBuf[pass], uniformBufAlloc[pass]->getMemory(), uniformBufAlloc[pass]->getOffset())); deMemcpy(uniformBufAlloc[pass]->getHostPtr(), &pass, uniformBufSize); flushMappedMemoryRange(vk, device, uniformBufAlloc[pass]->getMemory(), uniformBufAlloc[pass]->getOffset(), VK_WHOLE_SIZE); DescriptorSetUpdateBuilder() .writeSingle(*descriptorSet[pass], DescriptorSetUpdateBuilder::Location::binding(0u), VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, &uniformBufDesc[pass]) .update(vk, device); vk.cmdBindDescriptorSets(*cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *pipelineLayout, 0u, 1u, &*descriptorSet[pass], 0u, DE_NULL); beginRenderPass(vk, *cmdBuffer, *renderPass, *framebuffer, makeRect2D(imageExtent2D)); vk.cmdBindPipeline(*cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *pipeline); vk.cmdDraw(*cmdBuffer, 1u, 1u, 0u, 0u); endRenderPass(vk, *cmdBuffer); vk.cmdPipelineBarrier(*cmdBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, 1u, &colorPassBarrier); if (dsUsed) vk.cmdPipelineBarrier(*cmdBuffer, VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, 1u, &dsPassBarrier); } endCommandBuffer(vk, *cmdBuffer); submitCommandsAndWait(vk, device, queue, *cmdBuffer); zeroBuffer(vk, device, *colorBufferAlloc, colorBufferSize); zeroBuffer(vk, device, *depthBufferAlloc, depthBufferSize); zeroBuffer(vk, device, *stencilBufferAlloc, stencilBufferSize); beginCommandBuffer(vk, *cmdBuffer); { // Copy color image { const VkImageMemoryBarrier preCopyBarrier = makeImageMemoryBarrier(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, *colorImage, colorSubresRange); const VkBufferImageCopy region = makeBufferImageCopy(params.image.size, makeImageSubresourceLayers(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 0u, params.image.numLayers)); const VkBufferMemoryBarrier postCopyBarrier = makeBufferMemoryBarrier(VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT, *colorBuffer, 0ull, VK_WHOLE_SIZE); vk.cmdPipelineBarrier(*cmdBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, 1u, &preCopyBarrier); vk.cmdCopyImageToBuffer(*cmdBuffer, *colorImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, *colorBuffer, 1u, &region); vk.cmdPipelineBarrier(*cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0u, 0u, DE_NULL, 1u, &postCopyBarrier, DE_NULL, 0u); } // Depth/Stencil image copy if (dsUsed) { const VkImageMemoryBarrier preCopyBarrier = makeImageMemoryBarrier(VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, *dsImage, dsSubresRange); const VkBufferImageCopy depthCopyRegion = makeBufferImageCopy(params.image.size, makeImageSubresourceLayers(VK_IMAGE_ASPECT_DEPTH_BIT, 0u, 0u, params.image.numLayers)); const VkBufferImageCopy stencilCopyRegion = makeBufferImageCopy(params.image.size, makeImageSubresourceLayers(VK_IMAGE_ASPECT_STENCIL_BIT, 0u, 0u, params.image.numLayers)); const VkBufferMemoryBarrier postCopyBarriers[] = { makeBufferMemoryBarrier(VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT, *depthBuffer, 0ull, VK_WHOLE_SIZE), makeBufferMemoryBarrier(VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT, *stencilBuffer, 0ull, VK_WHOLE_SIZE), }; vk.cmdPipelineBarrier(*cmdBuffer, VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, 1u, &preCopyBarrier); vk.cmdCopyImageToBuffer(*cmdBuffer, *dsImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, *depthBuffer, 1u, &depthCopyRegion); vk.cmdCopyImageToBuffer(*cmdBuffer, *dsImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, *stencilBuffer, 1u, &stencilCopyRegion); vk.cmdPipelineBarrier(*cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0u, 0u, DE_NULL, DE_LENGTH_OF_ARRAY(postCopyBarriers), postCopyBarriers, DE_NULL, 0u); } } endCommandBuffer(vk, *cmdBuffer); submitCommandsAndWait(vk, device, queue, *cmdBuffer); invalidateMappedMemoryRange(vk, device, colorBufferAlloc->getMemory(), colorBufferAlloc->getOffset(), colorBufferSize); invalidateMappedMemoryRange(vk, device, depthBufferAlloc->getMemory(), depthBufferAlloc->getOffset(), depthBufferSize); invalidateMappedMemoryRange(vk, device, stencilBufferAlloc->getMemory(), stencilBufferAlloc->getOffset(), stencilBufferSize); if (!verifyResults(context.getTestContext().getLog(), params, colorFormat, colorBufferAlloc->getHostPtr())) result += " Color"; if (dsUsed) { if (!verifyResults(context.getTestContext().getLog(), params, dsFormat, depthBufferAlloc->getHostPtr(), true, false)) result += " Depth"; if (!verifyResults(context.getTestContext().getLog(), params, stencilBufferFormat, stencilBufferAlloc->getHostPtr(), false, true)) result += " Stencil"; } if (result.empty()) return tcu::TestStatus::pass("OK"); else return tcu::TestStatus::fail("Following parts of image are incorrect:" + result); } tcu::TestStatus testSecondaryCmdBuffer (Context& context, const TestParams params) { if (VK_IMAGE_VIEW_TYPE_3D == params.image.viewType && (!isDeviceExtensionSupported(context.getUsedApiVersion(), context.getDeviceExtensions(), "VK_KHR_maintenance1"))) { TCU_THROW(NotSupportedError, "Extension VK_KHR_maintenance1 not supported"); } const DeviceInterface& vk = context.getDeviceInterface(); const InstanceInterface& vki = context.getInstanceInterface(); const VkDevice device = context.getDevice(); const VkPhysicalDevice physDevice = context.getPhysicalDevice(); const VkPhysicalDeviceFeatures features = getPhysicalDeviceFeatures(vki, physDevice); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkQueue queue = context.getUniversalQueue(); Allocator& allocator = context.getDefaultAllocator(); checkGeometryShaderSupport(vki, physDevice); if (!features.fragmentStoresAndAtomics) TCU_THROW(NotSupportedError, "Storage image stores not supported in fragment shader"); const VkFormat colorFormat = VK_FORMAT_R8G8B8A8_UNORM; const deUint32 numLayers = (VK_IMAGE_VIEW_TYPE_3D == params.image.viewType ? params.image.size.depth : params.image.numLayers); const Vec4 clearColor = Vec4(0.0f, 0.0f, 0.0f, 1.0f); const VkDeviceSize colorBufferSize = params.image.size.width * params.image.size.height * params.image.size.depth * params.image.numLayers * tcu::getPixelSize(mapVkFormat(colorFormat)); const VkImageCreateFlags imageCreateFlags = (isCubeImageViewType(params.image.viewType) ? VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT : (VkImageCreateFlagBits)0) | (VK_IMAGE_VIEW_TYPE_3D == params.image.viewType ? VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR : (VkImageCreateFlagBits)0); const VkImageViewType viewType = (VK_IMAGE_VIEW_TYPE_3D == params.image.viewType ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : params.image.viewType); const Unique<VkImage> colorImage (makeImage(vk, device, makeImageCreateInfo(imageCreateFlags, getImageType(params.image.viewType), colorFormat, params.image.size, params.image.numLayers, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT))); const UniquePtr<Allocation> colorImageAlloc (bindImage(vk, device, allocator, *colorImage, MemoryRequirement::Any)); const Unique<VkImageView> colorImageView (makeImageView(vk, device, *colorImage, viewType, colorFormat, makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, numLayers))); const Unique<VkImage> offscreenImage (makeImage(vk, device, makeImageCreateInfo(imageCreateFlags, getImageType(params.image.viewType), colorFormat, params.image.size, params.image.numLayers, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT))); const UniquePtr<Allocation> offscreenImageAlloc (bindImage(vk, device, allocator, *offscreenImage, MemoryRequirement::Any)); const Unique<VkImageView> offscreenImageView (makeImageView(vk, device, *offscreenImage, params.image.viewType, colorFormat, makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, params.image.numLayers))); const Unique<VkBuffer> colorBuffer (makeBuffer(vk, device, makeBufferCreateInfo(colorBufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT))); const UniquePtr<Allocation> colorBufferAlloc (bindBuffer(vk, device, allocator, *colorBuffer, MemoryRequirement::HostVisible)); const Move<VkDescriptorPool> descriptorPool = DescriptorPoolBuilder() .addType(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1u) .build(vk, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1u); const Move<VkDescriptorSetLayout> descriptorSetLayout = DescriptorSetLayoutBuilder() .addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_FRAGMENT_BIT) .build(vk, device); const Move<VkDescriptorSet> descriptorSet = makeDescriptorSet(vk, device, *descriptorPool, *descriptorSetLayout); const Unique<VkShaderModule> vertexModule (createShaderModule(vk, device, context.getBinaryCollection().get("vert"), 0u)); const Unique<VkShaderModule> geometryModule (createShaderModule(vk, device, context.getBinaryCollection().get("geom"), 0u)); const Unique<VkShaderModule> fragmentModule (createShaderModule(vk, device, context.getBinaryCollection().get("frag"), 0u)); const Unique<VkRenderPass> renderPass (makeRenderPassWithSelfDependency(vk, device, colorFormat)); const Unique<VkFramebuffer> framebuffer (makeFramebuffer(vk, device, *renderPass, &*colorImageView, 1u, params.image.size.width, params.image.size.height, numLayers)); const Unique<VkPipelineLayout> pipelineLayout (makePipelineLayout(vk, device, *descriptorSetLayout)); const Unique<VkPipeline> pipeline (makeGraphicsPipeline(vk, device, *pipelineLayout, *renderPass, *vertexModule, *geometryModule, *fragmentModule, makeExtent2D(params.image.size.width, params.image.size.height))); const Unique<VkCommandPool> cmdPool (createCommandPool(vk, device, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, queueFamilyIndex)); const Unique<VkCommandBuffer> cmdBuffer (allocateCommandBuffer(vk, device, *cmdPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY)); const Unique<VkCommandBuffer> secondaryCmdBuffer (allocateCommandBuffer(vk, device, *cmdPool, VK_COMMAND_BUFFER_LEVEL_SECONDARY)); zeroBuffer(vk, device, *colorBufferAlloc, colorBufferSize); const VkDescriptorImageInfo imageDescriptorInfo = makeDescriptorImageInfo(DE_NULL, *offscreenImageView, VK_IMAGE_LAYOUT_GENERAL); DescriptorSetUpdateBuilder() .writeSingle(*descriptorSet, DescriptorSetUpdateBuilder::Location::binding(0u), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &imageDescriptorInfo) .update(vk, device); // Clear each layer of storage image { vk::Unique<vk::VkCommandBuffer> clearCmdBuffer (vk::allocateCommandBuffer(vk, device, *cmdPool, vk::VK_COMMAND_BUFFER_LEVEL_PRIMARY)); beginCommandBuffer(vk, *clearCmdBuffer); const vk::VkImageSubresourceRange subresourceRange = { vk::VK_IMAGE_ASPECT_COLOR_BIT, // VkImageAspectFlags aspectMask 0u, // deUint32 baseMipLevel 1u, // deUint32 levelCount 0u, // deUint32 baseArrayLayer params.image.numLayers // deUint32 layerCount }; const vk::VkImageMemoryBarrier preImageBarrier = { vk::VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // VkStructureType sType DE_NULL, // const void* pNext 0u, // VkAccessFlags srcAccessMask vk::VK_ACCESS_TRANSFER_WRITE_BIT, // VkAccessFlags dstAccessMask vk::VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout oldLayout vk::VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, // VkImageLayout newLayout queueFamilyIndex, // deUint32 srcQueueFamilyIndex queueFamilyIndex, // deUint32 dstQueueFamilyIndex *offscreenImage, // VkImage image subresourceRange // VkImageSubresourceRange subresourceRange }; const vk::VkImageMemoryBarrier postImageBarrier = { vk::VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // VkStructureType sType DE_NULL, // const void* pNext vk::VK_ACCESS_TRANSFER_WRITE_BIT, // VkAccessFlags srcAccessMask vk::VK_ACCESS_SHADER_WRITE_BIT, // VkAccessFlags dstAccessMask vk::VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, // VkImageLayout oldLayout vk::VK_IMAGE_LAYOUT_GENERAL, // VkImageLayout newLayout queueFamilyIndex, // deUint32 srcQueueFamilyIndex queueFamilyIndex, // deUint32 dstQueueFamilyIndex *offscreenImage, // VkImage image subresourceRange // VkImageSubresourceRange subresourceRange }; vk.cmdPipelineBarrier(*clearCmdBuffer, vk::VK_PIPELINE_STAGE_HOST_BIT, vk::VK_PIPELINE_STAGE_TRANSFER_BIT, (vk::VkDependencyFlags)0, 0, (const vk::VkMemoryBarrier*)DE_NULL, 0, (const vk::VkBufferMemoryBarrier*)DE_NULL, 1, &preImageBarrier); for (deUint32 layerNdx = 0; layerNdx < numLayers; ++layerNdx) { const deUint32 imageDepth = (VK_IMAGE_VIEW_TYPE_3D == params.image.viewType) ? layerNdx : 0u; const deUint32 layer = (VK_IMAGE_VIEW_TYPE_3D == params.image.viewType) ? 0u : layerNdx; const VkOffset3D imageOffset = makeOffset3D(0u, 0u, imageDepth); const VkExtent3D imageExtent = makeExtent3D(params.image.size.width, params.image.size.height, 1u); { const tcu::Vec4 storageImageClearColor = secondaryCmdBufClearColors[layerNdx % DE_LENGTH_OF_ARRAY(secondaryCmdBufClearColors)]; const deUint32 colorImagePixelSize = static_cast<deUint32>(tcu::getPixelSize(mapVkFormat(colorFormat))); const deUint32 bufferSliceSize = params.image.size.width * params.image.size.height * colorImagePixelSize; const VkDeviceSize bufferOffset = layerNdx * bufferSliceSize; const VkImageSubresourceLayers imageSubresource = makeImageSubresourceLayers(VK_IMAGE_ASPECT_COLOR_BIT, 0u, layer, 1u); const VkBufferImageCopy bufferImageCopyRegion = makeBufferImageCopy(bufferOffset, imageSubresource, imageOffset, imageExtent); fillBuffer(vk, device, *colorBufferAlloc, bufferOffset, bufferSliceSize, colorFormat, storageImageClearColor); vk.cmdCopyBufferToImage(*clearCmdBuffer, *colorBuffer, *offscreenImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1u, &bufferImageCopyRegion); } } vk.cmdPipelineBarrier(*clearCmdBuffer, vk::VK_PIPELINE_STAGE_TRANSFER_BIT, vk::VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, (vk::VkDependencyFlags)0, 0, (const vk::VkMemoryBarrier*)DE_NULL, 0, (const vk::VkBufferMemoryBarrier*)DE_NULL, 1, &postImageBarrier); endCommandBuffer(vk, *clearCmdBuffer); submitCommandsAndWait(vk, device, queue, *clearCmdBuffer); } // Begin secondary command buffer { const VkCommandBufferInheritanceInfo commandBufferInheritanceInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, // VkStructureType sType DE_NULL, // const void* pNext *renderPass, // VkRenderPass renderPass 0u, // deUint32 subpass params.inheritFramebuffer ? *framebuffer : (VkFramebuffer)0, // VkFramebuffer framebuffer VK_FALSE, // VkBool32 occlusionQueryEnable 0u, // VkQueryControlFlags queryFlags 0u // VkQueryPipelineStatisticFlags pipelineStatistics }; const VkCommandBufferBeginInfo commandBufferBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // VkStructureType sType DE_NULL, // const void* pNext VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT | VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT, // VkCommandBufferUsageFlags flags &commandBufferInheritanceInfo // const VkCommandBufferInheritanceInfo* pInheritanceInfo }; VK_CHECK(vk.beginCommandBuffer(*secondaryCmdBuffer, &commandBufferBeginInfo)); } vk.cmdBindDescriptorSets(*secondaryCmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *pipelineLayout, 0u, 1u, &*descriptorSet, 0u, DE_NULL); // Clear framebuffer: upper right corner for half of the layers and bottom right for the others. { const VkClearAttachment clearAttachment = { VK_IMAGE_ASPECT_COLOR_BIT, // VkImageAspectFlags aspectMask 0u, // deUint32 colorAttachment makeClearValueColorF32(0.5f, 0.25, 0.0f, 1.0f) // VkClearValue clearValue }; const VkOffset2D offsetTop = { (deInt32)params.image.size.width / 2, 0 }; const VkOffset2D offsetBottom = { (deInt32)params.image.size.width / 2, (deInt32)params.image.size.height / 2 }; const VkExtent2D extentTop = { params.image.size.width / 2, params.image.size.height / 2 }; const VkExtent2D extentBottom = { params.image.size.width / 2, de::max(params.image.size.height / 2, 1u) }; const VkRect2D rectRightTop = { offsetTop, extentTop }; const VkRect2D rectRightBottom = { offsetBottom, extentBottom }; const VkClearRect rects[] = { { rectRightBottom, // VkRect2D rect numLayers / 2, // deUint32 baseArrayLayer numLayers / 2 // deUint32 layerCount }, { rectRightTop, // VkRect2D rect 0u, // deUint32 baseArrayLayer numLayers / 2 // deUint32 layerCount } }; vk.cmdClearAttachments(*secondaryCmdBuffer, 1u, &clearAttachment, extentTop.height > 0 ? 2u : 1u, rects); } vk.cmdBindPipeline(*secondaryCmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *pipeline); vk.cmdDraw(*secondaryCmdBuffer, 1u, 1u, 0u, 0u); // Barrier between draws { const VkMemoryBarrier barrier = { VK_STRUCTURE_TYPE_MEMORY_BARRIER, // VkStructureType sType DE_NULL, // const void* pNext VK_ACCESS_SHADER_WRITE_BIT, // VkAccessFlags srcAccessMask VK_ACCESS_SHADER_READ_BIT // VkAccessFlags dstAccessMask }; vk.cmdPipelineBarrier(*secondaryCmdBuffer, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0u, 1u, &barrier, 0u, DE_NULL, 0u, DE_NULL); } vk.cmdDraw(*secondaryCmdBuffer, 1u, 1u, 0u, 0u); endCommandBuffer(vk, *secondaryCmdBuffer); beginCommandBuffer(vk, *cmdBuffer); beginRenderPass(vk, *cmdBuffer, *renderPass, *framebuffer, makeRect2D(0, 0, params.image.size.width, params.image.size.height), clearColor, VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS); vk.cmdExecuteCommands(*cmdBuffer, 1u, &(*secondaryCmdBuffer)); endRenderPass(vk, *cmdBuffer); copyLayeredImageToBuffer(vk, *cmdBuffer, *colorImage, *colorBuffer, params.image); endCommandBuffer(vk, *cmdBuffer); submitCommandsAndWait(vk, device, queue, *cmdBuffer); invalidateMappedMemoryRange(vk, device, colorBufferAlloc->getMemory(), colorBufferAlloc->getOffset(), colorBufferSize); if (!verifyResults(context.getTestContext().getLog(), params, colorFormat, colorBufferAlloc->getHostPtr())) return tcu::TestStatus::fail("Rendered images are incorrect"); else return tcu::TestStatus::pass("OK"); } } // anonymous tcu::TestCaseGroup* createLayeredRenderingTests (tcu::TestContext& testCtx) { MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "layered", "Layered rendering tests.")); const struct { TestType test; const char* name; const char* description; } testTypes[] = { { TEST_TYPE_DEFAULT_LAYER, "render_to_default_layer", "Render to the default layer" }, { TEST_TYPE_SINGLE_LAYER, "render_to_one", "Render to one layer" }, { TEST_TYPE_ALL_LAYERS, "render_to_all", "Render to all layers" }, { TEST_TYPE_DIFFERENT_CONTENT, "render_different_content", "Render different data to different layers" }, { TEST_TYPE_LAYER_ID, "fragment_layer", "Read gl_Layer in fragment shader" }, { TEST_TYPE_INVOCATION_PER_LAYER, "invocation_per_layer", "Render to multiple layers with multiple invocations, one invocation per layer" }, { TEST_TYPE_MULTIPLE_LAYERS_PER_INVOCATION, "multiple_layers_per_invocation", "Render to multiple layers with multiple invocations, multiple layers per invocation", }, { TEST_TYPE_LAYERED_READBACK, "readback", "Render to multiple layers with two passes to check LOAD_OP_LOAD capability" }, { TEST_TYPE_SECONDARY_CMD_BUFFER, "secondary_cmd_buffer", "Layered rendering using secondary command buffer" } }; const ImageParams imageParams[] = { { VK_IMAGE_VIEW_TYPE_1D_ARRAY, { 64, 1, 1 }, 4 }, { VK_IMAGE_VIEW_TYPE_2D_ARRAY, { 64, 64, 1 }, 4 }, { VK_IMAGE_VIEW_TYPE_CUBE, { 64, 64, 1 }, 6 }, { VK_IMAGE_VIEW_TYPE_CUBE_ARRAY, { 64, 64, 1 }, 2*6 }, { VK_IMAGE_VIEW_TYPE_3D, { 64, 64, 8 }, 1 } }; for (int imageParamNdx = 0; imageParamNdx < DE_LENGTH_OF_ARRAY(imageParams); ++imageParamNdx) { MovePtr<tcu::TestCaseGroup> viewTypeGroup(new tcu::TestCaseGroup(testCtx, getShortImageViewTypeName(imageParams[imageParamNdx].viewType).c_str(), "")); for (int testTypeNdx = 0; testTypeNdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeNdx) { TestParams params = { testTypes[testTypeNdx].test, imageParams[imageParamNdx], false }; if (testTypes[testTypeNdx].test == TEST_TYPE_LAYERED_READBACK) addFunctionCaseWithPrograms(viewTypeGroup.get(), testTypes[testTypeNdx].name, testTypes[testTypeNdx].description, initPrograms, testLayeredReadBack, params); else if (testTypes[testTypeNdx].test == TEST_TYPE_SECONDARY_CMD_BUFFER) { addFunctionCaseWithPrograms(viewTypeGroup.get(), "secondary_cmd_buffer", testTypes[testTypeNdx].description, initPrograms, testSecondaryCmdBuffer, params); params.inheritFramebuffer = true; addFunctionCaseWithPrograms(viewTypeGroup.get(), "secondary_cmd_buffer_inherit_framebuffer", testTypes[testTypeNdx].description, initPrograms, testSecondaryCmdBuffer, params); } else addFunctionCaseWithPrograms(viewTypeGroup.get(), testTypes[testTypeNdx].name, testTypes[testTypeNdx].description, initPrograms, test, params); } group->addChild(viewTypeGroup.release()); } return group.release(); } } // geometry } // vkt
[ "elix22@gmail.com" ]
elix22@gmail.com
4152a3d28dcaeb56ef18acb6b799741fbb74fe04
dd6fee79066e2dfa74371bd82c87a563dc0c47fd
/contest/ZOJ Monthly, September 2012/I2.cpp
9ad5918d57f8f2f3621048c3b017bf12d6c1ebfa
[]
no_license
mzry1992/workspace
404c31df66a3b15a60dc0f07fff397bf50bcc1dc
9a181419f0d7224e37baa729feaf3bb656544420
refs/heads/master
2021-01-19T12:39:17.854501
2012-12-24T11:13:22
2012-12-24T11:13:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,854
cpp
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> using namespace std; int n,m,l; int id[50][50]; int mp[50][50]; int sx,sy,ex,ey; struct Node { int x,y,sta; int step,ener; Node(){} Node(int _x,int _y,int _sta,int _step,int _ener) { x = _x; y = _y; sta = _sta; step = _step; ener = _ener; } bool operator <(const Node& b)const { if (step == b.step) return ener < b.ener; return step > b.step; } }; const int dx[4] = {0,0,1,-1}; const int dy[4] = {1,-1,0,0}; const int inf = 0x3f3f3f3f; pair<int,int> dist[50][50][32]; int calc() { priority_queue<Node> Q; Q.push(Node(sx,sy,0,0,0)); for (int i = 0;i < n;i++) for (int j = 0;j < m;j++) for (int k = 0;k < 32;k++) dist[i][j][k] = make_pair(inf,-inf); dist[sx][sy][0] = make_pair(0,0); Node now,nxt; while (!Q.empty()) { now = Q.top(); Q.pop(); if (dist[now.x][now.y][now.sta] < make_pair(now.step,-now.ener)) continue; if (now.x == ex && now.y == ey) return now.step; if (now.ener == 0) { now.step++; now.ener = l; } for (int i = 0;i < 4;i++) { nxt.x = now.x+dx[i]; nxt.y = now.y+dy[i]; if (nxt.x < 0 || nxt.x >= n || nxt.y < 0 || nxt.y >= m) continue; if (mp[nxt.x][nxt.y] == -1) continue; nxt.sta = now.sta; nxt.step=now.step; nxt.ener =now.ener-1; if (mp[nxt.x][nxt.y] && (((nxt.sta>>(mp[nxt.x][nxt.y]-1))&1) == 0)) nxt.ener=0; if (id[nxt.x][nxt.y] > 0) nxt.sta |= (1<<(id[nxt.x][nxt.y]-1)); if (dist[nxt.x][nxt.y][nxt.sta] > make_pair(nxt.step,-nxt.ener)) { dist[nxt.x][nxt.y][nxt.sta] = make_pair(nxt.step,-nxt.ener); Q.push(nxt); } } } return -1; } int main() { while (scanf("%d%d%d",&n,&m,&l) != EOF) { for (int i = 0;i < n;i++) for (int j = 0;j < m;j++) { id[i][j] = 0; scanf("%d",&mp[i][j]); while (mp[i][j] >= 6 || mp[i][j] < -1) puts("fuck"); } int tmp; scanf("%d",&tmp); for (int i = 1;i <= tmp;i++) { int x,y; scanf("%d%d",&x,&y); x--; y--; id[x][y] = i; } scanf("%d%d%d%d",&sx,&sy,&ex,&ey); sx--; sy--; ex--; ey--; int ret = calc(); if (ret == -1) puts("We need God's help!"); else printf("%d\n",ret); } return 0; }
[ "muziriyun@gmail.com" ]
muziriyun@gmail.com
04f80616bb47242bb47081b91e25380ee1ead1a4
777a75e6ed0934c193aece9de4421f8d8db01aac
/src/Providers/UNIXProviders/DatabaseService/UNIX_DatabaseService_STUB.hxx
d654ed4254616c7db9747aec9146d01c45a1abca
[ "MIT" ]
permissive
brunolauze/openpegasus-providers-old
20fc13958016e35dc4d87f93d1999db0eae9010a
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
refs/heads/master
2021-01-01T20:05:44.559362
2014-04-30T17:50:06
2014-04-30T17:50:06
19,132,738
1
0
null
null
null
null
UTF-8
C++
false
false
125
hxx
#ifdef PEGASUS_OS_STUB #ifndef __UNIX_DATABASESERVICE_PRIVATE_H #define __UNIX_DATABASESERVICE_PRIVATE_H #endif #endif
[ "brunolauze@msn.com" ]
brunolauze@msn.com
52ff22492a4e4d8c5bb2afd113338f3da94ac796
b66208cedcbca09c44f007dcd0e01e4d5f04a0b1
/frameworks/compile/mclinker/include/mcld/Target/PLT.h
58f7676ac69ee3ed76ba1f3fcb24491af5fd820c
[ "NCSA" ]
permissive
hua3505/AndroidFrameworkSource
2bb848110ec93f650fa8285f7dbb5524ee78e42e
c2fb180c9dbcc657456bab9feb62c351bec7f91e
refs/heads/master
2021-08-31T17:36:52.205076
2017-12-13T09:38:34
2017-12-13T09:38:34
111,386,259
8
1
null
null
null
null
UTF-8
C++
false
false
2,162
h
//===- PLT.h --------------------------------------------------------------===// // // The MCLinker Project // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef MCLD_TARGET_PLT_H_ #define MCLD_TARGET_PLT_H_ #include "mcld/Fragment/TargetFragment.h" #include "mcld/LD/LDSection.h" #include "mcld/LD/SectionData.h" namespace mcld { class LDSection; class ResolveInfo; /** \class PLTEntryDefaultBase * \brief PLTEntryDefaultBase provides the default interface for PLT Entry */ class PLTEntryBase : public TargetFragment { public: explicit PLTEntryBase(SectionData& pParent) : TargetFragment(Fragment::Target, &pParent), m_pValue(NULL) {} virtual ~PLTEntryBase() { free(m_pValue); } void setValue(unsigned char* pValue) { m_pValue = pValue; } const unsigned char* getValue() const { return m_pValue; } // Used by llvm::cast<>. static bool classof(const Fragment* O) { return true; } protected: unsigned char* m_pValue; }; /** \class PLT * \brief Procedure linkage table */ class PLT { public: typedef SectionData::iterator iterator; typedef SectionData::const_iterator const_iterator; template <size_t SIZE, typename EntryBase = PLTEntryBase> class Entry : public EntryBase { public: enum { EntrySize = SIZE }; public: explicit Entry(SectionData& pParent) : EntryBase(pParent) {} virtual ~Entry() {} size_t size() const { return EntrySize; } }; public: explicit PLT(LDSection& pSection); virtual ~PLT(); // finalizeSectionSize - set LDSection size virtual void finalizeSectionSize() = 0; uint64_t addr() const { return m_Section.addr(); } const_iterator begin() const { return m_pSectionData->begin(); } iterator begin() { return m_pSectionData->begin(); } const_iterator end() const { return m_pSectionData->end(); } iterator end() { return m_pSectionData->end(); } protected: LDSection& m_Section; SectionData* m_pSectionData; }; } // namespace mcld #endif // MCLD_TARGET_PLT_H_
[ "wolf.xu@ximalaya.com" ]
wolf.xu@ximalaya.com
eeca3d53c8673c3312cd061455d00dd83d7a345b
0cc407bd7fe8b06a43ace2f17f93014d1bca3f43
/src/accumulatormap.cpp
6009b0d4e43045e9edd6033de171c802d67bb226
[ "MIT" ]
permissive
cruxcoinsource/CruxCoin
cad0b5872361a378b2302a43b659537ff991cc30
2666c3f3a68812e7a619f5e392f10497516ea30d
refs/heads/master
2020-04-03T09:36:35.650085
2019-01-19T12:17:53
2019-01-19T12:17:53
155,170,228
3
1
null
null
null
null
UTF-8
C++
false
false
3,041
cpp
// Copyright (c) 2017-2018 The CruxCoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "accumulatormap.h" #include "accumulators.h" #include "main.h" #include "txdb.h" #include "libzerocoin/Denominations.h" using namespace libzerocoin; using namespace std; //Construct accumulators for all denominations AccumulatorMap::AccumulatorMap(libzerocoin::ZerocoinParams* params) { this->params = params; for (auto& denom : zerocoinDenomList) { unique_ptr<Accumulator> uptr(new Accumulator(params, denom)); mapAccumulators.insert(make_pair(denom, std::move(uptr))); } } //Reset each accumulator to its default state void AccumulatorMap::Reset() { Reset(params); } void AccumulatorMap::Reset(libzerocoin::ZerocoinParams* params2) { this->params = params2; mapAccumulators.clear(); for (auto& denom : zerocoinDenomList) { unique_ptr<Accumulator> uptr(new Accumulator(params2, denom)); mapAccumulators.insert(make_pair(denom, std::move(uptr))); } } //Load a checkpoint containing 8 32bit checksums of accumulator values. bool AccumulatorMap::Load(uint256 nCheckpoint) { for (auto& denom : zerocoinDenomList) { uint32_t nChecksum = ParseChecksum(nCheckpoint, denom); CBigNum bnValue; if (!zerocoinDB->ReadAccumulatorValue(nChecksum, bnValue)) return error("%s : cannot find checksum %d", __func__, nChecksum); mapAccumulators.at(denom)->setValue(bnValue); } return true; } //Load accumulator map from a hard-checkpoint void AccumulatorMap::Load(const AccumulatorCheckpoints::Checkpoint& checkpoint) { for (auto it : checkpoint) mapAccumulators.at(it.first)->setValue(it.second); } //Add a zerocoin to the accumulator of its denomination. bool AccumulatorMap::Accumulate(const PublicCoin& pubCoin, bool fSkipValidation) { CoinDenomination denom = pubCoin.getDenomination(); if (denom == CoinDenomination::ZQ_ERROR) return false; if (fSkipValidation) mapAccumulators.at(denom)->increment(pubCoin.getValue()); else mapAccumulators.at(denom)->accumulate(pubCoin); return true; } //Get the value of a specific accumulator CBigNum AccumulatorMap::GetValue(CoinDenomination denom) { if (denom == CoinDenomination::ZQ_ERROR) return CBigNum(0); return mapAccumulators.at(denom)->getValue(); } //Calculate a 32bit checksum of each accumulator value. Concatenate checksums into uint256 uint256 AccumulatorMap::GetCheckpoint() { uint256 nCheckpoint; //Prevent possible overflows from future changes to the list and forgetting to update this code assert(zerocoinDenomList.size() == 8); for (auto& denom : zerocoinDenomList) { CBigNum bnValue = mapAccumulators.at(denom)->getValue(); uint32_t nCheckSum = GetChecksum(bnValue); nCheckpoint = nCheckpoint << 32 | nCheckSum; } return nCheckpoint; }
[ "44469634+cruxcoinsource@users.noreply.github.com" ]
44469634+cruxcoinsource@users.noreply.github.com
ce11afc44dbff8aa5d8e1bcc68cc3723a1698492
fffb732290af97687ea3221ce4a6ce4d95640aff
/courses/w10_opencv/d04/Visio_Histogram_Equalize.cpp
d8a928eb067cf6d013ee5e0d3cc9c858917d4570
[]
no_license
NamWoo/self_driving_car
851de73ae909639e03756eea4d49ab663447fc19
cd5c1142c9e543e607ca9dc258f689de6879d207
refs/heads/master
2021-07-24T19:51:54.459485
2021-07-06T13:58:19
2021-07-06T13:58:19
186,267,543
9
7
null
null
null
null
UTF-8
C++
false
false
12,468
cpp
#include "OpenCV.h" using namespace std; using namespace cv; string imagepath = "../../../Data/Lane_Detection_Images/"; string roadImage_01 = "solidWhiteCurve.jpg"; string roadImage_02 = "solidWhiteRight.jpg"; string roadImage_03 = "solidYellowCurve.jpg"; string roadImage_04 = "solidYellowCurve2.jpg"; string roadImage_05 = "solidYellowLeft.jpg"; string roadImage_06 = "whiteCarLaneSwitch.jpg"; string videopath = "../../../Data/Lane_Detection_Videos/"; string roadVideo_01 = "solidYellowLeft.mp4"; string roadVideo_02 = "solidWhiteRight.mp4"; void frameProcessing(Mat &frame, Mat &result) { result = imageCopy(frame); int width = frame.cols; int height = frame.rows; vector<Point> pts; pts.push_back(Point(int(width * 0.35), int(height * 0.65))); pts.push_back(Point(int(width * 0.65), int(height * 0.65))); pts.push_back(Point(int(width), int(height))); pts.push_back(Point(int(0), int(height))); Mat ROI, ROI2; polyROI(frame, ROI, pts); ROI2 = frame - ROI; convertColor(ROI, ROI, COLOR_BGR2HSV); vector<Mat> channels; splitImage(ROI, channels); histogramEqualize(channels[1], channels[1]); histogramEqualize(channels[2], channels[2]); mergeImage(channels, ROI); convertColor(ROI, ROI, COLOR_HSV2BGR); Scalar lower_white_hls(0, 245, 0); Scalar upper_white_hls(179, 255, 255); Scalar lower_yellow_hls(15, 75, 150); Scalar upper_yellow_hls(35, 175, 255); Mat output_white_hls, output_yellow_hls; splitColor(ROI, output_white_hls, lower_white_hls, upper_white_hls, COLOR_BGR2HLS); splitColor(ROI, output_yellow_hls, lower_yellow_hls, upper_yellow_hls, COLOR_BGR2HLS); ROI = output_white_hls+output_yellow_hls; addWeightedImage(ROI, ROI2, result, 100, 100); return; } int main(void) { string openPath = videopath + roadVideo_01; Video(openPath, "output_Equalize.avi"); return 0; } Mat imageRead(string openPath, int flag) { Mat image = imread(openPath, flag); if(image.empty()) { cout<<"Image Not Opened"<<endl; cout<<"Program Abort"<<endl; exit(1); } else { cout<<"Image Opened"<<endl; return image; } } void imageShow(string imageName, Mat &image, int flag) { namedWindow(imageName, flag); imshow(imageName, image); waitKey(); return; } void imageWrite(string imageName, Mat &image) { imwrite(imageName, image); return; } void Video(string openPath, string savePath) { VideoCapture cap(openPath); if(!cap.isOpened()) { cout << "Error opening video stream or file" << endl; return; } int fps = cap.get(CAP_PROP_FPS); VideoWriter out; if (!savePath.empty()) { int width = int(cap.get(CAP_PROP_FRAME_WIDTH)); int height = int(cap.get(CAP_PROP_FRAME_HEIGHT)); VideoWriter out(savePath.c_str(), CV_FOURCC('D','I','V','X'), fps, Size(width, height)); } namedWindow("Input", WINDOW_GUI_EXPANDED); namedWindow("Output", WINDOW_GUI_EXPANDED); Mat frame, output; while (cap.isOpened()) { cap >> frame; if (frame.empty()) break; frameProcessing(frame, output); if (!savePath.empty()) out.write(output); imshow("Input", frame); imshow("Output", output); char c = (char)waitKey(int(1000.0/fps)); if (c==27) break; } cap.release(); if (!savePath.empty()) out.release(); destroyAllWindows(); } vector<int> imageParameters(string imagename,Mat &image) { vector<int> Result; Size size = image.size(); int width = image.cols; int height = image.rows; cout << imagename << ".size() is " << size<< endl; cout << imagename << ".rows is height: " << height<< endl; cout << imagename << ".cols is width: " << width<< endl; int channels = image.channels(); if( channels == 1) cout << "This is grayscale image." << endl; else cout << "This is not grayscale image." << endl; cout << "height*width*channels is " << height*width*channels << endl; cout << imagename << ".type() is " << image.type()<< endl; Result.push_back(height); Result.push_back(width); Result.push_back(channels); return Result; } int getPixel(Mat &image, int x, int y, int c) { if( image.type() == CV_8UC1) { uchar* pointer = image.ptr<uchar>(y); return pointer[x]; } else if( image.type() == CV_8UC3) { uchar* pointer = image.ptr<uchar>(y); return pointer[x*3+c]; } } void setPixel(Mat &image, int x, int y, int value, int c) { if( image.type() == CV_8UC1) { uchar* pointer = image.ptr<uchar>(y); pointer[x] = value; return; } else if( image.type() == CV_8UC3) { uchar* pointer = image.ptr<uchar>(y); pointer[x*3+c]= value; return;; } } Mat imageCopy(Mat &image) { Mat result; image.copyTo(result); return result; } void CutRectROI(Mat &image, Mat &result, Point pt1, Point pt2) { result = image(Rect(pt1, pt2)); return; } void PasteRectROI(Mat &image, Mat &result, Point pt1, Point pt2) { Mat dstROI(result, Rect(pt1, pt2)); image.copyTo(dstROI); return; } void polyROI(Mat &image, Mat &result, vector<Point> points) { result = Mat::zeros(image.rows, image.cols, image.type()); vector<vector<Point> > fillContAll; fillContAll.push_back(points); fillPoly(result, fillContAll, Scalar(255, 255, 255)); bitwise_and(result, image, result); return; } void splitImage(Mat &image, vector<Mat> &channels) { split(image, channels); return; } void mergeImage(vector<Mat> &channels, Mat &image) { merge(channels, image); return; } void mergeImage(Mat &ch1, Mat &ch2, Mat &ch3, Mat &image) { vector<Mat> channels; channels.push_back(ch1); channels.push_back(ch2); channels.push_back(ch3); mergeImage(channels, image); return; } void convertColor(Mat &image, Mat &result, int flag) { cvtColor(image, result, flag); return; } void rangeColor(Mat &image, Mat &result, Scalar &min, Scalar &max) { inRange(image, min, max, result); return; } void splitColor(Mat &image, Mat &result, Scalar &min, Scalar &max, int flag) { Mat mask; convertColor(image, mask, flag); rangeColor(mask, mask, min, max); bitwise_and(image, image, result, mask); return; } void drawLine(Mat &image, Mat &result, Point pt1, Point pt2, Scalar color, int thickness) { result = imageCopy(image); line(result, pt1, pt2, color, thickness); return; } void drawRect(Mat &image, Mat &result, Point pt1, Point pt2, Scalar color, int thickness) { result = imageCopy(image); rectangle(result, pt1, pt2, color, thickness); return; } void drawRect(Mat &image, Mat &result, Rect rect, Scalar color, int thickness) { result = imageCopy(image); rectangle(result, rect, color, thickness); return; } void drawCircle(Mat &image, Mat &result, Point center, int radius, Scalar color, int thickness) { result = imageCopy(image); circle(result, center, radius, color, thickness); return; } void drawEllipse(Mat &image, Mat &result, Point center, Size axis, double angle, double startAngle, double endAngle, Scalar color, int thickness) { result = imageCopy(image); ellipse(result, center, axis, angle, startAngle, endAngle, color, thickness); return; } void drawPolygon(Mat &image, Mat &result, vector<Point> points, bool isClosed, Scalar color, int thickness) { result = imageCopy(image); const Point *pts = (const Point *)Mat(points).data; int npts = Mat(points).rows; polylines(result, &pts, &npts, 1, isClosed, color, thickness); return; } void drawText(Mat& image, Mat &result, const string& text, Point point, int font, double fontScale, Scalar color, int thickness) { result = imageCopy(image); putText(result, text, point, font, fontScale, color, thickness); return; } void addImage(Mat &image1, Mat &image2, Mat &result) { add(image1, image2, result); } void addWeightedImage(Mat &image1, Mat &image2, Mat &result, double w1, double w2) { result = imageCopy(image1); if( w2 == -1) { addWeighted(image1, w1*0.01, image2, (100.0-w1)*0.01,0, result); } else { addWeighted(image1, w1*0.01, image2, w2*0.01, 0, result); } return; } void imageThreshold(Mat &image, Mat &result, double thresh, double maxval, int type) { threshold(image, result, thresh, maxval, type); return; } void imageBlur(Mat &image, Mat &result, int ksize) { Size kernelSize(ksize*2-1, ksize*2-1); blur(image, result, kernelSize); return; } void imageGaussianBlur(Mat &image, Mat &result, int ksize, double sigmaX, double sigmaY) { Size kernelSize(ksize*2-1, ksize*2-1); GaussianBlur(image, result, kernelSize, sigmaX, sigmaY); return; } void imageMedianBlur(Mat &image, Mat &result, int ksize) { medianBlur(image, result, ksize*2-1); return; } void imageBilateralFilter(Mat &image, Mat &result, int ksize, double sigmaColor, double sigmaSpace) { bilateralFilter(image, result, ksize*2-1, sigmaColor, sigmaSpace); return; } void imageFiltering(Mat &image, Mat &result, Mat &kernel, int ddepth) { filter2D(image, result, ddepth, kernel); return; } void imageEdgePrewitt(Mat &image, Mat &result) { float kernel_x[] = {-1, 0, 1, -1, 0, 1, -1, 0, 1}; Mat kernelx(3, 3, CV_32F,kernel_x); float kernel_y[] = {-1, -1, -1, 0, 0, 0, 1, 1, 1}; Mat kernely(3, 3, CV_32F,kernel_y); Mat dx, dy; imageFiltering(image, dx, kernelx); imageFiltering(image, dy, kernely); result = dx+dy; return; } void imageEdgeSobel(Mat &image, Mat &result) { Mat dx, dy; Sobel(image, dx, -1, 1, 0, 3); Sobel(image, dy, -1, 0, 1, 3); result = dx+dy; return; } void imageEdgeScharr(Mat &image, Mat &result) { Mat dx, dy; Scharr(image, dx, -1, 1, 0); Scharr(image, dy, -1, 0, 1); result = dx+dy; return; } void imageEdgeLaplacianCV(Mat &image, Mat &result) { Laplacian(image, result, -1, 1); return; } void imageEdgeLaplacianFilter2D(Mat &image, Mat &result) { float kernel_[] = {-1, -1, -1, -1, 8, -1, -1, -1, -1}; Mat kernel(3, 3, CV_32F,kernel_); imageFiltering(image, result, kernel); return; } void imageEdgeLoG(Mat &image, Mat &result) { float kernel_[] = {0, 0, -1, 0, 0, 0, -1, -2, -1, 0, -1, -2, 16, -2, -1, 0, -1, -2, -1, 0, 0, 0, -1, 0, 0}; Mat kernel(5, 5, CV_32F,kernel_); imageFiltering(image, result, kernel); return; } void cannyEdge(Mat &image, Mat &result, double threshold1, double threshold2) { Canny(image, result, threshold1, threshold2); return; } void computeHist(Mat &image, Mat &result) { Mat histogram; if( image.channels() == 1) { int histSize = 256; float range[] = { 0, 256 }; const float* histRange = { range }; calcHist(&image, 1, 0, Mat(), histogram, 1, &histSize, &histRange); int hist_w = 256; int hist_h = 300; int bin_w = cvRound((double)hist_w / (double)histSize); Mat histImage(hist_h, hist_w, CV_8UC1, Scalar(0, 0, 0)); normalize(histogram, histogram, 0, histImage.rows, NORM_MINMAX, -1, Mat()); for (int i = 1; i < histSize; i++) { line(histImage, Point(bin_w*(i - 1), hist_h - cvRound(histogram.at<float>(i - 1))), Point(bin_w*(i), hist_h - cvRound(histogram.at<float>(i))), 255, 2, 8, 0); } result = imageCopy(histImage); return; } else { vector<Mat> channels; splitImage(image, channels); int i; for ( i=0 ; i < 3 ; i++) computeHist(channels[i], channels[i]); mergeImage(channels, result); return; } } void histogramEqualize(Mat &image, Mat &result) { if( image.channels() == 1) { equalizeHist(image, result); return; } else { vector<Mat> channels; splitImage(image, channels); int i; for ( i=0 ; i < 3 ; i++) histogramEqualize(channels[i], channels[i]); mergeImage(channels, result); return; } }
[ "pre3ice@gmail.com" ]
pre3ice@gmail.com
9e269eb89897eeeae20e305b32b3e2faf5eeb56e
b97af846f6dddb8468c3ef9f89c8701335a60a61
/FlyAway/SnowyMountains.cpp
dcb94b76e04514eacc67c0eeaf0819b4fbfe5911
[]
no_license
erbuka/flyaway
2aeefd121b52c5dde9f209c44e44a0c636bd0f2d
8c34c0c4a581c9820d2f884d7152b9f70f4257b6
refs/heads/master
2020-03-18T16:40:19.026906
2020-01-16T10:23:43
2020-01-16T10:23:43
134,979,384
0
0
null
null
null
null
UTF-8
C++
false
false
1,889
cpp
#include "SnowyMountains.h" #include "Engine.h" #include "Terrain.h" #include "SceneObject.h" namespace _SnowyMountains { fa::Interpolator<fa::Vector3f> TerrainColor = { { 0.0f, fa::Vector3f::GetColor(99, 77, 56) }, { 0.48f, fa::Vector3f::GetColor(99, 77, 56) }, { 0.52f, fa::Vector3f::GetColor(255, 255, 255) }, { 1.0f, fa::Vector3f::GetColor(255, 255, 255) } }; } fa::SnowyMountains::SnowyMountains() { m_Height = std::unique_ptr<Perlin>(new Perlin(1024.0f)); m_Snow = std::unique_ptr<Perlin>(new Perlin(256.0f)); m_Height->SetPersistance(0.75f); m_Snow->SetPersistance(0.9f); std::shared_ptr<ModelRandomGenerator> item(new ModelRandomGenerator{ Engine::GetInstance()->GetModel(Models::XmasTree0DarkGreen), Engine::GetInstance()->GetModel(Models::Rock0DarkBrown) }); std::shared_ptr<ModelRandomGenerator> nothing(new ModelRandomGenerator{ nullptr }); m_ModelGenerator = std::unique_ptr<ModelRandomGenerator>(new ModelRandomGenerator{ "itemChance", item, nothing }); } fa::BiomeTerrainDescriptor fa::SnowyMountains::DescribeTerrainAtXY(float x, float z) { BiomeTerrainDescriptor result; result.TerrainColor = _SnowyMountains::TerrainColor.Sample(m_Snow->Sample({ x, z })); result.TerrainHeight = 100.0f + m_Height->Sample({ x, z }) * 150.0f; return result; } fa::SceneObject * fa::SnowyMountains::GenerateSceneObject(Terrain * terrain, BoundingBox3f bounds) { float x = Random::NextFit(1.0f, bounds.Min.X, bounds.Max.X); float z = Random::NextFit(1.0f, bounds.Min.Z, bounds.Max.Z); auto position = Vector3f(x, terrain->GetHeightAt({ x, 0, z }), z); Vector4f rotation = { 0.0f, 1.0f, 0.0f, PI<float>() * 2.0f * Random::NextValue<float>() }; ModelRandomGenerator::Inputs inputs = { { "itemChance", 0.01f } }; auto model = m_ModelGenerator->GetResult(inputs); return model == nullptr ? nullptr : new SceneObject(model, position, rotation); }
[ "erbuka@hotmail.com" ]
erbuka@hotmail.com
406409c3eb1ed28f4687d938f3f96abd57e249e9
09cf4d5c230e55c246693fe6fb9fe344c15d9750
/src/gc/impl/vmem.hpp
d3edb695c813edfe2a0ea0d6000dd64cc96cd5a9
[ "ISC" ]
permissive
Gwenio/synafis
c47fc130607fc0a4efac09d34d4fec4646d07648
37176e965318ae555fdc542fc87ffb79866f770f
refs/heads/master
2020-03-19T17:09:15.891340
2019-02-26T18:41:21
2019-02-26T18:41:21
136,746,457
1
0
null
null
null
null
UTF-8
C++
false
false
8,287
hpp
/* ISC License (ISC) Copyright 2018-2019 Adam Armstrong Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /** \file src/gc/impl/vmem.hpp * \brief Defines an abstraction layer for the host's virtual memory system. * \ingroup gc_impl */ /** \dir src/gc/impl/vmem * \brief Contains the platform specific implementation of gc::vmem. * \ingroup gc_impl */ //! TODO Implement gc::vmem for platforms other than Windows. #ifndef SYNAFIS_GC_VMEM_HPP #define SYNAFIS_GC_VMEM_HPP #pragma once #include <utility> #include "../../unit_test.hpp" #include "ptr_math.hpp" namespace gc { //! TODO Investigate supporting huge pages to reduce page map size in the kernel. /** \class vmem * \brief Abstracts the host system's virtual memory. * \note Execute privilege is considered unneeded at this time. * \ingroup gc_impl */ class vmem { //! \cond friends friend unit_test::tester<vmem>; //! \endcond private: /** \var ptr * \brief The address of the virtual memory. */ void *ptr; /** \var len * \brief The size of the virtual memory. */ std::size_t len; /** \fn allocate(std::size_t size, bool access) noexcept * \brief Allocates virtual memory. * \param size The size of the block of memory to allocate. * \param access If true start with read and write access; otherwise, start with no access. * \returns Returns the allocate memory or nullptr on failure. * \pre 'size' must be greater than zero. * \note If size is not a multiple of page_size, it will be rounded up to the nearest multiple. */ static void *allocate(std::size_t size, bool access) noexcept; /** \fn deallocate(void *ptr) noexcept * \brief Deallocates virtual memory. * \param ptr The virtual memory to deallocate. * \pre 'ptr' must be a block of virtual memory returned by allocate. */ static void deallocate(void *ptr) noexcept; public: /** \fn page_size() noexcept * \brief The basic unit size of virtual memory blocks. * \returns Returns the smallest unit of virtual memory used by the OS. */ static std::size_t page_size() noexcept; /** \fn vmem() noexcept * \brief Initializes with no virtual memory. */ constexpr vmem() noexcept : ptr(nullptr), len(0) {} /** \fn vmem(std::size_t const s, bool const access) noexcept * \brief Initializes with a new virtual memory block. * \param s The size of the block. * \param access If true start with read and write access; otherwise, start with no access. */ vmem(std::size_t const s, bool const access) noexcept : vmem() { ptr = allocate(s, access); if (ptr) { len = s; } } /** \fn vmem(vmem const &) * \brief Deleted. */ vmem(vmem const &) = delete; /** \fn vmem(vmem &&other) noexcept * \brief Moves the virtual memory from other to this. */ constexpr vmem(vmem &&other) noexcept : vmem() { if (other.ptr) { ptr = std::exchange(other.ptr, nullptr); len = std::exchange(other.len, 0); } } /** \fn ~vmem() noexcept * \brief Deallocates the virtual memory if ptr is not nullptr. */ ~vmem() noexcept { if (ptr) { deallocate(ptr); } } /** \fn operator=(std::nullptr_t) noexcept * \brief Removes the owned virtual memory if this has any. */ constexpr vmem &operator=(std::nullptr_t) noexcept { if (ptr) { deallocate(ptr); ptr = nullptr; len = 0; } return *this; } /** \fn operator=(vmem const &) * \brief Deleted. */ vmem &operator=(vmem const &) = delete; /** \fn operator=(vmem &&other) noexcept * \brief Moves the virtual memory from other to this. * \param other The object to move the virtual memory from. * \returns Returns *this. */ constexpr vmem &operator=(vmem &&other) noexcept { if (std::addressof(other) != this) { if (ptr) { deallocate(ptr); } ptr = std::exchange(other.ptr, nullptr); len = std::exchange(other.len, 0); } return *this; } /** \fn operator bool() const noexcept * \brief Converts to bool. * \returns Returns true if ptr != nullptr. */ constexpr operator bool() const noexcept { return ptr != nullptr; } /** \fn operator!() const noexcept * \brief Converts to bool. * \returns Returns true if ptr == nullptr. */ constexpr bool operator!() const noexcept { return ptr == nullptr; } /** \fn size() const noexcept * \brief Gets the size of the owned virtual memory. * \returns The size of the virtual memory. */ constexpr std::size_t size() const noexcept { return len; } /** \fn begin() const noexcept * \brief Gets the starting address of the block. * \returns ptr */ constexpr void *begin() const noexcept { return ptr; } /** \fn end() const noexcept * \brief Gets the end address of the block. * \returns The address just past the end. * \returns Returns nullptr if ptr is nullptr. */ constexpr void *end() const noexcept { return ptr ? add_offset(ptr, len) : nullptr; } /** \fn operator[](std::size_t offset) const noexcept * \brief Gets the pointer for an offset into the virtual memory. * \param offset The offset into the block to get a pointer for. * \returns The pointer to the offset from the beginning of the block. * \pre ptr != nullptr * \pre offset < len * \warning The precondition is only checked with SYNAFIS_ASSERT, * \warning which does nothing when not debugging or testing. */ void *operator[](std::size_t offset) const noexcept; /** \fn at(std::size_t offset) const * \brief Gets the pointer for an offset into the virtual memory. * \param offset The offset into the block to get a pointer for. * \returns The pointer to the offset from the beginning of the block. * \throws Throws std::logic_error if any of the preconditions are violated. * \pre offset < len * \pre ptr != nullptr */ void *at(std::size_t offset) const; /** \fn forbid(std::size_t offset, std::size_t length) noexcept * \brief Makes part of a previously allocated block inaccessible. * \param offset The starting point in the virtual memory block. * \param length The size of area to forbid. * \returns Returns a boolean value indicated whether the change succeeded. * \pre The whole indicated area must reside in the owned virtual memory. * \pre ptr != nullptr * \warning If any portion of a page falls in the area, the whole page * \warning will have its protection settings changed. */ bool forbid(std::size_t offset, std::size_t length); /** \fn readonly(std::size_t offset, std::size_t length) noexcept * \brief Makes part of a previously allocated block have read access only. * \param offset The starting point in the virtual memory block. * \param length The size of area to have read access only. * \returns Returns a boolean value indicated whether the change succeeded. * \pre The whole indicated area must reside in the owned virtual memory. * \pre ptr != nullptr * \warning If any portion of a page falls in the area, the whole page * \warning will have its protection settings changed. */ bool readonly(std::size_t offset, std::size_t length); /** \fn writable(std::size_t offset, std::size_t length) noexcept * \brief Makes part of a previously allocated block have read and write access. * \param offset The starting point in the virtual memory block. * \param length The size of area to make writable. * \returns Returns a boolean value indicated whether the change succeeded. * \pre The whole indicated area must reside in the owned virtual memory. * \pre ptr != nullptr * \warning If any portion of a page falls in the area, the whole page * \warning will have its protection settings changed. */ bool writable(std::size_t offset, std::size_t length); }; } #endif
[ "gwenio@live.com" ]
gwenio@live.com
f983eff020489870c8262285e9660aa220ef70e3
00b3499a12b10875fc8a28d55032fb949b2a37a4
/src/Script/JavaScript/Module.h
a54a4e630d7ea8453636b19b57e3eec1c7703da9
[ "MIT" ]
permissive
slagusev/rainbow
203066dfa388d80a57429472d04ae1648642e7c9
f117bac11c427d5f54cd69106021cd7e565a559a
refs/heads/master
2021-04-27T04:17:15.322885
2018-02-11T10:46:03
2018-02-13T18:51:56
122,728,447
1
0
null
2018-02-24T10:05:55
2018-02-24T10:05:55
null
UTF-8
C++
false
false
1,376
h
// Copyright (c) 2010-present Bifrost Entertainment AS and Tommy Nguyen // Distributed under the MIT License. // (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) #ifndef SCRIPT_JAVASCRIPT_MODULE_H_ #define SCRIPT_JAVASCRIPT_MODULE_H_ #include <duktape.h> extern "C" { // TODO: Remove workaround with Duktape v2.3.0 #include <duk_module_node.h> } #include "Common/Logging.h" namespace rainbow::duk::module { auto load(duk_context* ctx) -> duk_ret_t { // Entry stack: [ resolved_id exports module ] duk_push_string(ctx, "<source code>"); return 1; } auto resolve(duk_context* ctx) -> duk_ret_t { // Entry stack: [ requested_id parent_id ] auto requested_id = duk_get_string(ctx, 0); auto parent_id = duk_get_string(ctx, 1); std::string resolved_id = parent_id; resolved_id += '.'; resolved_id += requested_id; duk_push_string(ctx, resolved_id.c_str()); return 1; } void initialize(duk_context* ctx) { duk_push_object(ctx); duk_push_c_function(ctx, module::load, -1); duk_put_prop_string(ctx, -2, "load"); duk_push_c_function(ctx, module::resolve, -1); duk_put_prop_string(ctx, -2, "resolve"); duk_module_node_init(ctx); } } // namespace rainbow::duk::module #endif
[ "tn0502@gmail.com" ]
tn0502@gmail.com
f1c89ca48022d9f48a6703871f4ce44a978aa7aa
066c602514cba0e641886b713e53807e0c6e2108
/chapter_10/stack01.cpp
bba28c81e8e460bb3bcae2b7db2a369f9da9e2e2
[]
no_license
ravenCrown0627/Exercise
c0b1332c6bbf92f926fa2924b59ec9d29ce9ba77
acbea29cd48db5bfa2ed87c3a1f673440a32b0dd
refs/heads/master
2023-07-17T11:51:17.685753
2021-09-06T09:36:32
2021-09-06T09:36:32
403,550,789
0
0
null
2021-09-06T09:36:33
2021-09-06T08:51:28
C++
UTF-8
C++
false
false
365
cpp
#include "stack00.h" bool Stack::isempty() const { return top == 0; } bool Stack::isfull() const { return top == MAX; } bool Stack::push(const Item& item) { if (top < MAX) { customer[top++] = item; return true; } else return false; } bool Stack::pop(Item& item) { if (top > 0) { item = customer[--top]; return true; } else return false; }
[ "kagamine999@gmail.com" ]
kagamine999@gmail.com
84ce9deb94b150fec8e7a07e4e52e13828e0ca36
8f9d9f581ab1603f8719ea82d6e4d82df176741a
/htree.hh
9c003db97329f4fdef2a5473f2195567fc59b85a
[]
no_license
orbitalhybridization/CS221_HW7
0199e6175eee43ed4608f4e8b82e6949c37b1d40
aa769f144cfc339db0f07bf68c9425e37931e2df
refs/heads/master
2021-05-18T05:47:19.086957
2020-03-29T21:57:22
2020-03-29T21:57:22
251,142,785
0
0
null
null
null
null
UTF-8
C++
false
false
969
hh
/* * HTree: a class to represent a tree node with two values: a key * and a value. */ //#pragma once #include <memory> #include <list> class HTree { public: using tree_ptr_t = std::shared_ptr<const HTree>; enum class Direction { LEFT, RIGHT }; using path_t = std::list<Direction>; HTree(int key, uint64_t value, tree_ptr_t left = nullptr, tree_ptr_t right = nullptr); ~HTree(); int get_key() const; // Return key in current node uint64_t get_value() const; // Return value in current node // Return the child of this node indicated by dir. // If the child is nullptr (current node is a leaf), returns nullptr. tree_ptr_t get_child(Direction dir) const; // Return a list of directions from root to a node of a given key. // Crashes (with an assert) if key not contained in this tree path_t path_to(int key) const; private: int key_; uint64_t value_; tree_ptr_t left_; tree_ptr_t right_; };
[ "noreply@github.com" ]
noreply@github.com
fa6045ce3cdce477950a2b782d8c9631f290b605
d4d2a6001f2748334ba8f65d44d4cd5033e9470c
/include/nogara/expression/undef_container_macros.hpp
d149012b7c44a587d60ac571e8f928eb92dd3fc0
[]
no_license
lowwin-bzn/nogara
69ebc1e241e3ced80cf9d6b4fccde07607a76910
358d0868a01629cd5d26866990a6a3cc4987952c
refs/heads/master
2021-01-18T21:33:35.934021
2011-05-20T02:21:18
2011-05-20T02:21:18
1,774,403
0
0
null
null
null
null
UTF-8
C++
false
false
756
hpp
#undef MAKE_CONSTRUCTOR_EXTENDS_CPP0X1 #undef MAKE_CONSTRUCTOR_EXTENDS_CPP0X2 #undef MAKE_CONSTRUCTOR_EXTENDS_CPP0X3 #undef MAKE_CONSTRUCTOR_EXTENDS_CPP0X4 #undef MAKE_CONSTRUCTOR_EXTENDS_CPP0X5 #undef MAKE_CONSTRUCTOR_EXTENDS_CPP0X6 #undef MAKE_CONSTRUCTOR_EXTENDS_CPP0X7 #undef MAKE_CONSTRUCTOR_EXTENDS_CPP0X8 #undef MAKE_CONSTRUCTOR_EXTENDS_CPP0X #undef MAKE_CONSTRUCTOR1 #undef MAKE_CONSTRUCTOR2 #undef MAKE_CONSTRUCTOR3 #undef MAKE_CONSTRUCTOR4 #undef MAKE_CONSTRUCTOR5 #undef MAKE_CONSTRUCTOR6 #undef MAKE_CONSTRUCTOR7 #undef MAKE_CONSTRUCTOR8 #undef MAKE_CONSTRUCTOR #undef ASSIGN_IMPL1 #undef ASSIGN_IMPL2 #undef ASSIGN_IMPL3 #undef ASSIGN_IMPL4 #undef ASSIGN_IMPL5 #undef ASSIGN_IMPL6 #undef ASSIGN_IMPL7 #undef ASSIGN_IMPL8 #undef MAKE_ASSIGN
[ "mistselene.zl@gmail.com" ]
mistselene.zl@gmail.com
4acd5cc3ce6628747e2fb9db7d1b90a7364ee2c9
57ca30c82a493e78e8b498bb790bb50bde820279
/rfm73/endpoint/lib/IReceiveGS/IReceiveGS.cpp
f2fcd0105393c246ca577c0eebddb1a225fb5f00
[]
no_license
kqtrinh/cells
151241ad1c51c9479a85ad25367e410982efc523
42140b105ef51c86b5dea351ddace5d4c109d1a0
refs/heads/master
2021-01-18T09:08:45.870988
2014-10-21T08:30:57
2014-10-21T08:30:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
754
cpp
#include <IReceiveGS.h> #include <comm.h> IReceiveGS::IReceiveGS(const char *cmdstr) : IReceive(cmdstr) { } void IReceiveGS::setUserObj(user_activity *a) { _a = a; } /*接收到的数据,作进一步处理函数*/ void IReceiveGS::onReceive(unsigned char *dat, unsigned char len) { if (isNewPackage(dat)) { Serial.println("new package"); // saveAckBuf((unsigned char *)"getstatus:ok", strlen("getstatus:ok")); strcpy((char *)ack_buf, "getstatus:oa"); _a->m_comm->send((const char *)ack_buf, 12); // _a->m_comm->send("getstatus:ok", 12); } else { Serial.println("old package"); _a->m_comm->send((const char *)ack_buf, 12); // _a->m_comm->send("getstatus:ok", 12); // _a->m_comm->send((const char *)getAckBuf(), getAckBufLen()); } }
[ "china.gd.sz.cd@gmail.com" ]
china.gd.sz.cd@gmail.com
18177904a1d3dfb71bc2386dcb165867d64edbf7
b796e847de7b2f8269399daf3b0629c4c0a4a640
/C++/LinkedList/LinkedList.h
3324d4e6d65ef551c5a771376693093be8f94efa
[]
no_license
blackholeco/portfolio
18dffa062a8b2c2357f8e08f36ab92326f5ecf01
126e184164b4d688ac58036a8b5eae7dca1083c1
refs/heads/master
2021-06-27T16:39:19.502546
2019-06-12T12:49:04
2019-06-12T12:49:04
118,763,102
0
0
null
null
null
null
UTF-8
C++
false
false
5,250
h
/* * LinkedList.h by Chris Allen * This file is provided "as-is", for the sole purpose of a demonstration of my work. It is not intended to be copied or used in an external or third-party project, and no support will be given for that use. * You may not use or copy this file, in whole or in part, to use for your own projects. All rights reserved over this file. */ #pragma once #include <memory> using namespace std; template <class T> class LinkedList; template <class T> class LinkedListNode { public: LinkedListNode() { prevnode = nextnode = nullptr; nodeitem = make_shared<T>(); } LinkedListNode(T& item, LinkedListNode<T>* prev) { nodeitem.reset(&item); prevnode = prev; if(prevnode != nullptr) prevnode->nextnode = this; nextnode = nullptr; } LinkedListNode(shared_ptr<T> item, LinkedListNode* prev) { nodeitem = item; prevnode = prev; if(prevnode) prevnode->nextnode = this; nextnode = nullptr; } ~LinkedListNode() { nodeitem.reset(); } void operator =(LinkedListNode<T>& node) { prevnode = node.prevnode; nextnode = node.nextnode; nodeitem.reset(node.nodeitem); } LinkedListNode<T>* nextNode() { return nextnode; } LinkedListNode<T>* prevNode() { return prevnode; } shared_ptr<T> getNodeItem() { return nodeitem; } protected: friend class LinkedList<T>; LinkedListNode<T>* prevnode; LinkedListNode<T>* nextnode; shared_ptr<T> nodeitem; }; template <class T> class LinkedListIter { public: LinkedListIter() { curnode = nullptr; } LinkedListIter(LinkedListNode<T>*); void operator=(const LinkedListIter<T>& orig) { curnode = orig.curnode; } bool operator!=(const LinkedListNode<T>* orig) { return orig != curnode; } shared_ptr<T> operator *() { if(curnode != nullptr) return curnode->getNodeItem(); return make_shared<T>(); } void operator++() { if(curnode) curnode = curnode->nextNode(); } void operator++(int) { if(curnode) curnode = curnode->nextNode(); } void operator--() { if(curnode) curnode = curnode->prevNode(); } T* nextNodeItem() const; T* prevNodeItem() const; protected: friend class LinkedList<T>; LinkedListNode<T>* curnode; }; template <class T> class LinkedList { public: LinkedList() { listlength = 0; maxitems = 5; first = last = nullptr; }; ~LinkedList() { removeAllEntries(); } void setMaxItems(int max) { maxitems = max; } int getMaxItems() const { return maxitems; } int findEntry(int itemid, shared_ptr<T> ret = make_shared<T>()) { LinkedListIter<T> iterator = start(); for(int i = 0; iterator != nullptr; iterator++, i++) { if(*((*iterator)) == itemid) { if(ret.get()) ret = (*iterator); return i; } } return -1; } /** * Needs work */ bool removeEntry(int itmnum) { LinkedListNode<T>* curnode = nullptr; if(listlength == 0) return false; if(itmnum < listlength) { for(int i = 0; i <= itmnum; i++) { if(i == 0) curnode = first; else curnode = curnode->nextNode(); } assert(curnode); if(curnode == first) first = curnode->nextNode(); else if(curnode == last) last = curnode->prevNode(); if(curnode->nextnode != nullptr) curnode->nextnode->prevnode = curnode->prevnode; if(curnode->prevnode != nullptr) curnode->prevnode->nextnode = curnode->nextnode; delete curnode; curnode = nullptr; listlength--; return true; } return false; } void removeAllEntries() { if(listlength == 0) return; LinkedListNode<T>* tmp = last; LinkedListNode<T>* nextone = last->prevnode; while(tmp != nullptr) { delete tmp; tmp = nextone; } listlength = 0; last = first = nullptr; } shared_ptr<T> itemAt(unsigned int ref) { LinkedListNode<T>* curnode = nullptr; if(ref < listlength) { curnode = first; for(int i = 1; i <= ref; i++) curnode = curnode->nextNode(); return curnode->getNodeItem(); } return nullptr; } int addEntry() { return addEntry(make_shared<T>()); } int addEntry(T& newentry) { LinkedListNode<T>* newnode = nullptr; if(maxitems != 0 || listlength < maxitems) { if(first == nullptr) { newnode = new LinkedListNode<T>(newentry, nullptr); assert(newnode); first = newnode; } else newnode = new LinkedListNode<T>(newentry, last); assert(newnode); last = newnode; listlength++; return listlength -1; } else return -1; } int addEntry(shared_ptr<T> newentry) { LinkedListNode<T>* newnode = nullptr; if(maxitems != 0 || listlength < maxitems) { if(first == nullptr) { newnode = new LinkedListNode<T>(newentry, nullptr); assert(newnode); first = newnode; } else newnode = new LinkedListNode<T>(newentry, last); assert(newnode); last = newnode; listlength++; return listlength -1; } else return -1; } int length() const { return listlength; } LinkedListIter<T> start() { LinkedListIter<T> ret; ret.curnode = first; return ret; } protected: friend class LinkedListIter<T>; int listlength; int maxitems; LinkedListNode<T>* first; LinkedListNode<T>* last; };
[ "35765087+blackholeco@users.noreply.github.com" ]
35765087+blackholeco@users.noreply.github.com
9f55558ba26ce12ba8a464f7624120acbbb31133
dd8dd5cab1d4a678c412c64f30ef10f9c5d210f1
/cpp/leetcode/587. erect-the-fence.cpp
78bbf7cc7fd9f886e3556b1c7a500f0b62be1d7f
[]
no_license
blacksea3/leetcode
e48a35ad7a1a1bb8dd9a98ffc1af6694c09061ee
18f87742b64253861ca37a2fb197bb8cb656bcf2
refs/heads/master
2021-07-12T04:45:59.428804
2020-07-19T02:01:29
2020-07-19T02:01:29
184,689,901
6
2
null
null
null
null
GB18030
C++
false
false
2,995
cpp
#include "BinaryTree.h" #include "listnode.h" //Graham 扫描 //翻译至leetcode官方题解的JAVA版本的Graham方法 // class Solution { private: //这个函数有 3 个参数,分别是当前凸包上的点 p,下一个会加到凸包里的点 q,其他点空间内的任何一个点 r。如果 q 点相对于 r 点来说在点 p 的逆时针方向上的话,这个函数返回一个负值。 int orientation(const vector<int>& p, const vector<int>& q, const vector<int>& r) { return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]); } //求p和q的距离平方 int distance(const vector<int>& p, const vector<int>& q) { return (p[0] - q[0]) * (p[0] - q[0]) + (p[1] - q[1]) * (p[1] - q[1]); } vector<int> bottomLeft(const vector<vector<int>> points) { int stY = points[0][1]; int stX = points[0][0]; int stIndex = 0; for (int index = 1; index < points.size(); ++index) { if (points[index][1] < stY) { stY = points[index][1]; stX = points[index][0]; stIndex = index; } else if (points[index][1] == stY) { if (points[index][0] < stX) { stY = points[index][1]; stX = points[index][0]; stIndex = index; } } } return points[stIndex]; } public: vector<vector<int>> outerTrees(vector<vector<int>>& points) { if (points.size() <= 1) return points; vector<int> bL = this->bottomLeft(points); sort(points.begin(), points.end(), [this, &bL](vector<int> p, vector<int> q) { int diff = this->orientation(bL, p, q) - this->orientation(bL, q, p); if (diff == 0) { return (this->distance(bL, p) - this->distance(bL, q)) > 0; } else { return diff > 0 ? true : false; } } ); int i = points.size() - 1; while (i >= 0 && orientation(bL, points[points.size() - 1], points[i]) == 0) i--; for (int l = i + 1, h = points.size() - 1; l < h; l++, h--) { vector<int> temp = points[l]; points[l] = points[h]; points[h] = temp; } vector<vector<int>> st; st.push_back(points[0]); st.push_back(points[1]); for (int j = 2; j < points.size(); j++) { vector<int> top = st.back(); st.pop_back(); while (orientation(st.back(), top, points[j]) > 0) { top = st.back(); st.pop_back(); } st.push_back(top); st.push_back(points[j]); } return st; } }; int main() { Solution* s = new Solution(); vector<vector<int>> points1 = { {1, 1},{2, 2 }, {2, 0}, {2, 4}, { 3, 3}, {4, 2} }; auto ret = s->outerTrees(points1); return 0; }
[ "17865191779@163.com" ]
17865191779@163.com
4765346104f1e3e8402ad88d3ba0048c1082cc9a
25b26d87967aa5b80729db18cb452d1cfe36c957
/packager/media/formats/mp2t/ts_writer.h
9584e9482e0ed8e542f38a7193ba6efa3de12d94
[ "BSD-3-Clause" ]
permissive
guoyunliang/edash-packager
8c00ebd60d6752c74ba0949eec07f0120e093b96
9bb6c5d8d2666ce632e4b19d330c4d8e681801a9
refs/heads/master
2021-01-17T23:18:06.761170
2016-05-04T21:19:40
2016-05-05T16:41:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,468
h
// Copyright 2016 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd #ifndef PACKAGER_MEDIA_FORMATS_MP2T_TS_WRITER_H_ #define PACKAGER_MEDIA_FORMATS_MP2T_TS_WRITER_H_ #include <list> #include <map> #include <vector> #include "packager/base/memory/scoped_ptr.h" #include "packager/media/base/media_stream.h" #include "packager/media/file/file.h" #include "packager/media/file/file_closer.h" #include "packager/media/formats/mp2t/pes_packet.h" namespace edash_packager { namespace media { namespace mp2t { class ContinuityCounter { public: ContinuityCounter(); ~ContinuityCounter(); /// As specified by the spec, this starts from 0 and is incremented by 1 until /// it wraps back to 0 when it reaches 16. /// @return counter value. int GetNext(); private: int counter_ = 0; DISALLOW_COPY_AND_ASSIGN(ContinuityCounter); }; /// This class takes PesPackets, encapsulates them into TS packets, and write /// the data to file. This also creates PSI from StreamInfo. class TsWriter { public: TsWriter(); virtual ~TsWriter(); /// This must be called before calling other methods. /// @return true on success, false otherwise. virtual bool Initialize(const StreamInfo& stream_info); /// This will fail if the current segment is not finalized. /// @param file_name is the output file name. /// @return true on success, false otherwise. virtual bool NewSegment(const std::string& file_name); /// Flush all the pending PesPackets that have not been written to file and /// close the file. /// @return true on success, false otherwise. virtual bool FinalizeSegment(); /// Add PesPacket to the instance. PesPacket might not get written to file /// immediately. /// @param pes_packet gets added to the writer. /// @return true on success, false otherwise. virtual bool AddPesPacket(scoped_ptr<PesPacket> pes_packet); private: std::vector<uint8_t> psi_ts_packets_; uint32_t time_scale_ = 0u; ContinuityCounter pmt_continuity_counter_; ContinuityCounter pat_continuity_counter_; ContinuityCounter elementary_stream_continuity_counter_; scoped_ptr<File, FileCloser> current_file_; DISALLOW_COPY_AND_ASSIGN(TsWriter); }; } // namespace mp2t } // namespace media } // namespace edash_packager #endif // PACKAGER_MEDIA_FORMATS_MP2T_TS_WRITER_H_
[ "rkuroiwa@google.com" ]
rkuroiwa@google.com
66ce45a85f191f640c3d0758971e19fded69800d
baf7fb90abd76fc784dfe2a9b8d5fdd6c617ac7f
/src/sw/client/cli/command/commands.h
dffcb81172fb043aeaa8f3a4a58739c101f0e85c
[ "GPL-3.0-only", "AGPL-3.0-or-later", "GPL-3.0-or-later", "MPL-2.0", "Apache-2.0" ]
permissive
cppan/cppan
ee59bfbd61097d49eded0a665a573327d1426800
353c61100cdb9b16a90e25b244b18d06ae9f7dd1
refs/heads/master
2021-05-25T10:02:37.616917
2020-01-05T15:17:40
2020-01-05T15:17:40
51,918,764
118
26
Apache-2.0
2018-06-20T14:22:44
2016-02-17T11:47:22
C++
UTF-8
C++
false
false
2,358
h
/* * SW - Build System and Package Manager * Copyright (C) 2017-2019 Egor Pugin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include <primitives/sw/cl.h> #include <sw/core/build.h> #include <sw/core/sw_context.h> #include <sw/manager/package_data.h> namespace sw { struct StorageWithPackagesDatabase; } #define SUBCOMMAND_DECL(n) void cli_##n() #define SUBCOMMAND_DECL2(n) void cli_##n(sw::SwContext &swctx) #define SUBCOMMAND(n) SUBCOMMAND_DECL(n); SUBCOMMAND_DECL2(n); #include "commands.inl" #undef SUBCOMMAND #define DEFINE_SUBCOMMAND(n, d) ::cl::SubCommand subcommand_##n(#n, d) #define DEFINE_SUBCOMMAND_ALIAS(command, alias) \ DEFINE_SUBCOMMAND(alias, "Alias for " #command "."); \ SUBCOMMAND_DECL(alias) \ { \ cli_##command(); \ } std::unique_ptr<sw::SwContext> createSwContext(); std::unique_ptr<sw::SwBuild> createBuild(sw::SwContext &); std::pair<sw::SourceDirMap, const sw::Input &> fetch(sw::SwBuild &); std::pair<sw::SourceDirMap, const sw::Input &> fetch(sw::SwContext &); sw::PackageDescriptionMap getPackages(const sw::SwBuild &, const sw::SourceDirMap & = {}); sw::TargetSettings createInitialSettings(const sw::SwContext &); std::vector<sw::TargetSettings> createSettings(sw::SwContext &); std::unique_ptr<sw::SwBuild> setBuildArgsAndCreateBuildAndPrepare(sw::SwContext &, const Strings &inputs); std::unique_ptr<sw::SwBuild> createBuildAndPrepare(sw::SwContext &); std::map<sw::PackagePath, sw::VersionSet> getMatchingPackages(const sw::StorageWithPackagesDatabase &, const String &unresolved_arg); void run(sw::SwContext &swctx, const sw::PackageId &pkg);
[ "egor.pugin@gmail.com" ]
egor.pugin@gmail.com
70571cca6da0941859b9e9d1817afba962b85141
349251d9b110063cde04a77179e98094df9d3e65
/navigation/base_local_planner/include/base_local_planner/trajectory_sample_generator.h
d65fb87fbdc06fad20a0608f287475a58a1ddbb2
[]
no_license
mfkiwl/slam
728bb4e142f0eee6800c66504500eef85dd8a4db
aa7d4d69c92247e4bc1e232a3568a0568ae47e2f
refs/heads/master
2022-04-08T09:24:33.747950
2020-01-19T01:32:33
2020-01-19T01:32:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,619
h
/********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Author: TKruse *********************************************************************/ #ifndef TRAJECTORY_SAMPLE_GENERATOR_H_ #define TRAJECTORY_SAMPLE_GENERATOR_H_ #include <base_local_planner/trajectory.h> namespace base_local_planner { /** * @class TrajectorySampleGenerator * @brief Provides an interface for navigation trajectory generators */ class TrajectorySampleGenerator { public: /** * Whether this generator can create more trajectories */ virtual bool hasMoreTrajectories() = 0; /** * Whether this generator can create more trajectories */ virtual bool nextTrajectory(Trajectory &traj) = 0; /** * @brief Virtual destructor for the interface */ virtual ~TrajectorySampleGenerator() {} protected: TrajectorySampleGenerator() {} }; } // end namespace #endif /* TRAJECTORY_SAMPLE_GENERATOR_H_ */
[ "j.z.feng@foxmail.com" ]
j.z.feng@foxmail.com
072637d3319e857bd24efd3e6d51f01ab0cb583a
51e8abe780348857f5023fe97810d6f1fdd5f690
/opengl7/filters/Lap.h
0c7305885c20a5f3eedfbb829124db75a06fb04a
[]
no_license
rbaygildin/learn-graphics
959a0182d7a81a7a3c33349e337aa5adea0ff32c
b6b88659b4028a6e3b5c05c68954503afd3e1c97
refs/heads/master
2021-09-15T03:08:58.803772
2018-05-24T19:00:44
2018-05-24T19:00:44
109,318,622
2
0
null
null
null
null
UTF-8
C++
false
false
375
h
// // Created by Max Heartfield on 15.03.18. // #ifndef OPENGL_LAP_H #define OPENGL_LAP_H #include <QOpenGLShaderProgram> #include "../utils.h" class Lap : public QOpenGLShaderProgram { public: Lap(); private: static constexpr auto VERTEX_PATH = "data/shaders/vertex.vert"; static constexpr auto FRAG_PATH = "data/shaders/lap.frag"; }; #endif //OPENGL_LAP_H
[ "rbaygildin95@gmail.com" ]
rbaygildin95@gmail.com
07d5258be2a268165853cc696c66e5cc12f81514
eed4ec8c4ddc7ee5e8bd666c383eb65c3cd81ad3
/transferVertex/src/transferVertex.h
30b3cb2cde8a3bbf15356dc733354bc85fdb91e6
[]
no_license
Ndoye80/miMayaPlugins
c8bc06fd6a462ba1eedcfc4e93917868eab82b95
0ae82c454803071c40f407b6a4254fc78bfb306b
refs/heads/master
2020-05-26T17:32:07.625634
2019-02-17T18:59:32
2019-02-17T18:59:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
974
h
// transferVertex.h // // Copyright (c) 2019 Michitaka Inoue // // This software is released under the MIT License. // http://opensource.org/licenses/mit-license.php #ifndef __TransferVertex_H__ #define __TransferVertex_H__ #include <maya/MPxCommand.h> #include <maya/MDagPath.h> #include <maya/MPointArray.h> #include <maya/MFnMesh.h> #include <maya/MString.h> #include <maya/MSyntax.h> class TransferVertex : public MPxCommand { public: TransferVertex(); virtual ~TransferVertex(); MStatus doIt(const MArgList& argList); MStatus undoIt(); MStatus redoIt(); bool isUndoable() const; static void* creator(); static MSyntax newSyntax(); private: MDagPath mDagPath; MPointArray originalPositions; MPointArray newPositions; MFnMesh sourceFnMesh; MFnMesh targetFnMesh; MString sourceUvSet; MString targetUvSet; MString sourceMesh; MString targetMesh; double tolerance; }; #endif /* defined(__TransferVertex_H__) */
[ "michitaka.inoue@icloud.com" ]
michitaka.inoue@icloud.com
e702ce4e19fd2f7409e0ee4126f709e2242cde41
f8d76935f342abceff51a90a2844110ac57a4d2e
/solution/srm309_contestcoordinator.cpp
aaeb2f97b61a2f06b7a495893099d4896faec7d7
[]
no_license
rick-qiu/topcoder
b36cc5bc571f1cbc7be18fdc863a1800deeb5de1
04adddbdc49e35e10090d33618be90fc8d3b8e7d
refs/heads/master
2021-01-01T05:59:41.264459
2014-05-22T06:14:43
2014-05-22T06:14:43
11,315,215
1
0
null
null
null
null
UTF-8
C++
false
false
88,994
cpp
/******************************************************************************* * Automatically generated code for TopCode SRM Problem * Problem URL: http://community.topcoder.com/stat?c=problem_statement&pm=6243 *******************************************************************************/ #include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> using namespace std; class ContestCoordinator { public: double bestAverage(vector<int> scores); }; double ContestCoordinator::bestAverage(vector<int> scores) { double ret; return ret; } int test0() { vector<int> scores = {5, 3, 3, 10, 10, 4, 3, 10, 10, 3, 9, 5, 7, 10}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 6.666666666666667; if(result == expected) { cout << "Test Case 0: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 0: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test1() { vector<int> scores = {9, 5, 1, 7, 7, 7, 1, 5, 3, 10, 1, 5, 5, 3, 8, 10, 5, 7, 1, 6, 5, 9, 7, 7, 8, 10, 6, 9, 9, 1, 4, 5, 10, 6, 4, 2, 8, 5, 8, 7, 10, 4, 3, 2, 3, 10, 3, 9, 4, 3}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 5.8125; if(result == expected) { cout << "Test Case 1: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 1: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test2() { vector<int> scores = {1, 4, 1, 1, 2, 10, 6, 4, 8, 6, 6, 3, 3, 9, 2, 2, 5, 3, 4, 9, 9, 10, 9, 4, 7, 7, 4, 10, 10, 9, 9, 6, 4, 5, 3, 10, 8, 9, 9, 9, 4, 5, 1}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 6.0; if(result == expected) { cout << "Test Case 2: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 2: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test3() { vector<int> scores = {2, 5, 8, 2, 4, 1, 7, 4, 3, 2, 8, 5, 1, 2, 7, 1, 10}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 4.235294117647059; if(result == expected) { cout << "Test Case 3: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 3: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test4() { vector<int> scores = {8, 6, 7, 3, 1, 4, 5, 4, 5, 5, 10, 7, 1}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 5.142857142857143; if(result == expected) { cout << "Test Case 4: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 4: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test5() { vector<int> scores = {6, 5, 10, 2, 9, 1, 8, 9}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 7.0; if(result == expected) { cout << "Test Case 5: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 5: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test6() { vector<int> scores = {44, 12, 21, 6, 25, 77, 56, 77, 11, 45, 32, 68, 28, 23, 47, 4, 32, 59, 59, 95, 94, 34, 80, 46, 85, 31, 86, 39, 52, 90, 38, 40, 89, 67, 64, 84, 7, 46, 25, 95}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 50.36842105263158; if(result == expected) { cout << "Test Case 6: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 6: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test7() { vector<int> scores = {98, 42, 16, 35, 60, 29, 60, 92, 62, 66, 62, 29, 83, 49, 81, 36, 60, 98, 58, 50, 52, 21, 90, 82, 64, 43, 42, 53, 78, 68, 53, 27, 94, 30}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 59.0; if(result == expected) { cout << "Test Case 7: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 7: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test8() { vector<int> scores = {45, 85, 14, 59, 19, 86, 62, 61, 33, 67, 99, 81, 16, 97, 20, 70, 62, 78, 82, 32, 86, 61, 34, 8, 36, 79, 80, 17, 25, 22, 57, 22, 77, 35, 94, 41, 42, 7, 50, 16, 61, 68, 42, 94, 6, 29, 52, 32, 81, 88}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 54.5; if(result == expected) { cout << "Test Case 8: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 8: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test9() { vector<int> scores = {44, 94, 17, 65, 30, 4, 7, 60, 85, 53, 64, 61, 60, 92, 84}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 60.333333333333336; if(result == expected) { cout << "Test Case 9: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 9: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test10() { vector<int> scores = {22, 13, 94, 10, 66, 82, 80, 95, 3, 10, 4, 79, 20, 2, 83, 79, 75, 49, 13, 40, 43, 8, 89, 38, 62, 58, 66, 3, 40, 90}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 49.5; if(result == expected) { cout << "Test Case 10: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 10: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test11() { vector<int> scores = {80, 17, 7, 78, 42, 9, 3, 7, 32, 66, 55, 63, 31, 29, 98, 43, 98, 41, 92, 95, 19, 36}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 47.31818181818182; if(result == expected) { cout << "Test Case 11: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 11: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test12() { vector<int> scores = {6, 41, 52, 81, 68, 87, 1, 46, 85, 34, 11, 25, 20, 62, 23, 37, 95, 35, 5, 58, 9, 57, 41, 12, 54, 96, 98, 50, 34, 6, 49, 10, 77, 97, 98, 54, 68, 38, 1, 77, 47, 82, 97, 90, 71, 66, 45, 39, 42, 78}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 51.63333333333333; if(result == expected) { cout << "Test Case 12: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 12: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test13() { vector<int> scores = {30, 75, 86, 26, 33, 18, 61, 69, 44, 34, 89, 46, 15, 2, 66, 14, 28, 32, 58, 86, 70, 34, 14, 64, 15, 79, 67, 63, 6, 84, 7, 94, 36, 87, 96, 37, 84, 14, 49, 83, 14, 24, 40, 71, 46, 93, 40, 82, 16}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 49.42553191489362; if(result == expected) { cout << "Test Case 13: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 13: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test14() { vector<int> scores = {69, 21, 57, 82, 48, 43, 7, 24, 91, 48, 74, 39, 60, 8, 68, 99, 17, 18, 34, 66, 12, 37, 63, 27, 44, 60, 21, 71, 11, 19, 53, 38, 37, 89, 8, 33, 74, 65, 95, 75, 83, 30, 50, 1, 79, 26, 37, 95, 23, 28}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 47.14; if(result == expected) { cout << "Test Case 14: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 14: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test15() { vector<int> scores = {43, 6, 29, 80, 96, 67, 100, 72, 3, 100, 49, 32, 80, 16, 64, 1, 49, 74, 97, 30, 67, 36, 23, 55, 10, 71, 25, 16, 85, 44, 17, 70, 24, 80, 31, 80, 77, 62, 96, 4, 70, 97, 64, 5, 14, 73, 68, 88, 29, 2}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 58.5; if(result == expected) { cout << "Test Case 15: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 15: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test16() { vector<int> scores = {26, 92, 92, 24, 44, 16, 71, 13, 68, 75, 51, 51, 92, 2, 84, 49, 4, 80, 94, 44, 61, 26, 23, 55, 74, 78, 87, 46, 30, 22, 41, 54, 44, 75, 41, 57, 50, 17, 21, 2, 10, 32, 68, 83, 20, 43, 3, 93, 11, 41}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 47.6; if(result == expected) { cout << "Test Case 16: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 16: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test17() { vector<int> scores = {56, 30, 41, 99, 92, 10, 70, 60, 30, 91, 87, 71, 31, 82, 99, 21, 58, 81, 52, 88, 44, 53, 85, 2, 57, 59, 33, 86, 8, 58, 90, 81, 63, 68, 95, 75, 5, 31, 49, 71, 68, 78, 92, 76, 59, 52}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 64.31818181818181; if(result == expected) { cout << "Test Case 17: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 17: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test18() { vector<int> scores = {90, 22, 48, 74, 40, 91, 98, 89}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 81.5; if(result == expected) { cout << "Test Case 18: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 18: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test19() { vector<int> scores = {97, 84, 28, 11, 78, 21, 89}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 78.0; if(result == expected) { cout << "Test Case 19: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 19: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test20() { vector<int> scores = {759, 874, 334, 665, 963, 858, 196, 936, 644, 135, 810, 1000, 921, 741, 375, 527, 595, 659, 286, 73, 86, 432, 656, 214, 66, 112, 258, 680, 915, 879, 881, 601, 966, 69, 740, 867, 702, 90, 498, 403, 613, 508, 387, 699, 918}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 644.0; if(result == expected) { cout << "Test Case 20: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 20: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test21() { vector<int> scores = {731, 168, 59, 451, 724, 851, 178, 556, 618, 859, 118, 655, 125, 179, 507, 153, 211, 408, 473, 148, 93, 455, 301, 572, 699, 492, 828, 974, 257, 861, 602, 867, 444, 8, 11, 636, 560, 683, 103, 990, 228, 835, 195, 928, 353, 966, 397, 386, 310, 276}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 469.64; if(result == expected) { cout << "Test Case 21: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 21: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test22() { vector<int> scores = {384, 575, 43, 985, 679, 551, 923, 81, 40, 812, 315, 429, 171, 546, 25, 522, 997, 443, 695, 573, 621, 773, 372, 626, 971, 820, 328, 530, 722, 674, 692, 747, 49, 276, 249, 907, 836, 831, 393, 236, 304, 395, 955, 855, 558, 22, 194, 642, 295, 1000}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 559.5; if(result == expected) { cout << "Test Case 22: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 22: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test23() { vector<int> scores = {252, 386, 470, 727, 714, 826, 384, 673, 851, 307, 800, 96, 633, 462, 355, 664, 265, 443, 266, 668}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 516.3888888888889; if(result == expected) { cout << "Test Case 23: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 23: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test24() { vector<int> scores = {270, 422, 582, 287, 661, 927, 491, 441, 361, 891, 654, 875, 196, 605, 84, 789, 530, 972, 312, 277, 331, 182, 1000, 107, 895, 949, 880, 283, 947, 656, 445, 467, 491, 261, 69, 206, 136}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 511.6756756756757; if(result == expected) { cout << "Test Case 24: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 24: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test25() { vector<int> scores = {892, 1000, 980, 705, 810, 83, 988, 420, 724, 153, 126, 417, 631, 803, 962, 367, 893, 777, 622, 145, 489, 139, 724, 730, 469, 176, 495, 305, 286, 44, 686, 914, 350, 391, 912, 85, 538, 636, 625, 179, 829, 160, 676, 646, 965, 324, 321, 848, 189, 155}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 580.0; if(result == expected) { cout << "Test Case 25: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 25: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test26() { vector<int> scores = {127, 107, 32, 199, 239, 458, 50, 833, 945, 59, 257, 944, 11, 887, 686, 964, 703, 968, 174, 44, 144, 633, 112, 172, 515, 650, 831, 624, 99, 425, 873, 160, 7, 350, 161, 820, 984, 134, 930, 10, 525, 258, 277, 565, 569, 432, 949, 921, 136, 154}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 442.14; if(result == expected) { cout << "Test Case 26: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 26: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test27() { vector<int> scores = {181, 581, 366, 337, 703, 928, 47, 221, 1000, 687, 41, 443, 564, 946, 810, 727, 962, 667, 239, 584, 625, 462, 733, 560, 230, 549, 1000, 227, 566, 55, 250, 76, 947, 730, 262, 141, 261, 742, 538, 486, 636, 60, 550, 472, 420, 7, 55, 906, 26, 66}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 512.0; if(result == expected) { cout << "Test Case 27: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 27: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test28() { vector<int> scores = {875, 159, 123, 307, 537, 619, 982, 547, 642, 707, 84, 335, 841, 206, 853, 551, 875, 933, 860, 436, 546, 681, 787, 390, 521, 25, 399, 750, 897, 484, 980, 621, 596, 187, 924, 875, 665, 363, 852, 44, 216, 106, 872}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 596.9047619047619; if(result == expected) { cout << "Test Case 28: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 28: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test29() { vector<int> scores = {366, 943, 192, 443, 818, 711, 139, 101, 344, 294, 315, 51, 150, 699, 208, 437, 902}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 418.4117647058824; if(result == expected) { cout << "Test Case 29: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 29: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test30() { vector<int> scores = {90, 336, 588, 238, 185, 239, 376, 143, 168, 502, 46, 593, 1000, 888, 388, 1000, 34, 169, 299, 661, 505, 918, 850, 666, 188, 19, 967, 689, 596, 757, 95, 107, 219, 386, 665, 864, 347, 294, 126, 638, 985, 872, 203, 928, 146, 539, 594, 354, 644, 985}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 481.78; if(result == expected) { cout << "Test Case 30: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 30: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test31() { vector<int> scores = {820, 816, 173, 982, 942, 927, 784, 483, 292, 675, 279, 725, 121, 95, 490, 643, 568, 777, 888, 370, 480, 239, 105, 761, 896, 952, 596, 674, 900, 237, 51, 210, 207, 952, 276, 685, 266, 1000, 785, 308, 827, 579, 641, 944, 153, 495, 368, 340, 927, 844}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 618.5; if(result == expected) { cout << "Test Case 31: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 31: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test32() { vector<int> scores = {542, 351, 1000, 227, 766, 281, 1000, 139, 314, 524, 101, 671, 273, 908, 791, 561, 927, 853, 936, 509, 1000, 543, 446, 413, 952, 626, 145, 764, 594, 444, 939, 13, 72, 929, 236, 189, 291, 914, 976, 294, 227, 161, 501, 5, 161, 915, 215, 366, 627, 823}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 531.2391304347826; if(result == expected) { cout << "Test Case 32: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 32: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test33() { vector<int> scores = {446, 144, 759, 412, 210, 949, 941, 847, 374, 199, 696, 430, 288, 441, 846, 994, 991, 432, 531, 466, 142, 101, 747, 675, 333, 203, 269, 127, 50, 755, 346, 406, 59, 300, 748, 611, 647, 110, 497, 305, 966, 1000, 186, 733, 495, 57, 783, 221, 561, 237}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 481.32; if(result == expected) { cout << "Test Case 33: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 33: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test34() { vector<int> scores = {129, 811, 648, 148, 889, 863, 727, 34, 408, 996, 229, 611, 984, 860, 28, 806, 157, 294, 684, 743, 318, 213, 817, 491, 193, 480, 400, 396, 998, 922, 801, 977, 616, 357, 532, 321, 383, 803, 13, 249, 937, 494, 18, 765, 426, 265, 935, 204, 209, 790}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 531.5238095238095; if(result == expected) { cout << "Test Case 34: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 34: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test35() { vector<int> scores = {55, 638, 905, 438, 114, 225, 92, 901, 364, 260, 5, 150, 348, 524, 933, 464, 156, 444, 386, 437, 955, 570, 951, 66, 974, 278, 810, 534, 262, 904, 703, 727, 904, 1000, 715, 722, 632, 197, 204, 993, 343, 64, 855, 402, 912, 503, 593, 133, 589, 312}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 513.3541666666666; if(result == expected) { cout << "Test Case 35: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 35: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test36() { vector<int> scores = {278, 143, 212, 679, 316, 382, 35, 935, 433, 254, 329, 649, 596, 642, 184, 388, 459, 549, 502, 662, 108, 1000}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 442.5; if(result == expected) { cout << "Test Case 36: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 36: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test37() { vector<int> scores = {377, 606, 404, 176, 467, 251, 508, 251, 429, 889, 926, 766, 38, 714, 182, 217, 104, 192, 473, 668, 220, 629, 718, 962, 666, 490, 416, 507, 292, 750, 1000, 303, 595, 834, 657, 191, 657, 506, 848, 526, 329, 550, 272, 64, 412, 178, 542, 321, 854, 395}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 486.44; if(result == expected) { cout << "Test Case 37: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 37: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test38() { vector<int> scores = {9, 32, 3, 532, 31, 247, 631, 786, 604, 988, 303, 1000, 754, 461, 133, 431, 173, 245, 586, 497, 376, 800, 613, 268, 34, 113, 701, 605, 866, 599, 602, 735, 537, 701, 967, 507, 216, 897, 698, 162, 162, 552, 246, 666, 755, 976, 625, 533, 768, 357}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 556.5; if(result == expected) { cout << "Test Case 38: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 38: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test39() { vector<int> scores = {392, 65, 24, 382, 954, 557}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 395.6666666666667; if(result == expected) { cout << "Test Case 39: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 39: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test40() { vector<int> scores = {179, 540, 325, 852, 372, 344, 339, 795, 646, 44, 244, 290, 506, 121, 596, 879, 13, 663, 313, 66, 332, 748, 579, 75, 1000, 445, 882, 283, 184, 323, 488, 985, 604, 514, 240, 54, 290, 342, 576, 930, 267}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 445.5609756097561; if(result == expected) { cout << "Test Case 40: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 40: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test41() { vector<int> scores = {891, 193, 897, 190, 250, 792, 58, 656, 460, 781, 351, 859, 251, 526, 750, 567, 17, 784, 349, 463, 731, 827, 896, 696, 109, 739, 940, 1, 358, 699, 29, 523, 886, 325, 661, 922, 541, 141, 838, 301, 181, 23, 754, 651, 434, 790, 81, 671, 809, 734}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 609.0; if(result == expected) { cout << "Test Case 41: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 41: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test42() { vector<int> scores = {389, 143, 412}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 389.0; if(result == expected) { cout << "Test Case 42: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 42: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test43() { vector<int> scores = {229, 452, 325, 858, 640, 847, 716, 131, 264, 1000, 408, 639, 821, 836, 821, 761, 277, 507, 842, 589, 932, 751, 971, 748, 668, 447, 367, 3, 142, 651, 101, 855, 306, 763, 323, 627, 508, 131, 575, 774, 239, 997, 161, 647, 438, 503, 632, 282, 241, 422}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 582.0; if(result == expected) { cout << "Test Case 43: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 43: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test44() { vector<int> scores = {951, 461, 827, 149, 393, 471, 221, 938, 148, 786, 87, 252, 411, 70, 540, 196, 833, 924, 392, 890, 110, 872, 617, 328, 500, 326, 958, 446, 883, 872, 959, 967, 890, 46, 285, 476, 750, 1000, 394, 631, 944, 312, 380, 203, 634, 715, 302, 434, 10, 137}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 529.1428571428571; if(result == expected) { cout << "Test Case 44: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 44: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test45() { vector<int> scores = {231, 387, 538, 641, 629, 16, 12, 546, 111, 970, 803, 76, 226, 476, 496, 797, 8, 484, 165, 207}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 431.5; if(result == expected) { cout << "Test Case 45: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 45: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test46() { vector<int> scores = {669, 808, 385, 312, 444, 358, 570, 500, 791, 490, 299, 236, 780, 686, 820, 784, 33, 49, 682, 499, 1000, 713, 856, 965, 806, 571, 963, 897, 307, 905, 947, 359, 676, 267, 1000, 941, 808, 193, 839, 882, 688, 232}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 685.6666666666666; if(result == expected) { cout << "Test Case 46: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 46: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test47() { vector<int> scores = {499, 467, 715, 907, 513, 368, 988, 735, 435, 405, 259, 232, 88, 927, 54, 408, 175, 931, 74, 830, 859, 269, 777, 76, 401, 647, 388}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 497.2962962962963; if(result == expected) { cout << "Test Case 47: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 47: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test48() { vector<int> scores = {20, 285, 683, 630, 611, 670, 26, 652, 560, 837, 310, 71, 789, 664, 121, 262, 643, 913, 778, 803, 1000, 1000, 657, 120, 384, 800, 329, 546, 76, 929, 87, 388, 450, 165, 90, 655, 164, 566, 67, 833, 646, 232, 615, 108, 386, 187, 978, 953, 558, 834}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 576.0; if(result == expected) { cout << "Test Case 48: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 48: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test49() { vector<int> scores = {748, 459, 261, 517, 106, 191, 549, 1000, 248, 326, 574, 480, 709, 612, 913, 797, 427, 798, 355, 237, 178, 489, 416, 406, 214, 99, 452, 439, 266, 833, 763, 987, 892, 648, 391, 591, 27, 513, 867, 817, 87, 486, 550, 714, 39, 994, 41, 30, 81, 57}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 473.48; if(result == expected) { cout << "Test Case 49: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 49: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test50() { vector<int> scores = {960, 486, 834, 182, 235, 779, 798, 892, 207, 255, 420, 772, 41, 858, 667, 75, 790, 147, 556, 35, 809, 965, 918, 800, 955, 947, 36, 181, 130, 777, 605, 411, 614, 485, 378, 370, 655, 149, 285, 939, 963, 931, 319, 933, 495, 270, 618, 22, 3, 731}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 580.5; if(result == expected) { cout << "Test Case 50: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 50: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test51() { vector<int> scores = {429, 3, 716, 958, 246, 347, 880, 274, 893, 372, 604, 1000, 54, 644, 951, 887, 796, 170, 764, 454, 25, 314, 251, 506, 294, 86, 801, 607, 947}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 536.1052631578947; if(result == expected) { cout << "Test Case 51: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 51: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test52() { vector<int> scores = {1000, 737, 329, 488, 244, 964, 878, 84, 358, 149, 713, 26, 720, 864, 390, 453, 613, 35, 252, 355, 966, 131, 653, 989, 273, 958, 974, 645, 26, 737, 488, 238, 248, 315, 63, 256, 452, 273, 593, 331, 925, 147, 224, 412, 239, 783, 595, 462, 245, 613}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 478.12; if(result == expected) { cout << "Test Case 52: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 52: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test53() { vector<int> scores = {739, 125, 187, 209, 596, 1000, 625, 999, 932, 641, 87, 383, 59, 734, 542, 982, 370, 196, 269, 358, 235, 30, 757, 11, 803, 321, 359, 869, 74, 626, 292, 637, 850, 680, 469, 171, 838, 404, 509, 439, 733, 223, 811, 318, 591, 691, 628, 343, 871, 380}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 499.92; if(result == expected) { cout << "Test Case 53: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 53: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test54() { vector<int> scores = {119, 985, 240, 420, 658, 471, 77, 209}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 397.375; if(result == expected) { cout << "Test Case 54: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 54: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test55() { vector<int> scores = {735, 481, 842, 174, 215, 976, 827, 996, 347, 530, 584, 391, 854, 443, 964, 1000, 719, 383, 804, 522, 774, 885, 691, 842, 704, 27, 647, 701, 735, 667, 947, 375, 821, 588, 958, 53, 410, 380, 84, 68, 828, 365, 828, 926, 55, 925, 650, 87, 358, 74}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 663.75; if(result == expected) { cout << "Test Case 55: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 55: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test56() { vector<int> scores = {823, 120, 566, 812, 425, 582, 936, 901, 723, 867, 179, 118, 7, 757, 698, 360, 90, 964, 308, 136, 914, 913, 941, 192, 70, 169, 269, 997, 320, 442, 29, 306, 550, 996, 327, 1000, 858, 787, 414, 648, 286, 141, 798, 387, 508, 967, 564, 816, 101, 381}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 532.9615384615385; if(result == expected) { cout << "Test Case 56: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 56: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test57() { vector<int> scores = {831, 920, 257, 219, 699, 965, 980, 148, 61, 370, 883, 511, 96, 31, 371, 49, 628, 37, 464, 5, 375, 996, 899, 611, 321, 29, 850, 961, 1000, 925, 236, 233, 993, 540, 565, 253, 279, 612, 223, 185, 1000, 950, 570, 761, 904, 617, 333, 635, 19, 980}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 552.5; if(result == expected) { cout << "Test Case 57: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 57: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test58() { vector<int> scores = {229, 569, 366, 365, 778, 535, 820, 831, 617, 698, 331, 58, 1000, 470, 231, 469, 30, 955, 107, 754, 5, 900, 722, 439, 18, 914, 589, 921, 941, 569, 557, 953, 583, 696, 4, 884, 411, 623, 7, 309, 308, 588, 183, 398, 816}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 569.0; if(result == expected) { cout << "Test Case 58: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 58: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test59() { vector<int> scores = {449, 648, 579, 655, 546, 311, 255, 836, 398, 401, 594, 358, 275, 128, 848, 589, 762, 53, 562, 219, 494, 704, 671, 176, 864, 733, 811, 412, 297, 785, 30, 858, 625, 758, 886, 379, 976, 723, 559, 928, 692, 368, 705, 492, 3, 41, 235, 441, 513, 320}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 552.5; if(result == expected) { cout << "Test Case 59: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 59: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test60() { vector<int> scores = {650, 371, 120, 670, 833, 517, 479, 853, 915, 489, 747, 72, 440, 193, 456, 958, 103, 447, 753, 541, 257, 266, 254, 616, 525, 100, 700, 6, 484, 779, 899, 453, 429, 220, 452, 542, 140, 190, 994, 187, 791, 574, 835, 310, 778, 631, 422, 804, 827, 53}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 509.4; if(result == expected) { cout << "Test Case 60: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 60: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test61() { vector<int> scores = {850, 976, 858, 992, 590, 687, 896, 99, 41, 54, 479, 934, 380, 45, 625, 973, 425, 760, 85, 654, 611, 785, 370, 577, 113, 694, 348, 311, 430, 479, 891}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 592.6666666666666; if(result == expected) { cout << "Test Case 61: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 61: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test62() { vector<int> scores = {85, 115, 106, 449, 891, 187, 669, 324, 221, 535, 583, 592, 988, 1000, 122, 955, 454, 237, 400, 909, 855, 618, 715, 527, 896, 38, 824, 804, 870, 59, 985, 476, 942, 852, 770, 583, 760, 282, 772, 391, 425, 239, 9, 41, 750, 735, 319, 694, 766, 211}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 583.0; if(result == expected) { cout << "Test Case 62: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 62: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test63() { vector<int> scores = {132, 671, 8, 402, 210, 1000, 704, 467, 532, 84, 568, 406, 908, 998, 217, 492, 282, 460, 178, 509, 341, 534, 550, 750, 474, 185, 738, 776, 485, 471, 275, 22, 798, 833, 725, 270, 181}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 479.7142857142857; if(result == expected) { cout << "Test Case 63: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 63: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test64() { vector<int> scores = {1}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 1.0; if(result == expected) { cout << "Test Case 64: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 64: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test65() { vector<int> scores = {1, 2, 3, 4}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 2.5; if(result == expected) { cout << "Test Case 65: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 65: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test66() { vector<int> scores = {1, 1, 999, 999, 1000, 1000}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 999.0; if(result == expected) { cout << "Test Case 66: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 66: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test67() { vector<int> scores = {1, 13, 8, 6, 7, 9}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 7.5; if(result == expected) { cout << "Test Case 67: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 67: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test68() { vector<int> scores = {10, 31, 31, 31, 130, 130, 130}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 70.6; if(result == expected) { cout << "Test Case 68: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 68: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test69() { vector<int> scores = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 1.0; if(result == expected) { cout << "Test Case 69: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 69: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test70() { vector<int> scores = {10, 11, 1000}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 340.3333333333333; if(result == expected) { cout << "Test Case 70: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 70: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test71() { vector<int> scores = {1, 1, 999, 999, 1000, 1000}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 999.0; if(result == expected) { cout << "Test Case 71: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 71: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test72() { vector<int> scores = {1, 13, 8, 6, 7, 9}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 7.5; if(result == expected) { cout << "Test Case 72: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 72: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test73() { vector<int> scores = {1, 2}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 1.5; if(result == expected) { cout << "Test Case 73: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 73: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test74() { vector<int> scores = {1, 1, 999, 999, 3, 1000, 1000}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 999.0; if(result == expected) { cout << "Test Case 74: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 74: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test75() { vector<int> scores = {1, 3, 4}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 3.0; if(result == expected) { cout << "Test Case 75: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 75: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test76() { vector<int> scores = {1, 1, 100}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 34.0; if(result == expected) { cout << "Test Case 76: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 76: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test77() { vector<int> scores = {5}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 5.0; if(result == expected) { cout << "Test Case 77: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 77: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test78() { vector<int> scores = {1, 2, 3, 4, 6}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 3.2; if(result == expected) { cout << "Test Case 78: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 78: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test79() { vector<int> scores = {1, 1, 1}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 1.0; if(result == expected) { cout << "Test Case 79: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 79: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test80() { vector<int> scores = {10, 10, 10, 1, 1}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 10.0; if(result == expected) { cout << "Test Case 80: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 80: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test81() { vector<int> scores = {1, 7, 9, 8, 1000}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 205.0; if(result == expected) { cout << "Test Case 81: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 81: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test82() { vector<int> scores = {1, 5, 6}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 5.0; if(result == expected) { cout << "Test Case 82: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 82: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test83() { vector<int> scores = {1, 100, 324}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 141.66666666666666; if(result == expected) { cout << "Test Case 83: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 83: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test84() { vector<int> scores = {1, 1, 9, 10, 10}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 9.0; if(result == expected) { cout << "Test Case 84: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 84: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test85() { vector<int> scores = {1, 2, 3, 5, 7}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 3.6; if(result == expected) { cout << "Test Case 85: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 85: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test86() { vector<int> scores = {3}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 3.0; if(result == expected) { cout << "Test Case 86: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 86: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test87() { vector<int> scores = {1, 100, 101}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 100.0; if(result == expected) { cout << "Test Case 87: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 87: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test88() { vector<int> scores = {1, 1, 1, 2, 2}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 1.4; if(result == expected) { cout << "Test Case 88: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 88: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test89() { vector<int> scores = {1}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 1.0; if(result == expected) { cout << "Test Case 89: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 89: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test90() { vector<int> scores = {1, 1}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 1.0; if(result == expected) { cout << "Test Case 90: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 90: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test91() { vector<int> scores = {2, 2, 2, 4}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 2.5; if(result == expected) { cout << "Test Case 91: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 91: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test92() { vector<int> scores = {1, 54, 7, 78, 29, 3}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 28.666666666666668; if(result == expected) { cout << "Test Case 92: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 92: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test93() { vector<int> scores = {1, 2, 3, 10, 20, 30, 100}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 23.714285714285715; if(result == expected) { cout << "Test Case 93: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 93: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test94() { vector<int> scores = {1, 6}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 3.5; if(result == expected) { cout << "Test Case 94: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 94: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test95() { vector<int> scores = {7, 8, 1, 7, 8}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 7.333333333333333; if(result == expected) { cout << "Test Case 95: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 95: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test96() { vector<int> scores = {5, 2, 5, 1, 3, 2, 1, 10, 3}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 3.5555555555555554; if(result == expected) { cout << "Test Case 96: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 96: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test97() { vector<int> scores = {3, 5, 3}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 3.6666666666666665; if(result == expected) { cout << "Test Case 97: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 97: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test98() { vector<int> scores = {1, 2, 10, 10, 10}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 10.0; if(result == expected) { cout << "Test Case 98: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 98: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test99() { vector<int> scores = {1, 8, 9}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 8.0; if(result == expected) { cout << "Test Case 99: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 99: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test100() { vector<int> scores = {1, 3, 6, 6, 100, 101}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 36.166666666666664; if(result == expected) { cout << "Test Case 100: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 100: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test101() { vector<int> scores = {1, 2, 2, 2, 100}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 21.4; if(result == expected) { cout << "Test Case 101: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 101: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test102() { vector<int> scores = {1, 1, 1, 2, 2, 2}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 1.5; if(result == expected) { cout << "Test Case 102: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 102: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test103() { vector<int> scores = {1, 2, 99, 100, 101}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 99.0; if(result == expected) { cout << "Test Case 103: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 103: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test104() { vector<int> scores = {1, 13, 8, 6, 7, 9, 8, 5, 6, 9, 3}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 7.0; if(result == expected) { cout << "Test Case 104: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 104: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test105() { vector<int> scores = {1, 10, 11}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 10.0; if(result == expected) { cout << "Test Case 105: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 105: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test106() { vector<int> scores = {2, 5, 8, 9, 10, 11}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 8.5; if(result == expected) { cout << "Test Case 106: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 106: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test107() { vector<int> scores = {1, 2, 1000}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 334.3333333333333; if(result == expected) { cout << "Test Case 107: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 107: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test108() { vector<int> scores = {1, 3, 3, 4}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 3.0; if(result == expected) { cout << "Test Case 108: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 108: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test109() { vector<int> scores = {1, 1, 1, 1, 2, 2, 100, 100, 100, 100}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 40.8; if(result == expected) { cout << "Test Case 109: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 109: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test110() { vector<int> scores = {1, 3, 6, 6, 100, 101, 100, 101, 1, 3}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 42.2; if(result == expected) { cout << "Test Case 110: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 110: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test111() { vector<int> scores = {1, 2, 700, 701, 703, 704}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 700.5; if(result == expected) { cout << "Test Case 111: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 111: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test112() { vector<int> scores = {1, 6, 7}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 6.0; if(result == expected) { cout << "Test Case 112: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 112: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test113() { vector<int> scores = {7, 8, 10, 11, 12}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 10.0; if(result == expected) { cout << "Test Case 113: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 113: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test114() { vector<int> scores = {1, 3, 3}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 3.0; if(result == expected) { cout << "Test Case 114: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 114: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test115() { vector<int> scores = {4, 5}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 4.5; if(result == expected) { cout << "Test Case 115: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 115: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test116() { vector<int> scores = {5, 8, 8}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 8.0; if(result == expected) { cout << "Test Case 116: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 116: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test117() { vector<int> scores = {1, 2, 1}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 1.3333333333333333; if(result == expected) { cout << "Test Case 117: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 117: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test118() { vector<int> scores = {9, 1, 10}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 9.0; if(result == expected) { cout << "Test Case 118: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 118: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test119() { vector<int> scores = {9, 1, 9}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 9.0; if(result == expected) { cout << "Test Case 119: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 119: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test120() { vector<int> scores = {1, 2, 2, 5}; ContestCoordinator* pObj = new ContestCoordinator(); clock_t start = clock(); double result = pObj->bestAverage(scores); clock_t end = clock(); delete pObj; double expected = 2.5; if(result == expected) { cout << "Test Case 120: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 120: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int main(int argc, char* argv[]) { int passed = 0; int failed = 0; test0() == 0 ? ++passed : ++failed; test1() == 0 ? ++passed : ++failed; test2() == 0 ? ++passed : ++failed; test3() == 0 ? ++passed : ++failed; test4() == 0 ? ++passed : ++failed; test5() == 0 ? ++passed : ++failed; test6() == 0 ? ++passed : ++failed; test7() == 0 ? ++passed : ++failed; test8() == 0 ? ++passed : ++failed; test9() == 0 ? ++passed : ++failed; test10() == 0 ? ++passed : ++failed; test11() == 0 ? ++passed : ++failed; test12() == 0 ? ++passed : ++failed; test13() == 0 ? ++passed : ++failed; test14() == 0 ? ++passed : ++failed; test15() == 0 ? ++passed : ++failed; test16() == 0 ? ++passed : ++failed; test17() == 0 ? ++passed : ++failed; test18() == 0 ? ++passed : ++failed; test19() == 0 ? ++passed : ++failed; test20() == 0 ? ++passed : ++failed; test21() == 0 ? ++passed : ++failed; test22() == 0 ? ++passed : ++failed; test23() == 0 ? ++passed : ++failed; test24() == 0 ? ++passed : ++failed; test25() == 0 ? ++passed : ++failed; test26() == 0 ? ++passed : ++failed; test27() == 0 ? ++passed : ++failed; test28() == 0 ? ++passed : ++failed; test29() == 0 ? ++passed : ++failed; test30() == 0 ? ++passed : ++failed; test31() == 0 ? ++passed : ++failed; test32() == 0 ? ++passed : ++failed; test33() == 0 ? ++passed : ++failed; test34() == 0 ? ++passed : ++failed; test35() == 0 ? ++passed : ++failed; test36() == 0 ? ++passed : ++failed; test37() == 0 ? ++passed : ++failed; test38() == 0 ? ++passed : ++failed; test39() == 0 ? ++passed : ++failed; test40() == 0 ? ++passed : ++failed; test41() == 0 ? ++passed : ++failed; test42() == 0 ? ++passed : ++failed; test43() == 0 ? ++passed : ++failed; test44() == 0 ? ++passed : ++failed; test45() == 0 ? ++passed : ++failed; test46() == 0 ? ++passed : ++failed; test47() == 0 ? ++passed : ++failed; test48() == 0 ? ++passed : ++failed; test49() == 0 ? ++passed : ++failed; test50() == 0 ? ++passed : ++failed; test51() == 0 ? ++passed : ++failed; test52() == 0 ? ++passed : ++failed; test53() == 0 ? ++passed : ++failed; test54() == 0 ? ++passed : ++failed; test55() == 0 ? ++passed : ++failed; test56() == 0 ? ++passed : ++failed; test57() == 0 ? ++passed : ++failed; test58() == 0 ? ++passed : ++failed; test59() == 0 ? ++passed : ++failed; test60() == 0 ? ++passed : ++failed; test61() == 0 ? ++passed : ++failed; test62() == 0 ? ++passed : ++failed; test63() == 0 ? ++passed : ++failed; test64() == 0 ? ++passed : ++failed; test65() == 0 ? ++passed : ++failed; test66() == 0 ? ++passed : ++failed; test67() == 0 ? ++passed : ++failed; test68() == 0 ? ++passed : ++failed; test69() == 0 ? ++passed : ++failed; test70() == 0 ? ++passed : ++failed; test71() == 0 ? ++passed : ++failed; test72() == 0 ? ++passed : ++failed; test73() == 0 ? ++passed : ++failed; test74() == 0 ? ++passed : ++failed; test75() == 0 ? ++passed : ++failed; test76() == 0 ? ++passed : ++failed; test77() == 0 ? ++passed : ++failed; test78() == 0 ? ++passed : ++failed; test79() == 0 ? ++passed : ++failed; test80() == 0 ? ++passed : ++failed; test81() == 0 ? ++passed : ++failed; test82() == 0 ? ++passed : ++failed; test83() == 0 ? ++passed : ++failed; test84() == 0 ? ++passed : ++failed; test85() == 0 ? ++passed : ++failed; test86() == 0 ? ++passed : ++failed; test87() == 0 ? ++passed : ++failed; test88() == 0 ? ++passed : ++failed; test89() == 0 ? ++passed : ++failed; test90() == 0 ? ++passed : ++failed; test91() == 0 ? ++passed : ++failed; test92() == 0 ? ++passed : ++failed; test93() == 0 ? ++passed : ++failed; test94() == 0 ? ++passed : ++failed; test95() == 0 ? ++passed : ++failed; test96() == 0 ? ++passed : ++failed; test97() == 0 ? ++passed : ++failed; test98() == 0 ? ++passed : ++failed; test99() == 0 ? ++passed : ++failed; test100() == 0 ? ++passed : ++failed; test101() == 0 ? ++passed : ++failed; test102() == 0 ? ++passed : ++failed; test103() == 0 ? ++passed : ++failed; test104() == 0 ? ++passed : ++failed; test105() == 0 ? ++passed : ++failed; test106() == 0 ? ++passed : ++failed; test107() == 0 ? ++passed : ++failed; test108() == 0 ? ++passed : ++failed; test109() == 0 ? ++passed : ++failed; test110() == 0 ? ++passed : ++failed; test111() == 0 ? ++passed : ++failed; test112() == 0 ? ++passed : ++failed; test113() == 0 ? ++passed : ++failed; test114() == 0 ? ++passed : ++failed; test115() == 0 ? ++passed : ++failed; test116() == 0 ? ++passed : ++failed; test117() == 0 ? ++passed : ++failed; test118() == 0 ? ++passed : ++failed; test119() == 0 ? ++passed : ++failed; test120() == 0 ? ++passed : ++failed; cout << "Total Test Case: " << passed + failed << "; Passed: " << passed << "; Failed: " << failed << endl; return failed == 0 ? 0 : 1; } /******************************************************************************* * Top Submission URL: * http://community.topcoder.com/stat?c=problem_solution&cr=21620711&rd=9989&pm=6243 ******************************************************************************** #include <vector> #include <iostream> # define FOR(i,x,y) for(i=x;i<y;i++) # define si size() using namespace std; class ContestCoordinator { public: double bestAverage(vector <int> scores) { int i=0,j=0; sort(scores.begin(),scores.end()); double avg=0.0; double max=0.0; FOR(i,0,scores.si) { int temp=0; int c=0; FOR(j,i,scores.si-i) { temp+=scores[j]; c++; } if(c!=0) avg=(double)temp/c; if(avg>max) max=avg; } return max; } }; // Powered by PopsEdit ******************************************************************************** *******************************************************************************/
[ "qiudejun@gmail.com" ]
qiudejun@gmail.com
69f210b3b44979f8aa7eefb2c4cb56b2fbcd0aa0
f7315930643edc12e76c229a742d5446dad77097
/src/frontends/lean/migrate_cmd.cpp
7b2ccb572f9f97d6134f91e85bb16cc816d48f2d
[ "Apache-2.0" ]
permissive
bmalehorn/lean
8f77b762a76c59afff7b7403f9eb5fc2c3ce70c1
53653c352643751c4b62ff63ec5e555f11dae8eb
refs/heads/master
2021-01-18T04:54:44.489033
2015-04-22T05:40:20
2015-04-22T05:44:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,842
cpp
/* Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "util/sexpr/option_declarations.h" #include "kernel/abstract.h" #include "kernel/instantiate.h" #include "library/reducible.h" #include "library/scoped_ext.h" #include "library/normalize.h" #include "library/explicit.h" #include "library/projection.h" #include "library/aliases.h" #include "library/coercion.h" #include "library/class.h" #include "library/locals.h" #include "library/placeholder.h" #include "library/util.h" #include "library/occurs.h" #include "library/module.h" #include "library/constants.h" #include "library/replace_visitor.h" #include "library/error_handling/error_handling.h" #include "frontends/lean/parser.h" #include "frontends/lean/util.h" #include "frontends/lean/decl_cmds.h" #include "frontends/lean/tokens.h" #ifndef LEAN_DEFAULT_MIGRATE_TRACE #define LEAN_DEFAULT_MIGRATE_TRACE false #endif namespace lean { static name * g_migrate_trace = nullptr; bool get_migrate_trace(options const & o) { return o.get_bool(*g_migrate_trace, LEAN_DEFAULT_MIGRATE_TRACE); } /** \brief Converter used by the migrate command. It treat definitions from a given set of namespaces as opaque. */ class migrate_converter : public unfold_semireducible_converter { list<name> m_namespaces; public: migrate_converter(environment const & env, list<name> const & ns): unfold_semireducible_converter(env, true, true), m_namespaces(ns) { } virtual bool is_opaque(declaration const & d) const { name const & n = d.get_name(); if (!is_instance(m_env, n) && std::any_of(m_namespaces.begin(), m_namespaces.end(), [&](name const & ns) { return is_prefix_of(ns, n); })) return true; return default_converter::is_opaque(d); } }; struct migrate_cmd_fn { parser & m_p; environment m_env; name_generator m_ngen; bool m_trace; type_checker_ptr m_tc; type_checker_ptr m_migrate_tc; pos_info m_pos; buffer<expr> m_params; level_param_names m_ls; name m_from; buffer<pair<name, expr>> m_replacements; buffer<pair<name, name>> m_renames; buffer<name> m_hiding; list<expr> m_ctx; buffer<expr> m_S_params; migrate_cmd_fn(parser & p): m_p(p), m_env(p.env()), m_ngen(p.mk_ngen()) { m_trace = get_migrate_trace(p.get_options()); } io_state_stream out() const { return regular(m_env, m_p.ios()); } expr whnf(expr const & e) { return m_tc->whnf(e).first; } expr infer_type(expr const & e) { return m_tc->infer(e).first; } /** \brief Return true iff type has at least m_S_params.size() + 1 args, and argument m_S_params.size() is inst_implicit */ bool check_sufficient_args(expr type) { for (unsigned i = 0; i < m_S_params.size(); i++) { if (!is_pi(type)) return false; type = binding_body(type); } return is_pi(type) && binding_info(type).is_inst_implicit(); } /** \brief Return true iff \c e is of the form (p a_1 ... a_n s ...), where \c p is a projection, n == m_S_params.size(), and s contains an instance */ bool is_projection_inst(expr const & e) { if (!is_app(e)) return false; expr const & f = get_app_fn(e); if (!is_constant(f) || !is_projection(m_env, const_name(f))) return false; buffer<expr> args; get_app_args(e, args); if (args.size() < m_S_params.size() + 1) return false; return true; // TODO(Leo): check if instance occurs here refine } class normalize_fn : public replace_visitor { migrate_cmd_fn & m_main; unsigned m_num_params; // number of parameters of the class expr visit_app(expr const & e) { buffer<expr> args; expr f = get_app_args(e, args); expr new_f = visit(f); for (expr & arg : args) arg = visit(arg); expr r = mk_app(new_f, args); if (is_constant(new_f) && args.size() >= m_num_params + 1) { name const & fname = const_name(new_f); if (is_projection(m_main.m_env, fname)) { return normalize(*m_main.m_migrate_tc, r, true); } else { for (auto const & p : m_main.m_replacements) { if (p.first == fname) { expr new_r = p.second; for (unsigned i = m_num_params + 1; i < args.size(); i++) new_r = mk_app(new_r, args[i]); if (m_main.m_tc->is_def_eq(r, new_r).first) return new_r; break; } } } } return r; } expr visit_binding(expr const & b) { expr new_domain = visit(binding_domain(b)); expr l = mk_local(m_main.m_tc->mk_fresh_name(), new_domain); expr new_body = abstract(visit(instantiate(binding_body(b), l)), l); return update_binding(b, new_domain, new_body); } public: normalize_fn(migrate_cmd_fn & m): m_main(m), m_num_params(m_main.m_S_params.size()) {} }; void migrate_decl(declaration const & d) { if (!check_sufficient_args(d.get_type())) { if (m_trace) out() << "skipped '" << d.get_name() << "': does not have sufficient number of arguments\n"; return; } name d_name = d.get_name(); if (is_projection(m_env, d_name)) { if (m_trace) out() << "skipped '" << d.get_name() << "': projections are ignored\n"; return; // we don't migrate projections } if (is_coercion(m_env, d_name)) { if (m_trace) out() << "skipped '" << d.get_name() << "': coercions are ignored\n"; return; // we don't migrate coercions } bool renamed = false; name short_name, full_name; for (auto const & p : m_renames) { if (p.first == d_name) { renamed = true; full_name = p.second; short_name = full_name.replace_prefix(full_name, name()); break; } } if (!renamed) { short_name = d_name.replace_prefix(m_from, name()); full_name = get_namespace(m_env) + short_name; } if (m_env.find(full_name)) { if (m_trace) out() << "skipped '" << d.get_name() << "': new name '" << full_name << "' has already been declared\n"; return; // already has this decl } try { expr d_inst = mk_app(mk_app(mk_explicit(mk_constant(d_name)), m_S_params), mk_strict_expr_placeholder()); expr v; level_param_names ls; std::tie(v, ls) = m_p.elaborate_relaxed(d_inst, m_ctx); ls = append(m_ls, ls); expr t = normalize_fn(*this)(infer_type(v)); expr new_type = Pi(m_params, t); expr new_value = Fun(m_params, v); try { if (d.is_axiom()) m_env = module::add(m_env, check(m_env, mk_theorem(full_name, ls, new_type, new_value))); else if (d.is_theorem()) m_env = module::add(m_env, check(m_env, mk_theorem(full_name, ls, new_type, new_value))); else m_env = module::add(m_env, check(m_env, mk_definition(m_env, full_name, ls, new_type, new_value, d.is_opaque()))); m_p.add_decl_index(full_name, m_pos, d.is_theorem() ? name("theorem") : name("definition"), new_type); if (short_name != full_name) m_env = add_expr_alias_rec(m_env, short_name, full_name); if (m_trace) out() << "migrated: " << full_name << " : " << new_type << "\n"; } catch (exception & ex) { if (m_trace) { out() << "failed to migrate '" << d.get_name() << "', kernel rejected new declaration\n"; ::lean::display_error(out(), nullptr, ex); out() << "\n"; } return; } } catch (exception & ex) { if (m_trace) { out() << "skipped '" << d.get_name() << "': failed to be elaborated\n"; ::lean::display_error(out(), nullptr, ex); out() << "\n"; } return; } } void parse_params() { if (!m_p.curr_is_token(get_from_tk())) { unsigned rbp = 0; m_p.parse_binders(m_params, rbp); } for (expr const & l : m_params) m_p.add_local(l); } void parse_S_params() { m_p.check_token_next(get_with_tk(), "invalid 'migrate' command, 'with' expected"); while (true) { m_S_params.push_back(m_p.parse_expr()); if (!m_p.curr_is_token(get_comma_tk())) break; m_p.next(); } } void parse_from_namespace() { m_p.check_token_next(get_from_tk(), "invalid 'migrate' command, 'from' expected"); if (!m_p.curr_is_identifier()) throw parser_error("invalid 'migrate' command, identifier expected", m_p.pos()); auto n = to_valid_namespace_name(m_env, m_p.get_name_val()); if (!n) throw parser_error(sstream() << "invalid 'migrate' command, '" << m_p.get_name_val() << "' is not a namespace", m_p.pos()); m_from = *n; m_p.next(); } name parse_source_id() { if (!m_p.curr_is_identifier()) throw parser_error("invalid 'migrate' command, identifier expected", m_p.pos()); name n = m_p.get_name_val(); if (!m_env.find(n)) { n = m_from + n; if (!m_env.find(n)) throw parser_error(sstream() << "invalid 'migrate' command, '" << n << "' is not a declaration", m_p.pos()); } else { if (is_prefix_of(m_from, n)) throw parser_error(sstream() << "invalid 'migrate' command, '" << n << "' is not in the source namespace", m_p.pos()); } m_p.next(); return n; } name parse_to_id() { if (!m_p.curr_is_identifier()) throw parser_error("invalid 'migrate' command, identifier expected", m_p.pos()); name n = m_p.get_name_val(); name ns = get_namespace(m_env); if (!is_prefix_of(ns, n)) n = ns + n; m_p.next(); return n; } void parse_modifiers() { while (m_p.curr_is_token(get_replacing_tk()) || m_p.curr_is_token(get_hiding_tk()) || m_p.curr_is_token(get_renaming_tk())) { if (m_p.curr_is_token(get_replacing_tk())) { m_p.next(); while (true) { name from_id = parse_source_id(); m_p.check_token_next(get_arrow_tk(), "invalid 'migrate' command, '->' expected"); expr to = m_p.parse_expr(); m_replacements.emplace_back(from_id, to); if (!m_p.curr_is_token(get_comma_tk())) break; m_p.next(); } } else if (m_p.curr_is_token(get_hiding_tk())) { m_p.next(); while (true) { name id = parse_source_id(); m_hiding.push_back(id); if (!m_p.curr_is_token(get_comma_tk())) break; m_p.next(); } } else if (m_p.curr_is_token(get_renaming_tk())) { m_p.next(); name from_id = parse_source_id(); m_p.check_token_next(get_arrow_tk(), "invalid 'migrate' command, '->' expected"); name to_id = parse_to_id(); m_renames.emplace_back(from_id, to_id); if (!m_p.curr_is_token(get_comma_tk())) break; m_p.next(); } else { lean_unreachable(); } } } expr update_locals(expr new_tmp, buffer<expr> & locals) { for (unsigned i = 0; i < locals.size(); i++) { expr new_local = mk_local(mlocal_name(locals[i]), binding_name(new_tmp), binding_domain(new_tmp), binding_info(new_tmp)); locals[i] = new_local; new_tmp = instantiate(binding_body(new_tmp), new_local); } return new_tmp; } // hack to treat expressions as type expr mk_as_type(expr const & e) { return mk_app(mk_constant(get_eq_name()), e, e); } expr get_as_type_expr(expr const & e) { lean_assert(is_eq(e)); return app_arg(e); } void elaborate() { buffer<expr> include_vars; m_p.get_include_variables(include_vars); buffer<expr> tmp_locals; tmp_locals.append(m_params); for (auto const & p : m_S_params) tmp_locals.push_back(mk_local(m_ngen.next(), mk_as_type(p))); for (auto const & p : m_replacements) tmp_locals.push_back(mk_local(m_ngen.next(), mk_as_type(p.second))); expr_struct_set dep_set; for (expr const & v : include_vars) { ::lean::collect_locals(mlocal_type(v), dep_set); dep_set.insert(v); } for (expr const & p : m_params) ::lean::collect_locals(mlocal_type(p), dep_set); buffer<expr> ctx; sort_locals(dep_set, m_p, ctx); expr dummy = mk_Prop(); expr tmp = Pi_as_is(ctx, Pi(tmp_locals, dummy, m_p), m_p); level_param_names new_ls; expr new_tmp; std::tie(new_tmp, new_ls) = m_p.elaborate_type(tmp, list<expr>()); m_ls = new_ls; new_tmp = update_locals(new_tmp, ctx); new_tmp = update_locals(new_tmp, m_params); for (auto & p : m_S_params) { p = get_as_type_expr(binding_domain(new_tmp)); new_tmp = binding_body(new_tmp); } for (auto & p : m_replacements) { p.second = get_as_type_expr(binding_domain(new_tmp)); new_tmp = binding_body(new_tmp); } buffer<expr> explicit_params; explicit_params.append(m_params); m_params.clear(); m_params.append(ctx); m_params.append(explicit_params); } environment operator()() { m_pos = m_p.pos(); m_migrate_tc = std::unique_ptr<type_checker>(new type_checker(m_env, m_ngen.mk_child(), std::unique_ptr<converter>(new migrate_converter(m_env, get_namespaces(m_env))))); m_tc = std::unique_ptr<type_checker>(new type_checker(m_env, m_ngen.mk_child(), std::unique_ptr<converter>(new unfold_semireducible_converter(m_env, true, true)))); parse_params(); parse_from_namespace(); parse_S_params(); parse_modifiers(); elaborate(); m_ctx = reverse_to_list(m_params.begin(), m_params.end()); for (expr & p : m_S_params) p = mk_as_is(p); environment env = m_env; env.for_each_declaration([&](declaration const & d) { if (!d.is_definition() && !d.is_theorem() && !d.is_axiom()) return; if (std::find(m_hiding.begin(), m_hiding.end(), d.get_name()) != m_hiding.end()) return; if (is_prefix_of(m_from, d.get_name())) migrate_decl(d); }); return m_env; } }; static environment migrate_cmd(parser & p) { return migrate_cmd_fn(p)(); } void register_migrate_cmd(cmd_table & r) { add_cmd(r, cmd_info("migrate", "instantiate structure theorems", migrate_cmd)); } void initialize_migrate_cmd() { g_migrate_trace = new name{"migrate", "trace"}; register_bool_option(*g_migrate_trace, LEAN_DEFAULT_MIGRATE_TRACE, "(migrate) enable/disable trace messages describing which declarations have been migrated"); } void finalize_migrate_cmd() { delete g_migrate_trace; } }
[ "leonardo@microsoft.com" ]
leonardo@microsoft.com
3cbc0433488889b59a8299d3b58a9301ae58569e
cac3c97dbb2780384786a4bc432ac19fd0e1e242
/math_library/math_library/src/vector_3.cc
3bb0a5d6d10c309296590c03892bcb68e44be3e9
[]
no_license
sergiovall/2PG_TA_garciasa
1f43dc9c3f8cdb09116ea797d9f2df4811ccac3c
e7b0a602276d85549d22b85db22e0e2b0c0ad639
refs/heads/master
2023-04-24T18:54:38.216633
2021-05-15T07:04:33
2021-05-15T07:04:33
331,273,713
0
0
null
null
null
null
UTF-8
C++
false
false
484
cc
#include "vector_3.h" const Vector3 Vector3::up = Vector3(0.0f, 1.0f, 0.0f); const Vector3 Vector3::down = Vector3(0.0f, -1.0f, 0.0f); const Vector3 Vector3::right = Vector3(1.0f, 0.0f, 0.0f); const Vector3 Vector3::left = Vector3(-1.0f, 0.0f, 0.0f); const Vector3 Vector3::forward = Vector3(0.0f, 0.0f, 1.0f); const Vector3 Vector3::back = Vector3(0.0f, 0.0f, -1.0f); const Vector3 Vector3::zero = Vector3(0.0f, 0.0f, 0.0f); const Vector3 Vector3::unit = Vector3(1.0f, 1.0f, 1.0f);
[ "garciasa@esat-alumni.com" ]
garciasa@esat-alumni.com
77a6ccbebd1ff71f28281f63ca60669cf632465b
85e502ffad5b0119fed53a9e43a34266a9f76866
/Source/Queue.cpp
5008d8d70e99be9fbe2cd3378d022f515e9fb041
[ "MIT" ]
permissive
escalonely/PipeDreamer
764a754ccaa7ba0ce812e9e5703e362de1c82e05
f608b0702f6787a1c3512dd76ddc49479a2f6526
refs/heads/main
2023-05-07T12:01:43.669178
2021-05-31T16:13:12
2021-05-31T16:13:12
352,394,204
0
1
MIT
2021-05-03T14:28:54
2021-03-28T17:32:01
C++
UTF-8
C++
false
false
3,113
cpp
/* =============================================================================== Copyright (C) 2021 Bernardo Escalona. All Rights Reserved. This file is part of Pipe Dreamer, found at: https://github.com/escalonely/PipeDreamer Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================================================== */ #include "Queue.h" #include "Randomizer.h" // ---- Class Implementation ---- Queue::Queue(int size) { m_buff.reserve(size); Randomizer* rand = Randomizer::GetInstance(); // Fill initial queue with random tiles, of any type between VERTICAL and CROSS. for (int i = 0; i < size; ++i) { TilePiece::Type t(static_cast<TilePiece::Type>(rand->GetWithinRange(TilePiece::TYPE_VERTICAL, TilePiece::TYPE_CROSS))); m_buff.push_back(dynamic_cast<Pipe*>(TilePiece::CreateTile(t))); } // This will move with every Pop. m_readPos = 0; } Queue::~Queue() { for (int i = 0; i < m_buff.size(); ++i) delete m_buff[i]; } void Queue::Reset() { Randomizer* rand = Randomizer::GetInstance(); for (int i = 0; i < m_buff.size(); ++i) { delete m_buff[i]; TilePiece::Type t(static_cast<TilePiece::Type>(rand->GetWithinRange(TilePiece::TYPE_VERTICAL, TilePiece::TYPE_CROSS))); m_buff[i] = dynamic_cast<Pipe*>(TilePiece::CreateTile(t)); } m_readPos = 0; } int Queue::GetSize() const { return static_cast<int>(m_buff.size()); } Pipe* Queue::GetTile(int pos) const { int idx = (m_readPos + pos) % m_buff.size(); return m_buff[idx]; } TilePiece::Type Queue::GetTileType(int pos) const { int idx = (m_readPos + pos) % m_buff.size(); return m_buff[idx]->GetType(); } TilePiece::Type Queue::Pop() { TilePiece::Type currentType(m_buff[m_readPos]->GetType()); // Randomize type of m_buff[m_readPos] Randomizer* rand = Randomizer::GetInstance(); TilePiece::Type t(static_cast<TilePiece::Type>(rand->GetWithinRange(TilePiece::TYPE_VERTICAL, TilePiece::TYPE_CROSS))); delete m_buff[m_readPos]; m_buff[m_readPos] = dynamic_cast<Pipe*>(TilePiece::CreateTile(t)); // Move read position m_readPos = (m_readPos + 1) % m_buff.size(); return currentType; }
[ "bernardo.escalona@dbaudio.com" ]
bernardo.escalona@dbaudio.com
7ed3e547a394ef033914cbe22163477dafb48389
b814e969ab2c8d3606b67cc644ba943cad6dc5c7
/SHS/test/main.cpp
4d7145e5caf4a0a24eb8358a8f27c52a665e86fd
[ "MIT" ]
permissive
AAAAaron/SHS
e0f3d79fd376715fec50fcbac0ea8974ca0227e8
e330a70fa30ad294fdb1b0cc32de439812b51103
refs/heads/master
2020-04-10T21:43:58.722359
2019-08-01T02:15:54
2019-08-01T02:15:54
161,304,981
1
0
null
null
null
null
UTF-8
C++
false
false
14,052
cpp
// SHS_pro.cpp : 定义控制台应用程序的入口点。 // #include <fstream> #include <time.h> #include "common_include.h" #include "pdrsim.h" #include "displayattitude.h" #include "config.h" void OnPdrStepCallbackEvent(double x, double y, double sl, double yaw ,double deta_angle) { cout<<x<<","<<y<<","<<","<<sl<<","<<yaw<<","<<deta_angle<<endl; } void OnFloorChangebackEvent(int x, int y, double sl, double yaw ,int deta_angle) { cout<<x<<","<<y<<","<<","<<sl<<","<<yaw<<","<<deta_angle<<endl; } int main(int argc, char** argv) { cout<<"-------"<<endl; // SHS::DisplayAttitude dst; string lineStr2; // ifstream poiFile("../media/4FloorName.csv"); // while (getline(poiFile, lineStr2)) { // stringstream ss(lineStr2); // string str; // vector<string> lineArray; // // 按照逗号分隔 // POIPoint pp; // while (getline(ss, str, ',')) // { // lineArray.push_back(str); // } // pp.x=atof(lineArray[3].c_str()); // pp.y=atof(lineArray[4].c_str()); // pp.name=lineArray[2]; // dst.poiVector.push_back(pp); // } // poiFile.close(); // cout<<"poi"<<dst.poiVector.size()<<endl; Eigen::Quaterniond test=angle2quat(M_PI/2,0,0);//如果用这个函数的话,实际输入要求是yaw,roll, Eigen::Quaterniond worldq=angle2quat(0,0,0); SHS::Config::setParameterFile ("../config/default.yaml"); time_t start,stop; start = time(NULL); SHS::PDRSIM _ptest; _ptest.stest->set_para(1.3,0.9); int mode=SHS::Config::get<int> ( "choose_method" ); double setyaw=SHS::Config::get<double> ( "init_yaw" ); double BJoffset=SHS::Config::get<double> ( "magoffset" ); BJoffset=BJoffset*M_PI/180.0; _ptest.pdrEkf=bool( SHS::Config::get<int> ( "pdrEkf" )); double initx=SHS::Config::get<double> ( "init_x" ); double inity=SHS::Config::get<double> ( "init_y" ); char css[20]; // istringstream( SHS::Config::get<string> ( "pdrEkf" ))>>_ptest.pdrEkf; cout<<"使用ekf?:"<<_ptest.pdrEkf<<endl; switch(mode) { //积分角度,积分转角 case 1:{ _ptest.choose_ahrs(1); _ptest.YAWORINTE=OutYaw(1); _ptest.InitialXYYaw(initx,inity,setyaw); break; } //积分角度,欧拉角 case 2:{ _ptest.choose_ahrs(1); _ptest.YAWORINTE=OutYaw(0); _ptest.InitialXYYaw(initx,inity,setyaw); break; } //积分角度,夹角 case 3:{ _ptest.choose_ahrs(1); _ptest.YAWORINTE=OutYaw(2); _ptest.InitialXYYaw(initx,inity,setyaw); break; } //鲁邦角度,欧拉角 case 4:{ _ptest.choose_ahrs(2); _ptest.YAWORINTE=OutYaw(0); _ptest.InitialXY(initx,inity); _ptest.set_magoffset(BJoffset);//北京磁偏北偏东7°,南特大约为北偏西0.39 break; } //鲁邦角度,积分角度 case 5:{ _ptest.choose_ahrs(2); _ptest.YAWORINTE=OutYaw(1); // _ptest.InitialXY(initx,inity); _ptest.InitialXYYaw(initx,inity,setyaw); _ptest.set_magoffset(BJoffset);//北京磁偏北偏东7°,南特大约为北偏西0.39 break; } case 6:{ _ptest.choose_ahrs(2); _ptest.YAWORINTE=OutYaw(2); _ptest.InitialXY(initx,inity); _ptest.set_magoffset(BJoffset);//北京磁偏北偏东7°,南特大约为北偏西0.39 break; } //ahrsqsmf yaw case 7:{ _ptest.choose_ahrs(3); _ptest.YAWORINTE=OutYaw(0); _ptest.InitialXY(initx,inity); _ptest.set_magoffset(BJoffset);//北京磁偏北偏东7°,南特大约为北偏西0.39 break; } //ahrsqsmf inte case 8:{ _ptest.choose_ahrs(3); _ptest.YAWORINTE=OutYaw(1); _ptest.InitialXYYaw(initx,inity,setyaw); _ptest.set_magoffset(BJoffset);//北京磁偏北偏东7°,南特大约为北偏西0.39 break; } //ahrsqsmf realyaw case 9:{ _ptest.choose_ahrs(3); _ptest.YAWORINTE=OutYaw(2); _ptest.InitialXY(initx,inity); _ptest.set_magoffset(BJoffset);//北京磁偏北偏东7°,南特大约为北偏西0.39 break; } //ahrsqsmfb yaw case 10:{ _ptest.choose_ahrs(4); _ptest.YAWORINTE=OutYaw(0); _ptest.InitialXY(initx,inity); _ptest.set_magoffset(BJoffset);//北京磁偏北偏东7°,南特大约为北偏西0.39 break; } //ahrsqsmfb inte case 11:{ _ptest.choose_ahrs(4); _ptest.YAWORINTE=OutYaw(1); _ptest.InitialXYYaw(initx,inity,setyaw); _ptest.set_magoffset(BJoffset);//北京磁偏北偏东7°,南特大约为北偏西0.39 break; } //ahrsqsmfb real case 12:{ _ptest.choose_ahrs(4); _ptest.YAWORINTE=OutYaw(2); _ptest.InitialXY(initx,inity); // _ptest.pdrEkf=false; _ptest.set_magoffset(BJoffset);//北京磁偏北偏东7°,南特大约为北偏西0.39 break; } //旋转积分 case 13:{ _ptest.choose_ahrs(5); _ptest.YAWORINTE=OutYaw(0); _ptest.InitialXYYaw(initx,inity,setyaw);//北京磁偏北偏东7°,南特大约为北偏西0.39 } } if(bool( SHS::Config::get<int> ( "setIos" ))) { _ptest.set_IOS(); cout<<"ios"<<endl; } _ptest.setCallBack(OnPdrStepCallbackEvent); // cout<<_ptest.cur_index<<endl; //ifstream inFile("./acc.csv");//index,ax,ay,az,gx,gy,gz,mx,my,mz,grox,groy,groz,pressure,time // ifstream inFile("../data/logfile_2018_11_28_16_21_23.csv");//这个目录指的是运行目录,锁定在当前运行目录下 // ifstream inFile(SHS::Config::get<string> ( "file_name" )); ifstream inFile(argv[1]); // cout<<argv[1]<<endl; // vector<string> gf; // gf=getFiles("../data/"); // ifstream inFile("./test.csv"); ofstream outFile; outFile.open("../data/data.csv"); string lineStr; // _ptest.InitialXY(10,10); // _ptest.InitialXYYaw(10,10,3.14); // _ptest.set_magoffset(-8/180.0*3.14159268); int count=0; while (getline(inFile, lineStr)) { stringstream ss(lineStr); string str; vector<double> lineArray; // 按照逗号分隔 while (getline(ss, str, ',')) { lineArray.push_back(atof(str.c_str())); } // cout<<lineArray[17]<<endl; count++; // _ptest.adddata( lineArray[10],lineArray[11],lineArray[12], lineArray[1]+lineArray[4],lineArray[2]+lineArray[5],lineArray[3]+lineArray[6],lineArray[7],lineArray[8],lineArray[9],lineArray[14]); // _ptest.adddata( lineArray[10],lineArray[11],lineArray[12], lineArray[1],lineArray[2],lineArray[3],lineArray[4],lineArray[5],lineArray[6],lineArray[7],lineArray[8],lineArray[9],lineArray[14]); //吕总 // _ptest.adddata( lineArray[7],lineArray[8],lineArray[9], lineArray[1],lineArray[2],lineArray[3],lineArray[4],lineArray[5],lineArray[6],lineArray[10],lineArray[11],lineArray[12],lineArray[27]); //采集DAT // _ptest.adddata(lineArray[0],lineArray[1],lineArray[2],lineArray[3],lineArray[4],lineArray[5],lineArray[6],lineArray[7],lineArray[8],lineArray[9],lineArray[10],lineArray[11],lineArray[12]); if(bool( SHS::Config::get<int> ( "setIos" ))) { // _ptest.adddata( lineArray[7],lineArray[8],lineArray[9], lineArray[1],lineArray[2],lineArray[3],lineArray[4],lineArray[5],lineArray[6],lineArray[10],lineArray[11],lineArray[12],lineArray[25]); //旧版王超采集DAT // _ptest.adddata( lineArray[7],lineArray[8],lineArray[9], lineArray[1],lineArray[2],lineArray[3],lineArray[4],lineArray[5],lineArray[6],lineArray[10],lineArray[11],lineArray[12],lineArray[27]); //采集DAT _ptest.adddata( lineArray[10],lineArray[11],lineArray[12], lineArray[1],lineArray[2],lineArray[3],lineArray[4],lineArray[5],lineArray[6],lineArray[13],lineArray[14],lineArray[15],lineArray[17]); //采集DAT } else{ if(!bool( SHS::Config::get<int> ( "DAT" ))) { if(lineArray[0]>-1) { _ptest.adddata( lineArray[10],lineArray[11],lineArray[12], lineArray[1],lineArray[2],lineArray[3],lineArray[4],lineArray[5],lineArray[6],lineArray[7],lineArray[8],lineArray[9],lineArray[13]); //getsensor数据 // _ptest.adddata( lineArray[10],lineArray[11],lineArray[12], lineArray[1],lineArray[2],lineArray[3],lineArray[4],lineArray[5],lineArray[6],lineArray[10],lineArray[11],lineArray[12],lineArray[27]); //sensor } } else{ _ptest.adddata( lineArray[7],lineArray[8],lineArray[9], lineArray[1],lineArray[2],lineArray[3],lineArray[4],lineArray[5],lineArray[6],lineArray[10],lineArray[11],lineArray[12],lineArray[27]); //DAT安卓的数据 } } // // test=angle2quat(_ptest.atest->Att(2),_ptest.atest->Att(0),_ptest.atest->Att(1)); // test=test.inverse(); // test=Eigen::Quaterniond(_ptest.atest->quaternion.w(),-_ptest.atest->quaternion.y(),-_ptest.atest->quaternion.x(),_ptest.atest->quaternion.z()); // //以这种方式是可以对上的,使得安卓正常对上了,苹果也可以正常使用 // //主要是cv用的方式和eigen的有点差别, // Eigen::Vector3d cphone(15.53,17.9,1); // // if(lineArray[28]>-1e-5&&lineArray.size()>29) // { // Eigen::Quaterniond qpw(test); // dst.ProcessImgAr(SHS::Config::get<string> ( "file_dir" )+to_string(int(lineArray[28]))+".jpg",cphone,qpw,_ptest.atest->GetRealFace()); // } // // cout<<"------"<<endl; // // cout<<_ptest.atest->Att*180.0/M_PI<<endl; // dst.SetStringContent("GetRealYaw:"+to_string(_ptest.atest->GetRealYaw()*180.0/M_PI)+"\n"+"GetRealFace:"+to_string(_ptest.atest->GetRealFace()*180.0/M_PI)+"\n"+"yaw:"+to_string(_ptest.atest->Att(2)*180.0/M_PI)+"\n"+"pitch:"+to_string(_ptest.atest->Att(1)*180.0/M_PI)+"\n"+"roll:"+to_string(_ptest.atest->Att(0)*180.0/M_PI)); // // getchar(); // cv::Affine3d PhoneAtt( // cv::Affine3d::Mat3( test.toRotationMatrix()(0,0),test.toRotationMatrix()(1,0),test.toRotationMatrix()(2,0), // test.toRotationMatrix()(0,1),test.toRotationMatrix()(1,1),test.toRotationMatrix()(2,1), // test.toRotationMatrix()(0,2),test.toRotationMatrix()(1,2),test.toRotationMatrix()(2,2) // ), // cv::Affine3d::Vec3( // 0,0,0 // ) // ); // // cv::Affine3d World( // cv::Affine3d::Mat3( worldq.toRotationMatrix()(0,0),worldq.toRotationMatrix()(1,0),worldq.toRotationMatrix()(2,0), // worldq.toRotationMatrix()(0,1),worldq.toRotationMatrix()(1,1),worldq.toRotationMatrix()(2,1), // worldq.toRotationMatrix()(0,2),worldq.toRotationMatrix()(1,2),worldq.toRotationMatrix()(2,2) // ), // cv::Affine3d::Vec3( // 0,0,0 // ) // ); // dst.SetCurrentFrame(PhoneAtt,World); // _ptest.atest->Att(2)*180.0/M_PI // dst.SetStringContent("ss"); if (_ptest.ISSTEP) { // cout<<lineArray[13]<<endl; // _ptest.setXY(20,20); // cout<<count<<"step"<<_ptest.get_X()<<","<<_ptest.get_Y()<<","<<_ptest.get_SL()<<","<<_ptest.get_YAW()<<endl; if(_ptest.get_SL()>0){ sprintf(css, "%f", _ptest.get_time()); outFile<<_ptest.get_X()<<","<<_ptest.get_Y()<<","<<_ptest.get_SL()<<","<<_ptest.get_YAW()<<","<<_ptest.get_deta_angle()<<","<<_ptest.get_mx()<<","<<_ptest.get_my()<<","<<_ptest.get_mz()<<","<<_ptest.cur_index<<","<<css<<endl; } // cout<<_ptest.get_X()<<","<<_ptest.get_Y()<<","<<_ptest.get_SL()<<","<<_ptest.get_YAW()<<","<<_ptest.get_deta_angle()<<","<<_ptest.cur_index<<","<<_ptest.cur_time<<endl; } } stop = time(NULL); cout<<stop-start<<"s time"<<endl; // for (unsigned int i = 0; i < pdresult.size(); i++) // { // outFile<<pdresult[i].x<<","<<pdresult[i].y<<","<<pdresult[i].sl<<","<<pdresult[i].yaw<<endl; // cout<<i<<endl; // } cout<<"-------------"<<mode<<endl; inFile.close(); outFile.close(); // getchar(); cout<<"-------------"<<mode<<endl; return 0; } //测转移是否正确 int main22(int argc, char** argv) { double theta=M_PI/4; double coutheta=0; for(int i=0;i<9;i++) { coutheta=acos(cos(theta*i)); if(sin(theta*i)<0) { coutheta*=-1.0; } cout<<"curtheta="<<theta*i<<"out "<<coutheta<<endl; } } //测气压 // int main22(int argc, char** argv) // { // string lineStr2; // Eigen::Quaterniond test=angle2quat(M_PI/2,0,0);//如果用这个函数的话,实际输入要求是yaw,roll, // Eigen::Quaterniond worldq=angle2quat(0,0,0); // SHS::Config::setParameterFile ("../config/default.yaml"); // // time_t start,stop; // start = time(NULL); // // SHS::PDRSIM _ptest; // _ptest.set_IOS(); // _ptest.setFloorCallBack(OnFloorChangebackEvent); // _ptest.InitFloorModule(4); // _ptest.stest->set_para(1.3,0.9); // int mode=SHS::Config::get<int> ( "choose_method" ); // double setyaw=SHS::Config::get<double> ( "init_yaw" ); // double BJoffset=-7.0*M_PI/180.0; // _ptest.pdrEkf=bool( SHS::Config::get<int> ( "pdrEkf" )); // double initx=SHS::Config::get<double> ( "init_x" ); // double inity=SHS::Config::get<double> ( "init_y" ); // // if(bool( SHS::Config::get<int> ( "setIos" ))) // { // _ptest.set_IOS(); // cout<<"ios"<<endl; // } // double FFfloorHeights[] ={5.0f, 7.8f, 4.3f, 4.3f, 4.3f, 4.3f, 4.3f, 4.3f, 4.3f, 4.3f, 4.3f, 4.3f}; // for(int i=0;i<12;i++) // { // _ptest.floorModuleAddFloorHeight(FFfloorHeights[i]); // } // _ptest.floorModuleUpdateFloorHeightMatrix(); // // // // ifstream inFile(SHS::Config::get<string> ( "file_name" )); // // ofstream outFile; // outFile.open("../data/data.csv"); // string lineStr; // int count=0; // // while (getline(inFile, lineStr)) { // stringstream ss(lineStr); // string str; // vector<double> lineArray; // // 按照逗号分隔 // // while (getline(ss, str, ',')) // { // lineArray.push_back(atof(str.c_str())); // } // count++; // int Fchange=_ptest.floorModuleAddData(lineArray[0],lineArray[1],lineArray[2],lineArray[3]); // if (Fchange!=0) // { // // outFile<<_ptest.get_X()<<","<<_ptest.get_Y()<<","<<_ptest.get_SL()<<","<<_ptest.get_YAW()<<","<<_ptest.get_deta_angle()<<","<<_ptest.cur_index<<","<<_ptest.cur_time<<endl; } // cout<<_ptest.floortest->currentFloorIndex<<endl; // // } // } // stop = time(NULL); // cout<<stop-start<<"s time"<<endl; // cout<<"-------------"<<mode<<endl; // inFile.close(); // outFile.close(); // // getchar(); // cout<<"-------------"<<mode<<endl; // return 0; // }
[ "15201622482@163.com" ]
15201622482@163.com
f4c642cf0f4d383aeaa9febfc24d83e3a571532b
1c70c3c299b635495ba69941511a474239b118c4
/src/midi/MIDIFile.h
5b687765d6fecf6e40b2594b99b7738ab4519573
[]
no_license
XJALYN/MIDIVisualizer
90304f39a6eea628f32cd440d11540e4777e2134
5acf8f4328432b341ed584e522d4089057942ee4
refs/heads/master
2021-01-19T14:39:54.183739
2017-03-16T13:21:01
2017-03-16T13:21:01
88,177,781
1
2
null
2017-04-13T15:09:43
2017-04-13T15:09:43
null
UTF-8
C++
false
false
613
h
#ifndef MIDI_FILE_H #define MIDI_FILE_H #include "MIDIUtils.h" #include "MIDITrack.h" class MIDIFile { private: uint16_t _tracksCount; MIDIType format; uint16_t unitsPerFrame; float framesPerSeconds; uint16_t unitsPerQuarterNote; public: MIDIFile(); MIDIFile(const std::string & filePath); ~MIDIFile(); void printTracks(); void mergeTracks(); void getNotesActive(std::vector<int>& actives, double time, size_t track); void getNotesActiveFull(std::vector<std::pair<double,double>>& actives, double time, size_t track); std::vector<MIDITrack> tracks; }; #endif // MIDI_FILE_H
[ "kosua20@gmail.com" ]
kosua20@gmail.com
ee909785533ca2824b70b6b8a7b5df5c7874cc23
46811a68282194436142b010f1ff862ef89d9567
/BacktrackingDemo/BacktrackingDemo/src/Letter Combinations of a Phone Number.cpp
f6b78c4f16ca0d3cba5d09e018f09e7b35fc3f72
[]
no_license
zhenyiyi/algorithm
24094c10fa34960d73a8899b4c8268246e2e3420
8d21dbc3736ce0d2d193e4cf6174b055a4dfc77c
refs/heads/master
2020-06-28T04:10:17.477625
2019-08-14T03:20:30
2019-08-14T03:20:30
200,139,186
1
0
null
null
null
null
UTF-8
C++
false
false
222
cpp
// // Letter Combinations of a Phone Number.cpp // BacktrackingDemo // // Created by 张枫林 on 2019/8/8. // Copyright © 2019 张枫林. All rights reserved. // #include "Letter Combinations of a Phone Number.hpp"
[ "17712676370@163.com" ]
17712676370@163.com
c6ad132b4047ff9f9dfbdc95c69b97ec266116ae
f81124e4a52878ceeb3e4b85afca44431ce68af2
/re20_1/processor61/constant/polyMesh/points
d2032f77917848fa7a18574a496fc84e2fef6c4e
[]
no_license
chaseguy15/coe-of2
7f47a72987638e60fd7491ee1310ee6a153a5c10
dc09e8d5f172489eaa32610e08e1ee7fc665068c
refs/heads/master
2023-03-29T16:59:14.421456
2021-04-06T23:26:52
2021-04-06T23:26:52
355,040,336
0
1
null
null
null
null
UTF-8
C++
false
false
5,458
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class vectorField; location "constant/polyMesh"; object points; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // 152 ( (7.1875 0 -0.05) (7.458333333 0 -0.05) (7.186597136 0.1343879199 -0.05) (7.457731424 0.1337861204 -0.05) (7.18389724 0.2685988476 -0.05) (7.455931494 0.2674542459 -0.05) (7.179426313 0.4024574953 -0.05) (7.452950875 0.4008875181 -0.05) (7.173227413 0.535791968 -0.05) (7.448818275 0.5339713403 -0.05) (7.165360237 0.6684354187 -0.05) (7.443573491 0.6665944812 -0.05) (7.155900552 0.8002276552 -0.05) (7.437267035 0.798650146 -0.05) (7.14493946 0.9310166833 -0.05) (7.42995964 0.9300370051 -0.05) (7.132582521 1.06066017 -0.05) (7.421721681 1.06066017 -0.05) (7.1875 0 0.05) (7.458333333 0 0.05) (7.186597136 0.1343879199 0.05) (7.457731424 0.1337861204 0.05) (7.18389724 0.2685988476 0.05) (7.455931494 0.2674542459 0.05) (7.179426313 0.4024574953 0.05) (7.452950875 0.4008875181 0.05) (7.173227413 0.535791968 0.05) (7.448818275 0.5339713403 0.05) (7.165360237 0.6684354187 0.05) (7.443573491 0.6665944812 0.05) (7.155900552 0.8002276552 0.05) (7.437267035 0.798650146 0.05) (7.14493946 0.9310166833 0.05) (7.42995964 0.9300370051 0.05) (7.132582521 1.06066017 0.05) (7.421721681 1.06066017 0.05) (7.421721681 2.040440113 -0.05) (7.71086084 2.040440113 -0.05) (7.421721681 2.285385099 -0.05) (7.71086084 2.285385099 -0.05) (7.421721681 2.530330085 -0.05) (7.71086084 2.530330085 -0.05) (7.421721681 2.775275071 -0.05) (7.71086084 2.775275071 -0.05) (7.421721681 3.020220057 -0.05) (7.71086084 3.020220057 -0.05) (7.421721681 3.265165043 -0.05) (7.71086084 3.265165043 -0.05) (7.421721681 3.510110028 -0.05) (7.71086084 3.510110028 -0.05) (7.421721681 3.755055014 -0.05) (7.71086084 3.755055014 -0.05) (7.421721681 4 -0.05) (7.71086084 4 -0.05) (7.421721681 2.040440113 0.05) (7.71086084 2.040440113 0.05) (7.421721681 2.285385099 0.05) (7.71086084 2.285385099 0.05) (7.421721681 2.530330085 0.05) (7.71086084 2.530330085 0.05) (7.421721681 2.775275071 0.05) (7.71086084 2.775275071 0.05) (7.421721681 3.020220057 0.05) (7.71086084 3.020220057 0.05) (7.421721681 3.265165043 0.05) (7.71086084 3.265165043 0.05) (7.421721681 3.510110028 0.05) (7.71086084 3.510110028 0.05) (7.421721681 3.755055014 0.05) (7.71086084 3.755055014 0.05) (7.421721681 4 0.05) (7.71086084 4 0.05) (7.132582521 -1.06066017 -0.05) (7.132582521 -1.305605156 -0.05) (7.132582521 -1.550550142 -0.05) (7.132582521 -1.795495127 -0.05) (7.132582521 -2.040440113 -0.05) (7.132582521 -2.285385099 -0.05) (7.132582521 -2.530330085 -0.05) (7.132582521 -2.775275071 -0.05) (7.132582521 -3.020220057 -0.05) (7.132582521 -3.265165042 -0.05) (7.132582521 -3.510110028 -0.05) (7.132582521 -3.755055014 -0.05) (7.132582521 -4 -0.05) (7.421721681 -1.06066017 -0.05) (7.421721681 -1.305605156 -0.05) (7.421721681 -1.550550142 -0.05) (7.421721681 -1.795495127 -0.05) (7.421721681 -2.040440113 -0.05) (7.421721681 -2.285385099 -0.05) (7.421721681 -2.530330085 -0.05) (7.421721681 -2.775275071 -0.05) (7.421721681 -3.020220057 -0.05) (7.421721681 -3.265165042 -0.05) (7.421721681 -3.510110028 -0.05) (7.421721681 -3.755055014 -0.05) (7.421721681 -4 -0.05) (7.132582521 -1.06066017 0.05) (7.132582521 -1.305605156 0.05) (7.132582521 -1.550550142 0.05) (7.132582521 -1.795495127 0.05) (7.132582521 -2.040440113 0.05) (7.132582521 -2.285385099 0.05) (7.132582521 -2.530330085 0.05) (7.132582521 -2.775275071 0.05) (7.132582521 -3.020220057 0.05) (7.132582521 -3.265165042 0.05) (7.132582521 -3.510110028 0.05) (7.132582521 -3.755055014 0.05) (7.132582521 -4 0.05) (7.421721681 -1.06066017 0.05) (7.421721681 -1.305605156 0.05) (7.421721681 -1.550550142 0.05) (7.421721681 -1.795495127 0.05) (7.421721681 -2.040440113 0.05) (7.421721681 -2.285385099 0.05) (7.421721681 -2.530330085 0.05) (7.421721681 -2.775275071 0.05) (7.421721681 -3.020220057 0.05) (7.421721681 -3.265165042 0.05) (7.421721681 -3.510110028 0.05) (7.421721681 -3.755055014 0.05) (7.421721681 -4 0.05) (7.14493946 -0.9310166833 -0.05) (7.42995964 -0.9300370051 -0.05) (7.155900552 -0.8002276552 -0.05) (7.437267035 -0.798650146 -0.05) (7.165360237 -0.6684354187 -0.05) (7.443573491 -0.6665944812 -0.05) (7.173227413 -0.535791968 -0.05) (7.448818275 -0.5339713403 -0.05) (7.179426313 -0.4024574953 -0.05) (7.452950875 -0.4008875181 -0.05) (7.18389724 -0.2685988476 -0.05) (7.455931494 -0.2674542459 -0.05) (7.186597136 -0.1343879199 -0.05) (7.457731424 -0.1337861204 -0.05) (7.14493946 -0.9310166833 0.05) (7.42995964 -0.9300370051 0.05) (7.155900552 -0.8002276552 0.05) (7.437267035 -0.798650146 0.05) (7.165360237 -0.6684354187 0.05) (7.443573491 -0.6665944812 0.05) (7.173227413 -0.535791968 0.05) (7.448818275 -0.5339713403 0.05) (7.179426313 -0.4024574953 0.05) (7.452950875 -0.4008875181 0.05) (7.18389724 -0.2685988476 0.05) (7.455931494 -0.2674542459 0.05) (7.186597136 -0.1343879199 0.05) (7.457731424 -0.1337861204 0.05) ) // ************************************************************************* //
[ "chaseguy15" ]
chaseguy15
02f6684fd8ae00a2d34d4441964425dd3e4538dd
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/scrape/data/Organized/QAQmika/QAQmika_A.cpp
9f995c1ce798fa205cd82e0013f6021b5bae1fdc
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
708
cpp
#include<iostream> #include<stdio.h> #include<math.h> #include<string> #include<string.h> #include<algorithm> #include<vector> using namespace std; #define ull unsigned long long const int maxn = 1e5+10; int ans; ull index,pre; ull m,k; int n; ull a[maxn]; int main() { scanf("%llu%d%llu",&m,&n,&k); for(int i=1;i<=n;i++) scanf("%llu",&a[i]); index=k; int temp=0;ull t1; while(true) { if(pre>=n) break; for(int i=pre;i<=n;i++) { if(i==n||(a[i]<=index&&a[i+1]>index)) { temp=i; break; } } if(temp==pre) { t1=a[temp+1]-index; if(t1<=k) index+=k; else index+=t1/k*k; } else { index+=temp-pre; pre=temp; ans++; } } printf("%d",ans); return 0; }
[ "mukeshchugani10@gmail.com" ]
mukeshchugani10@gmail.com
a358e2ff05845dfee81400588c97455d4c2977d2
575731c1155e321e7b22d8373ad5876b292b0b2f
/examples/native/ios/Pods/boost-for-react-native/boost/spirit/include/karma_and_predicate.hpp
bbec10506e6d08ef6c1d5e0605c6800b33d359cb
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
Nozbe/zacs
802a84ffd47413a1687a573edda519156ca317c7
c3d455426bc7dfb83e09fdf20781c2632a205c04
refs/heads/master
2023-06-12T20:53:31.482746
2023-06-07T07:06:49
2023-06-07T07:06:49
201,777,469
432
10
MIT
2023-01-24T13:29:34
2019-08-11T14:47:50
JavaScript
UTF-8
C++
false
false
667
hpp
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Copyright (c) 2001-2011 Hartmut Kaiser http://spirit.sourceforge.net/ Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef BOOST_SPIRIT_INCLUDE_KARMA_AND_PREDICATE #define BOOST_SPIRIT_INCLUDE_KARMA_AND_PREDICATE #if defined(_MSC_VER) #pragma once #endif #include <boost/spirit/home/karma/operator/and_predicate.hpp> #endif
[ "radexpl@gmail.com" ]
radexpl@gmail.com
507bf567538988696ab6a2ab48906efcb3bdcaae
ac6b4921f52018439df20a4f7300b45db08d36a1
/Source/Penguin_Meltdown/Private/Player/PlayerPawn_Polar.cpp
02909ba19b651119b820570ab6d39f4428608e1f
[]
no_license
lipneteng/PenguinMeltdown
ea49c2660b208de45c8f981fc9a90f83f57cac45
5205ddaa8c4cc6ab9720a686274c39b22f2763a0
refs/heads/master
2021-08-11T00:34:51.639173
2018-05-02T21:26:50
2018-05-02T21:26:50
91,559,016
7
2
null
null
null
null
UTF-8
C++
false
false
5,816
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "Penguin_Meltdown.h" #include "Kismet/KismetMathLibrary.h" #include "Bullet.h" #include "PlayerPawn_Polar.h" // Sets default values APlayerPawn_Polar::APlayerPawn_Polar() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; Gun = CreateDefaultSubobject<USkeletalMeshComponent>("Gun"); Gun->AttachToComponent(GetMesh(), FAttachmentTransformRules::KeepRelativeTransform, "GunSocket"); StepsSoundComponent = CreateDefaultSubobject<UAudioComponent>("StepsSound"); StepsSoundComponent->SetActive(false); } // Called when the game starts or when spawned void APlayerPawn_Polar::BeginPlay() { Super::BeginPlay(); } // Called every frame void APlayerPawn_Polar::Tick(float DeltaTime) { Super::Tick(DeltaTime); PlayStepsSound(); CalculateTimeUnderPower(DeltaTime); } void APlayerPawn_Polar::PlayStepsSound() { float Velocity = 0.0f; Velocity = GetCharacterMovement()->Velocity.Size(); if (Velocity == 0) { StepsSoundComponent->SetActive(false); } else { StepsSoundComponent->SetActive(true); } } // Called to bind functionality to input void APlayerPawn_Polar::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); } void APlayerPawn_Polar::TakePenguin() { APenguin* PenguinRef = nullptr; if (CurrentPenguins.Num() < PenguinLimit && CheckNearPenguin(PenguinRef)) { if (PenguinRef->SetPolarControl(true)) { CurrentPenguins.Add(PenguinRef); FName SocketName = GetPenguinSocket(); FVector SocketLocation = GetMesh()->GetSocketLocation(SocketName); PenguinRef->SetActorLocation(SocketLocation); PenguinRef->AttachToActor(this, FAttachmentTransformRules::KeepWorldTransform, SocketName); UpdateSpeed(); } } } bool APlayerPawn_Polar::CheckNearPenguin(APenguin* & PenguinRef) { FHitResult Hit; FVector TraceStartLocation = GetActorLocation(); FVector TraceEndLocation = TraceStartLocation + FVector(0, 0, 1); float TraceSphereRadius = PenguinTakeRadius; FCollisionObjectQueryParams TraceCollisionObjectParams; TraceCollisionObjectParams.AddObjectTypesToQuery(ECC_Pawn); FCollisionQueryParams TraceCollisionParams; TraceCollisionParams.AddIgnoredActor(this); #ifdef TestTracing TraceCollisionParams.TraceTag = "TraceTag"; UWorld* World = GetWorld(); World->DebugDrawTraceTag = "TraceTag"; #endif GetWorld()->SweepSingleByObjectType(Hit, TraceStartLocation, TraceEndLocation, FQuat(), TraceCollisionObjectParams, FCollisionShape::MakeSphere(TraceSphereRadius), TraceCollisionParams); if (APenguin* PenguinCastActor = Cast<APenguin>(Hit.GetActor())) { PenguinRef = PenguinCastActor; return true; } return false; } FName APlayerPawn_Polar::GetPenguinSocket() { int32 SocketNumber = CurrentPenguins.Num(); FName SocketName; switch (SocketNumber) { case 1: SocketName = "Penguin1"; break; case 2: SocketName = "Penguin2"; break; } return SocketName; } void APlayerPawn_Polar::UpdateSpeed() { float Speed = 0.0f; if (!bIsUnderPower) { int32 PenguinNum = CurrentPenguins.Num(); switch (PenguinNum) { case 0: Speed = DefaultSpeed; break; case 1: Speed = DefaultSpeed / 2; break; case 2: Speed = DefaultSpeed / 4; break; } GetCharacterMovement()->MaxWalkSpeed = Speed; } else { GetCharacterMovement()->MaxWalkSpeed = DefaultSpeed; } } void APlayerPawn_Polar::UnTakePenguin() { if (CurrentPenguins.Num() > 0) { APenguin* PenguinRef = CurrentPenguins[CurrentPenguins.Num() - 1]; if (PenguinRef->SetPolarControl(false)) { CurrentPenguins.Remove(PenguinRef); UpdateSpeed(); } } } void APlayerPawn_Polar::SetDefaultLocation() { SetActorLocation(DefaultLocation); ClearPenguins(); } void APlayerPawn_Polar::ClearPenguins() { if (CurrentPenguins.Num() > 0) { for (int32 i = 0; i < CurrentPenguins.Num(); i++) { CurrentPenguins[i]->Destroy(); } CurrentPenguins.Empty(); } UpdateSpeed(); } void APlayerPawn_Polar::ClearPenguinSpecific(APenguin* PenguinRef) { CurrentPenguins.Remove(PenguinRef); PenguinRef->Destroy(); UpdateSpeed(); } TArray <APenguin*> APlayerPawn_Polar::GetPenguinsArray() { return CurrentPenguins; } void APlayerPawn_Polar::SetUnderPower(float TimeUnderPower) { if (!bIsUnderPower) { bIsUnderPower = true; this->TimeUnderPower = TimeUnderPower; UpdateSpeed(); } } void APlayerPawn_Polar::CalculateTimeUnderPower(float DeltaSeconds) { if (bIsUnderPower) { TimeUnderPower -= DeltaSeconds; if (TimeUnderPower <= 0.0f) { TimeUnderPower = 0.0f; bIsUnderPower = false; UpdateSpeed(); } } } void APlayerPawn_Polar::IncBullets(int32 BulletsValue) { BulletsNum += BulletsValue; } void APlayerPawn_Polar::DecBullets() { BulletsNum--; } void APlayerPawn_Polar::Attack() { if (BulletClass && BulletsNum > 0) { APlayerController* PC; FVector MouseLocation; FVector MouseDirection; FRotator RotateTo; PC = UGameplayStatics::GetPlayerController(this, 0); PC->DeprojectMousePositionToWorld(MouseLocation, MouseDirection); MouseDirection *= (MouseLocation.Z / MouseDirection.Z) * -1; MouseLocation += MouseDirection; RotateTo = UKismetMathLibrary::FindLookAtRotation(GetActorLocation(), MouseLocation); RotateTo = FRotator(GetActorRotation().Pitch, RotateTo.Yaw, GetActorRotation().Roll); SetActorRotation(RotateTo); GetWorld()->SpawnActor<ABullet>(BulletClass, Gun->GetSocketLocation("Muzzle"), RotateTo); MakeAttackSound(); DecBullets(); OnFireIsStarted.Broadcast(); } } void APlayerPawn_Polar::MakeAttackSound() { UGameplayStatics::PlaySoundAtLocation(this, AttackSound, Gun->GetSocketLocation("Muzzle")); }
[ "la@familyagency.ru" ]
la@familyagency.ru
b473634e9605890445c595916ff5bd8ff43b80da
c1159fb3bc3cf42690056ad9532224be6e820e4e
/tensorflow/compiler/xla/service/hlo_instructions.cc
c160647f7a77f808f29b4bf1578015c8860cee03
[ "Apache-2.0" ]
permissive
jlaako/tensorflow
2d5cb985fad709e1afc4ebd43971c0bd2e8c2a53
13da30d465a017207d9ca2116f978f0d2a9d15b5
refs/heads/master
2020-03-22T18:06:23.170454
2018-07-10T13:13:26
2018-07-10T13:16:52
140,437,424
0
0
Apache-2.0
2018-07-10T13:36:38
2018-07-10T13:36:37
null
UTF-8
C++
false
false
72,095
cc
/* Copyright 2018 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/compiler/xla/service/hlo_instructions.h" #include <deque> #include "tensorflow/compiler/xla/literal_util.h" #include "tensorflow/compiler/xla/service/hlo_casting_utils.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_module.h" #include "tensorflow/compiler/xla/window_util.h" #include "tensorflow/core/lib/gtl/flatmap.h" namespace xla { namespace { using ::tensorflow::str_util::CEscape; using ::tensorflow::str_util::Join; using ::tensorflow::strings::StrAppend; using ::tensorflow::strings::StrCat; bool IsInstructionElementwiseOnOperand(const HloInstruction* instruction, const HloInstruction* operand) { std::vector<int64> operand_indices = instruction->OperandIndices(operand); return std::all_of( operand_indices.begin(), operand_indices.end(), [instruction](int64 operand_index) { return instruction->IsElementwiseOnOperand(operand_index); }); } } // namespace HloBatchNormInstruction::HloBatchNormInstruction( HloOpcode opcode, const Shape& shape, HloInstruction* operand, HloInstruction* scale, float epsilon, int64 feature_index) : HloInstruction(opcode, shape), epsilon_(epsilon), feature_index_(feature_index) { AppendOperand(operand); AppendOperand(scale); } bool HloBatchNormInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { const auto& casted_other = static_cast<const HloBatchNormInstruction&>(other); return feature_index() == casted_other.feature_index() && epsilon() == casted_other.epsilon(); } HloInstructionProto HloBatchNormInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); proto.set_epsilon(epsilon_); proto.set_feature_index(feature_index_); return proto; } std::vector<string> HloBatchNormInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { return {StrCat("epsilon=", epsilon()), StrCat("feature_index=", feature_index())}; } HloBatchNormTrainingInstruction::HloBatchNormTrainingInstruction( const Shape& shape, HloInstruction* operand, HloInstruction* scale, HloInstruction* offset, float epsilon, int64 feature_index) : HloBatchNormInstruction(HloOpcode::kBatchNormTraining, shape, operand, scale, epsilon, feature_index) { AppendOperand(offset); } std::unique_ptr<HloInstruction> HloBatchNormTrainingInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { CHECK_EQ(new_operands.size(), 3); return MakeUnique<HloBatchNormTrainingInstruction>( shape, new_operands[0], new_operands[1], new_operands[2], epsilon(), feature_index()); } HloBatchNormInferenceInstruction::HloBatchNormInferenceInstruction( const Shape& shape, HloInstruction* operand, HloInstruction* scale, HloInstruction* offset, HloInstruction* mean, HloInstruction* variance, float epsilon, int64 feature_index) : HloBatchNormInstruction(HloOpcode::kBatchNormInference, shape, operand, scale, epsilon, feature_index) { AppendOperand(offset); AppendOperand(mean); AppendOperand(variance); } std::unique_ptr<HloInstruction> HloBatchNormInferenceInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { CHECK_EQ(new_operands.size(), 5); return MakeUnique<HloBatchNormInferenceInstruction>( shape, new_operands[0], new_operands[1], new_operands[2], new_operands[3], new_operands[4], epsilon(), feature_index()); } HloBatchNormGradInstruction::HloBatchNormGradInstruction( const Shape& shape, HloInstruction* operand, HloInstruction* scale, HloInstruction* mean, HloInstruction* variance, HloInstruction* grad_output, float epsilon, int64 feature_index) : HloBatchNormInstruction(HloOpcode::kBatchNormGrad, shape, operand, scale, epsilon, feature_index) { AppendOperand(mean); AppendOperand(variance); AppendOperand(grad_output); } std::unique_ptr<HloInstruction> HloBatchNormGradInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { CHECK_EQ(new_operands.size(), 5); return MakeUnique<HloBatchNormGradInstruction>( shape, new_operands[0], new_operands[1], new_operands[2], new_operands[3], new_operands[4], epsilon(), feature_index()); } HloFftInstruction::HloFftInstruction( const Shape& shape, HloInstruction* operand, FftType fft_type, tensorflow::gtl::ArraySlice<int64> fft_length) : HloInstruction(HloOpcode::kFft, shape), fft_type_(fft_type) { fft_length_.assign(fft_length.begin(), fft_length.end()); AppendOperand(operand); } HloInstructionProto HloFftInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); proto.set_fft_type(fft_type_); for (int64 fft_len : fft_length_) { proto.add_fft_length(fft_len); } return proto; } std::vector<string> HloFftInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { return {StrCat("fft_type=", FftType_Name(fft_type())), StrCat("fft_length={", Join(fft_length(), ","), "}")}; } bool HloFftInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { const auto& casted_other = static_cast<const HloFftInstruction&>(other); return fft_type() == casted_other.fft_type() && fft_length() == casted_other.fft_length(); } std::unique_ptr<HloInstruction> HloFftInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { CHECK_EQ(new_operands.size(), 1); return MakeUnique<HloFftInstruction>(shape, new_operands[0], fft_type_, fft_length_); } HloSendRecvInstruction::HloSendRecvInstruction(HloOpcode opcode, const Shape& shape, int64 channel_id) : HloInstruction(opcode, shape), channel_id_(channel_id) {} HloInstructionProto HloSendRecvInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); proto.set_channel_id(channel_id_); return proto; } std::vector<string> HloSendRecvInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { return {StrCat("channel_id=", channel_id_)}; } bool HloSendRecvInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { // Not yet supported. return false; } // Send instruction produces a tuple of {aliased operand, U32 context}. HloSendInstruction::HloSendInstruction(HloInstruction* operand, HloInstruction* token, int64 channel_id) : HloSendRecvInstruction( HloOpcode::kSend, ShapeUtil::MakeTupleShape({CHECK_NOTNULL(operand)->shape(), ShapeUtil::MakeShape(U32, {}), ShapeUtil::MakeTokenShape()}), channel_id) { AppendOperand(operand); AppendOperand(token); } std::unique_ptr<HloInstruction> HloSendInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { CHECK_EQ(new_operands.size(), 2); return MakeUnique<HloSendInstruction>(new_operands[0], new_operands[1], channel_id()); } HloSendDoneInstruction::HloSendDoneInstruction(HloSendInstruction* operand) : HloSendRecvInstruction(HloOpcode::kSendDone, ShapeUtil::MakeTokenShape(), CHECK_NOTNULL(operand)->channel_id()) { AppendOperand(operand); } std::unique_ptr<HloInstruction> HloSendDoneInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { CHECK_EQ(new_operands.size(), 1); return MakeUnique<HloSendDoneInstruction>( Cast<HloSendInstruction>(new_operands[0])); } // Recv instruction produces a tuple of {receive buffer, U32 context}. HloRecvInstruction::HloRecvInstruction(const Shape& shape, HloInstruction* token, int64 channel_id) : HloSendRecvInstruction( HloOpcode::kRecv, ShapeUtil::MakeTupleShape({shape, ShapeUtil::MakeShape(U32, {}), ShapeUtil::MakeTokenShape()}), channel_id) { AppendOperand(token); } std::unique_ptr<HloInstruction> HloRecvInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { CHECK_EQ(new_operands.size(), 1); return MakeUnique<HloRecvInstruction>( ShapeUtil::GetTupleElementShape(shape, 0), new_operands[0], channel_id()); } HloRecvDoneInstruction::HloRecvDoneInstruction(HloRecvInstruction* operand) : HloSendRecvInstruction( HloOpcode::kRecvDone, ShapeUtil::MakeTupleShape( {ShapeUtil::GetTupleElementShape(operand->shape(), 0), ShapeUtil::MakeTokenShape()}), CHECK_NOTNULL(operand)->channel_id()) { AppendOperand(operand); } std::unique_ptr<HloInstruction> HloRecvDoneInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { CHECK_EQ(new_operands.size(), 1); return MakeUnique<HloRecvDoneInstruction>( Cast<HloRecvInstruction>(new_operands[0])); } HloAllReduceInstruction::HloAllReduceInstruction( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> operands, HloComputation* reduce_computation, tensorflow::gtl::ArraySlice<int64> replica_group_ids, tensorflow::StringPiece barrier, const tensorflow::gtl::optional<int64>& all_reduce_id) : HloInstruction(HloOpcode::kCrossReplicaSum, shape), replica_group_ids_(replica_group_ids.begin(), replica_group_ids.end()), cross_replica_sum_barrier_(barrier.begin(), barrier.end()), all_reduce_id_(all_reduce_id) { // TODO(b/79737069): Remove the CHECK when supported. CHECK(!all_reduce_id_); for (auto operand : operands) { AppendOperand(operand); } AppendComputation(reduce_computation); } HloInstructionProto HloAllReduceInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); for (int64 i : replica_group_ids_) { proto.add_replica_group_ids(i); } // Proto3 is so sad. if (all_reduce_id_) { proto.set_all_reduce_id(*all_reduce_id_); } proto.set_cross_replica_sum_barrier(cross_replica_sum_barrier_); return proto; } std::vector<string> HloAllReduceInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& /*options*/) const { std::vector<string> result = { StrCat("replica_group_ids={", Join(replica_group_ids(), ","), "}")}; if (!cross_replica_sum_barrier().empty()) { result.push_back(StrCat("barrier=\"", cross_replica_sum_barrier(), "\"")); } if (all_reduce_id_) { result.push_back(StrCat("all_reduce_id=", *all_reduce_id_)); } return result; } bool HloAllReduceInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { const auto& casted_other = static_cast<const HloAllReduceInstruction&>(other); return replica_group_ids() == casted_other.replica_group_ids() && eq_computations(to_apply(), casted_other.to_apply()) && cross_replica_sum_barrier() == casted_other.cross_replica_sum_barrier() && all_reduce_id() == casted_other.all_reduce_id(); } std::unique_ptr<HloInstruction> HloAllReduceInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* /*context*/) const { return MakeUnique<HloAllReduceInstruction>( shape, new_operands, to_apply(), replica_group_ids(), cross_replica_sum_barrier(), all_reduce_id()); } HloReverseInstruction::HloReverseInstruction( const Shape& shape, HloInstruction* operand, tensorflow::gtl::ArraySlice<int64> dimensions) : HloInstruction(HloOpcode::kReverse, shape), dimensions_(dimensions.begin(), dimensions.end()) { AppendOperand(operand); } HloInstructionProto HloReverseInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); for (int64 dimension : dimensions_) { proto.add_dimensions(dimension); } return proto; } std::vector<string> HloReverseInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { return {StrCat("dimensions={", Join(dimensions(), ","), "}")}; } bool HloReverseInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { const auto& casted_other = static_cast<const HloReverseInstruction&>(other); return dimensions() == casted_other.dimensions(); } std::unique_ptr<HloInstruction> HloReverseInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { CHECK_EQ(new_operands.size(), 1); return MakeUnique<HloReverseInstruction>(shape, new_operands[0], dimensions()); } HloConcatenateInstruction::HloConcatenateInstruction( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> operands, int64 dimension) : HloInstruction(HloOpcode::kConcatenate, shape), dimensions_({dimension}) { for (auto operand : operands) { AppendOperand(operand); } } HloInstructionProto HloConcatenateInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); for (int64 dimension : dimensions_) { proto.add_dimensions(dimension); } return proto; } std::vector<string> HloConcatenateInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { return {StrCat("dimensions={", Join(dimensions(), ","), "}")}; } bool HloConcatenateInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { const auto& casted_other = static_cast<const HloConcatenateInstruction&>(other); return dimensions() == casted_other.dimensions(); } std::unique_ptr<HloInstruction> HloConcatenateInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { return MakeUnique<HloConcatenateInstruction>(shape, new_operands, dimensions(0)); } HloReduceInstruction::HloReduceInstruction( const Shape& shape, HloInstruction* arg, HloInstruction* init_value, tensorflow::gtl::ArraySlice<int64> dimensions_to_reduce, HloComputation* reduce_computation) : HloInstruction(HloOpcode::kReduce, shape), dimensions_(dimensions_to_reduce.begin(), dimensions_to_reduce.end()) { AppendOperand(arg); AppendOperand(init_value); AppendComputation(reduce_computation); } HloInstructionProto HloReduceInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); for (int64 dimension : dimensions_) { proto.add_dimensions(dimension); } return proto; } std::vector<string> HloReduceInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { return {StrCat("dimensions={", Join(dimensions(), ","), "}")}; } bool HloReduceInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { const auto& casted_other = static_cast<const HloReduceInstruction&>(other); // Reduction results are determined by the reduction dimension and the // reduction computation. return dimensions() == casted_other.dimensions() && eq_computations(to_apply(), casted_other.to_apply()); } std::unique_ptr<HloInstruction> HloReduceInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { CHECK_EQ(new_operands.size(), 2); return MakeUnique<HloReduceInstruction>( shape, new_operands[0], new_operands[1], dimensions(), to_apply()); } HloTransposeInstruction::HloTransposeInstruction( const Shape& shape, HloInstruction* operand, tensorflow::gtl::ArraySlice<int64> dimensions) : HloInstruction(HloOpcode::kTranspose, shape), dimensions_(dimensions.begin(), dimensions.end()) { CHECK_EQ(shape.dimensions().size(), dimensions.size()); CHECK_EQ(shape.dimensions().size(), operand->shape().dimensions().size()); CHECK(std::equal(operand->shape().dimensions().begin(), operand->shape().dimensions().end(), Permute(dimensions, shape.dimensions()).begin())) << "shape: " << ShapeUtil::HumanString(shape) << ", operand->shape(): " << ShapeUtil::HumanString(shape) << ", dimensions: {" << Join(dimensions, ", ") << "}"; AppendOperand(operand); } bool HloTransposeInstruction::IsRank2Transpose() const { return dimensions() == std::vector<int64>({1, 0}) && shape().dimensions_size() == 2 && std::equal(shape().dimensions().begin(), shape().dimensions().end(), operand(0)->shape().dimensions().rbegin()); } HloInstructionProto HloTransposeInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); for (int64 dimension : dimensions_) { proto.add_dimensions(dimension); } return proto; } std::vector<string> HloTransposeInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { return {StrCat("dimensions={", Join(dimensions(), ","), "}")}; } bool HloTransposeInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { const auto& casted_other = static_cast<const HloTransposeInstruction&>(other); return dimensions() == casted_other.dimensions(); } std::unique_ptr<HloInstruction> HloTransposeInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { CHECK_EQ(new_operands.size(), 1); return MakeUnique<HloTransposeInstruction>(shape, new_operands[0], dimensions()); } HloBroadcastInstruction::HloBroadcastInstruction( const Shape& shape, HloInstruction* operand, tensorflow::gtl::ArraySlice<int64> broadcast_dimension) : HloInstruction(HloOpcode::kBroadcast, shape), dimensions_(broadcast_dimension.begin(), broadcast_dimension.end()) { AppendOperand(operand); } HloInstructionProto HloBroadcastInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); for (int64 dimension : dimensions_) { proto.add_dimensions(dimension); } return proto; } std::vector<string> HloBroadcastInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { return {StrCat("dimensions={", Join(dimensions(), ","), "}")}; } bool HloBroadcastInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { const auto& casted_other = static_cast<const HloBroadcastInstruction&>(other); return dimensions() == casted_other.dimensions(); } std::unique_ptr<HloInstruction> HloBroadcastInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { CHECK_EQ(new_operands.size(), 1); return MakeUnique<HloBroadcastInstruction>(shape, new_operands[0], dimensions()); } HloMapInstruction::HloMapInstruction( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> operands, HloComputation* map_computation) : HloInstruction(HloOpcode::kMap, shape) { for (auto operand : operands) { AppendOperand(operand); } AppendComputation(map_computation); // TODO(b/65689298) Remove code below once Map is generalized to accept // arbitrary map dimensions. dimensions_.resize(ShapeUtil::Rank(shape)); std::iota(dimensions_.begin(), dimensions_.end(), 0); } HloInstructionProto HloMapInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); for (int64 dimension : dimensions_) { proto.add_dimensions(dimension); } return proto; } bool HloMapInstruction::IsElementwiseImpl( const tensorflow::gtl::optional<int64>& operand_idx) const { if (!dimensions().empty()) { // Check that the map is executed in elementwise compatible dimensions. if (dimensions().size() != shape().dimensions_size()) { return false; } for (int i = 0; i < dimensions().size(); ++i) { if (dimensions()[i] != i) { return false; } } } return true; } std::vector<string> HloMapInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { return {StrCat("dimensions={", Join(dimensions(), ","), "}")}; } bool HloMapInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { return eq_computations(to_apply(), other.to_apply()); } std::unique_ptr<HloInstruction> HloMapInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { return MakeUnique<HloMapInstruction>(shape, new_operands, to_apply()); } HloSliceInstruction::HloSliceInstruction( const Shape& shape, HloInstruction* operand, tensorflow::gtl::ArraySlice<int64> start_indices, tensorflow::gtl::ArraySlice<int64> limit_indices, tensorflow::gtl::ArraySlice<int64> strides) : HloInstruction(HloOpcode::kSlice, shape), slice_starts_(start_indices.begin(), start_indices.end()), slice_limits_(limit_indices.begin(), limit_indices.end()), slice_strides_(strides.begin(), strides.end()) { AppendOperand(operand); // For backward compatibility with old serialized computations: if there are // no strides, assume all strides are 1. // TODO(b/63317920): remove this code. if (slice_strides_.empty()) { slice_strides_ = std::vector<int64>(start_indices.size(), 1LL); } } HloInstructionProto HloSliceInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); for (int i = 0; i < slice_starts_.size(); ++i) { auto* slice_dimension = proto.add_slice_dimensions(); slice_dimension->set_start(slice_starts_[i]); slice_dimension->set_limit(slice_limits_[i]); slice_dimension->set_stride(slice_strides_[i]); } return proto; } std::vector<string> HloSliceInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { std::vector<string> bounds; bounds.reserve(slice_starts_.size()); const bool omit_stride = std::all_of(slice_strides_.begin(), slice_strides_.end(), [](int64 stride) { return stride == 1; }); for (int i = 0; i < slice_starts_.size(); ++i) { string stride_str = omit_stride ? "" : StrCat(":", slice_strides_[i]); bounds.push_back( StrCat("[", slice_starts_[i], ":", slice_limits_[i], stride_str, "]")); } return {StrCat("slice={", Join(bounds, ", "), "}")}; } bool HloSliceInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { const auto& other_slice = static_cast<const HloSliceInstruction&>(other); return slice_starts_ == other_slice.slice_starts_ && slice_limits_ == other_slice.slice_limits_ && slice_strides_ == other_slice.slice_strides_; } std::unique_ptr<HloInstruction> HloSliceInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { CHECK_EQ(new_operands.size(), 1); return MakeUnique<HloSliceInstruction>(shape, new_operands[0], slice_starts_, slice_limits_, slice_strides_); } HloConstantInstruction::HloConstantInstruction(std::unique_ptr<Literal> literal) : HloInstruction(HloOpcode::kConstant, CHECK_NOTNULL(literal)->shape()), literal_(std::move(literal)) {} HloConstantInstruction::HloConstantInstruction(const Shape& shape) : HloInstruction(HloOpcode::kConstant, shape) {} HloInstructionProto HloConstantInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); if (literal_ != nullptr) { *proto.mutable_literal() = literal_->ToProto(); } return proto; } bool HloConstantInstruction::IsElementwiseImpl( const tensorflow::gtl::optional<int64>& operand_idx) const { return true; } void HloConstantInstruction::RelayoutConstant(const Layout& new_layout, const ShapeIndex& shape_index) { Shape* mutable_array_subshape = ShapeUtil::GetMutableSubshape(mutable_shape(), shape_index); CHECK(ShapeUtil::IsArray(*mutable_array_subshape)); // Normally array_subshape will always have a layout, but this invariant is // temporarily broken in LayoutAssignment::AssignLayouts. if (!mutable_array_subshape->has_layout() || !LayoutUtil::Equal(mutable_array_subshape->layout(), new_layout)) { literal_ = literal_->Relayout(new_layout, shape_index); *mutable_array_subshape->mutable_layout() = new_layout; } } bool HloConstantInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { const auto& other_slice = static_cast<const HloSliceInstruction&>(other); return literal() == other_slice.literal(); } std::unique_ptr<HloInstruction> HloConstantInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { return MakeUnique<HloConstantInstruction>(literal_->CloneToUnique()); } string HloConstantInstruction::OperandsToStringWithCanonicalNameMap( const HloPrintOptions& options, CanonicalNameMap* canonical_name_map) const { string operands; // For constants, show the actual value in place of an empty operand list. if (literal_ != nullptr && ((ShapeUtil::IsArray(shape()) && ShapeUtil::ElementsIn(shape()) <= 10) || options.print_large_constants())) { // Literal::ToString emits multidimensional arrays over multiple // lines. Compact this into one line by stripping out white space. string tmp = literal().ToString(); std::replace(tmp.begin(), tmp.end(), '\n', ' '); std::vector<string> v = tensorflow::str_util::Split(tmp, ' '); bool first = true; // Concatenate elements in "v" with spaces separating them, but ignoring // empty entries. for (const auto& s : v) { if (s.empty()) { continue; } StrAppend(&operands, (first ? "" : " "), s); first = false; } } else { // Do not show large constants or tuples. operands = "{...}"; } return operands; } HloTraceInstruction::HloTraceInstruction(const string& tag, HloInstruction* operand) : HloInstruction(HloOpcode::kTrace, ShapeUtil::MakeNil()), literal_(LiteralUtil::CreateR1U8(tag)) { AppendOperand(operand); operand->set_tracing(this); } HloInstructionProto HloTraceInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); *proto.mutable_literal() = literal_->ToProto(); return proto; } bool HloTraceInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { return false; } std::unique_ptr<HloInstruction> HloTraceInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { LOG(FATAL) << "Not yet implemented, clone: " << HloOpcodeString(opcode()); } HloFusionInstruction::HloFusionInstruction(const Shape& shape, FusionKind fusion_kind, HloInstruction* fused_root) : HloInstruction(HloOpcode::kFusion, shape), fusion_kind_(fusion_kind) { CHECK(fused_root != nullptr); SetAndSanitizeName("fusion"); set_parent(fused_root->parent()); set_metadata(fused_root->metadata()); CloneAndFuseInternal(fused_root); } HloFusionInstruction::HloFusionInstruction( const Shape& shape, FusionKind fusion_kind, tensorflow::gtl::ArraySlice<HloInstruction*> operands, HloComputation* fusion_computation) : HloInstruction(HloOpcode::kFusion, shape), fusion_kind_(fusion_kind) { for (auto operand : operands) { AppendOperand(operand); } SetAndSanitizeName("fusion"); AppendComputation(fusion_computation); fusion_computation->SetFusionInstruction(this); } string HloFusionInstruction::ToCategory() const { switch (fusion_kind()) { case FusionKind::kLoop: return "loop fusion"; case FusionKind::kInput: return "input fusion"; case FusionKind::kOutput: return "output fusion"; case FusionKind::kCustom: return "custom fusion"; } } HloInstructionProto HloFusionInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); proto.set_fusion_kind(xla::ToString(fusion_kind())); proto.add_called_computation_ids( fused_instructions_computation()->unique_id()); return proto; } bool HloFusionInstruction::IsElementwiseImpl( const tensorflow::gtl::optional<int64>& operand_idx) const { if (!operand_idx.has_value()) { for (auto* fused : fused_instructions()) { if (fused->opcode() != HloOpcode::kParameter && !fused->IsElementwise()) { return false; } } return true; } // A loop-fusion is elementwise on an operand if all operations (computed // using BFS) between the operand and the fused root are elementwise. std::deque<HloInstruction*> worklist; std::unordered_set<const HloInstruction*> visited; worklist.push_back(fused_parameter(operand_idx.value())); visited.insert(fused_parameter(operand_idx.value())); while (!worklist.empty()) { HloInstruction* operand = worklist.front(); worklist.pop_front(); for (HloInstruction* user : operand->users()) { CHECK_GE(user->unique_id(), 0); if (ContainsKey(visited, user)) { continue; } if (user->IsElementwise() || IsInstructionElementwiseOnOperand(user, operand)) { worklist.push_back(user); visited.insert(user); } else { return false; } } } return true; } HloInstruction* HloFusionInstruction::AddFusionOperand( HloInstruction* new_operand) { CHECK_EQ(operand_count(), fused_instructions_computation()->parameter_instructions().size()); const int64 param_no = operand_count(); // Name the parameter after the instruction it represents in the outer // (non-fusion) computation. string param_name = StrCat(new_operand->name(), ".param_", param_no); HloInstruction* fused_parameter = fused_instructions_computation()->AddParameter( HloInstruction::CreateParameter(param_no, new_operand->shape(), param_name)); AppendOperand(new_operand); return fused_parameter; } void HloFusionInstruction::MergeFusionInstruction( HloFusionInstruction* instruction_to_merge) { CHECK(std::find(operands().begin(), operands().end(), instruction_to_merge) != operands().end()); // Clone the instruction from which to merge fused instructions. std::unique_ptr<HloInstruction> cloned = instruction_to_merge->Clone(); HloFusionInstruction* cloned_fusion = static_cast<HloFusionInstruction*>(cloned.get()); // Replace uses of fused parameters with the corresponding operand of the // fusion. Add all non-parameter fused instructions to // 'unfused_instructions' to be merged into 'this'. This is done in reverse // post order. std::vector<HloInstruction*> unfused_instructions; auto fused_instructions = cloned_fusion->fused_instructions_computation() ->MakeInstructionPostOrder(); for (auto fused_it = fused_instructions.rbegin(); fused_it != fused_instructions.rend(); ++fused_it) { auto fused_instruction = *fused_it; if (fused_instruction->opcode() == HloOpcode::kParameter) { TF_CHECK_OK( fused_instruction->ReplaceAllUsesWith(cloned_fusion->mutable_operand( fused_instruction->parameter_number()))); } else { unfused_instructions.push_back(fused_instruction); } } CHECK(unfused_instructions.front() == cloned_fusion->fused_expression_root()); // Replace instruction_to_merge use of 'this' with unfused_root. TF_CHECK_OK( instruction_to_merge->ReplaceUseWith(this, unfused_instructions.front())); // Fuse 'unfused_instructions' into 'this'. for (auto& instruction : unfused_instructions) { FuseInstruction(instruction); } CHECK_EQ(0, cloned_fusion->user_count()); TF_CHECK_OK(parent()->parent()->RemoveEmbeddedComputation( cloned_fusion->fused_instructions_computation())); } void HloFusionInstruction::MergeFusionInstructionIntoMultiOutput( HloFusionInstruction* instruction_to_merge) { // Add all non-parameter fused instructions to 'unfused_instructions' to be // merged into 'this'. `old_to_new' maps the instructions in the fused node // to the disaseembled fusion instructions. // Note that we add the unfused instructions to this->parent_ computation. // This is necessary because the unique_id needs for an instruction and // it's only added when inserting to the computation. tensorflow::gtl::FlatMap<HloInstruction*, HloInstruction*> old_to_new; std::vector<HloInstruction*> unfused_instructions; auto computation_to_merge = instruction_to_merge->fused_instructions_computation(); auto post_order = computation_to_merge->MakeInstructionPostOrder(); for (auto rit = post_order.rbegin(); rit != post_order.rend(); ++rit) { auto fused_instruction = *rit; if (fused_instruction->opcode() == HloOpcode::kParameter) { InsertOrDie(&old_to_new, fused_instruction, instruction_to_merge->mutable_operand( fused_instruction->parameter_number())); continue; } // Here we clone the insertion and call FuseInstructionIntoMultiOutput() // which clones again. This can be improved. auto cloned_instruction = parent()->AddInstruction(fused_instruction->Clone()); unfused_instructions.push_back(cloned_instruction); InsertOrDie(&old_to_new, fused_instruction, cloned_instruction); } for (auto unfused_instruction : unfused_instructions) { for (int64 index = 0; index < unfused_instruction->operand_count(); index++) { auto new_operand = FindOrDie(old_to_new, unfused_instruction->mutable_operand(index)); TF_CHECK_OK(unfused_instruction->ReplaceOperandWith(index, new_operand)); } } HloInstruction* unfused_root = unfused_instructions.front(); TF_CHECK_OK(instruction_to_merge->ReplaceAllUsesWith(unfused_root)); TF_CHECK_OK( instruction_to_merge->parent()->RemoveInstruction(instruction_to_merge)); if (GetModule()) { TF_CHECK_OK(GetModule()->RemoveEmbeddedComputation(computation_to_merge)); } // Fuse the root instruction and generate multiple outputs. FuseInstructionIntoMultiOutput(unfused_root); TF_CHECK_OK(unfused_root->parent()->RemoveInstruction(unfused_root)); // The rest instructions are of normal fusing. for (int64 i = 1; i < unfused_instructions.size(); i++) { auto instruction = unfused_instructions[i]; FuseInstruction(instruction); TF_CHECK_OK(instruction->parent()->RemoveInstruction(instruction)); } } HloComputation* HloFusionInstruction::fused_instructions_computation() const { CHECK(!called_computations().empty()); auto* fused_instructions_computation = called_computations().front(); CHECK(fused_instructions_computation->IsFusionComputation()) << "Computation " << fused_instructions_computation->name() << " is not a fusion kind"; return fused_instructions_computation; } HloInstruction* HloFusionInstruction::fused_expression_root() const { return fused_instructions_computation()->root_instruction(); } HloInstruction* HloFusionInstruction::fused_parameter( int64 parameter_number) const { return fused_instructions_computation()->parameter_instruction( parameter_number); } const std::vector<HloInstruction*>& HloFusionInstruction::fused_parameters() const { return fused_instructions_computation()->parameter_instructions(); } const tensorflow::gtl::iterator_range<UnwrappingIterator< std::list<std::unique_ptr<HloInstruction>>::const_iterator>> HloFusionInstruction::fused_instructions() const { const HloComputation* subcomp = fused_instructions_computation(); return subcomp->instructions(); } const tensorflow::gtl::iterator_range< UnwrappingIterator<std::list<std::unique_ptr<HloInstruction>>::iterator>> HloFusionInstruction::fused_instructions() { return fused_instructions_computation()->instructions(); } int64 HloFusionInstruction::fused_instruction_count() const { return fused_instructions_computation()->instruction_count(); } HloInstruction* HloFusionInstruction::FuseInstructionInternal( HloInstruction* instruction_to_fuse, bool add_output) { // When add_output is false, this fusion instruction must be a user of // instruction_to_fuse. if (!add_output) { CHECK(IsUserOf(instruction_to_fuse)); } HloInstruction* fused_instruction = CloneAndFuseInternal(instruction_to_fuse, add_output); return fused_instruction; } HloInstruction* HloFusionInstruction::CloneAndFuseInternal( HloInstruction* instruction_to_fuse, bool add_output) { CHECK(instruction_to_fuse->IsFusable()) << instruction_to_fuse->ToString(); VLOG(3) << "CloneAndFuseInternal:\n" << instruction_to_fuse->ToString(); HloInstruction* clone = nullptr; if (called_computations().empty()) { // New fusion instruction. It should not be a multioutput instruction. CHECK(!add_output); auto builder = HloComputation::Builder("fused_computation", this); builder.AddInstruction(instruction_to_fuse->Clone(/*suffix=*/"")); AppendComputation( CHECK_NOTNULL(GetModule())->AddEmbeddedComputation(builder.Build())); clone = fused_expression_root(); } else { // When add_output is false, instruction_to_fuse is necessarily an operand // of the fusion instruction. After fusion this will no longer be the // case. Remove the operand from the operand list and remove its // corresponding fused parameter instruction. Renumber parameters as // necessary to make parameter numbers consistent with their index in the // fused_parameter_ vector. bool in_operand_list = std::find(operands().begin(), operands().end(), instruction_to_fuse) != operands().end(); CHECK(add_output || in_operand_list); if (instruction_to_fuse->opcode() == HloOpcode::kTuple) { // We assume all uses of a kTuple operation are GTE ops, not another // fusion node. In this case, we don't need to clone // 'instruction_to_fuse'. CHECK(!in_operand_list); clone = instruction_to_fuse; } else { clone = fused_instructions_computation()->AddInstruction( instruction_to_fuse->Clone(/*suffix=*/"")); } const std::vector<HloInstruction*>& fused_parameters = fused_instructions_computation()->parameter_instructions(); for (int64 operand_num = 0; operand_num < operand_count(); ++operand_num) { if (instruction_to_fuse == operand(operand_num)) { // replace the fused parameter instruction's uses with the clone. HloInstruction* fused_parameter = fused_parameters[operand_num]; TF_CHECK_OK(fused_parameter->ReplaceAllUsesWith(clone)); // Remove the corresponding fused parameter and operand from their // respective vectors. TF_CHECK_OK( fused_instructions_computation()->RemoveParameter(operand_num)); RemoveOperandAt(operand_num); break; } } // We've cloned instruction_to_fuse into this fusion instruction, so this // fusion instruction is no longer a use of instruction_to_fuse. if (in_operand_list) { DetachFrom(instruction_to_fuse); // When the instruction_to_fuse does not have other users, we don't need // to generate a multioutput fusion instruction. if (instruction_to_fuse->user_count() == 0) { add_output = false; } } } // Reread the parameters in the computation. const std::vector<HloInstruction*>& fused_parameters = fused_instructions_computation()->parameter_instructions(); // Add each operand of the clone as an operand of the fusion instruction. A // complication is that some clone operands may already be operands of the // fusion instruction. for (int64 operand_num = 0; operand_num < clone->operand_count(); ++operand_num) { HloInstruction* operand = clone->mutable_operand(operand_num); // See if this operand is already an operand of the fusion node. CHECK_EQ(operands().size(), fused_parameters.size()); HloInstruction* fused_param = nullptr; for (int64 i = 0; i < operands().size(); ++i) { if (this->operand(i) == operand) { fused_param = fused_parameters[i]; break; } } if (fused_param == nullptr) { // Clone's operand was not already an operand of the fusion // instruction. Add it as an operand and add a corresponding fused // parameter instruction. fused_param = AddFusionOperand(operand); } TF_CHECK_OK(clone->ReplaceOperandWith(operand_num, fused_param)); } if (add_output) { CHECK_GT(instruction_to_fuse->user_count(), 0); // If this is already a multioutput fusion instruction, expand the root // tuple by 1. HloInstruction* fused_root = fused_expression_root(); HloInstruction::InstructionVector tuple_elements; bool newly_created_tuple_instr = false; if (fused_root->opcode() == HloOpcode::kTuple) { tuple_elements = fused_root->operands(); } else { tuple_elements.push_back(fused_root); newly_created_tuple_instr = true; } if (clone->opcode() == HloOpcode::kTuple) { for (auto inst : clone->operands()) { tuple_elements.push_back(inst); } } else { tuple_elements.push_back(clone); } HloInstruction* new_root = fused_instructions_computation()->AddInstruction( HloInstruction::CreateTuple(tuple_elements)); fused_instructions_computation()->set_root_instruction(new_root); *mutable_shape() = new_root->shape(); if (fused_root->opcode() == HloOpcode::kTuple) { TF_CHECK_OK( fused_instructions_computation()->RemoveInstruction(fused_root)); } // If this is a newly created multioutput instruction, we need to update // the use of the original fusion instruction. if (newly_created_tuple_instr) { HloInstruction* new_instr = parent()->AddInstruction( HloInstruction::CreateGetTupleElement(fused_root->shape(), this, 0)); TF_CHECK_OK(ReplaceAllUsesWith(new_instr)); } int64 index = tuple_elements.size(); if (instruction_to_fuse->opcode() == HloOpcode::kTuple) { CHECK_EQ(clone, instruction_to_fuse); index -= clone->operand_count(); std::vector<HloInstruction*> to_be_removed; for (auto old_gte : clone->users()) { CHECK_EQ(old_gte->opcode(), HloOpcode::kGetTupleElement); int64 old_tuple_index = old_gte->tuple_index(); HloInstruction* new_gte = parent()->AddInstruction(HloInstruction::CreateGetTupleElement( old_gte->shape(), this, index + old_tuple_index)); TF_CHECK_OK(old_gte->ReplaceAllUsesWith(new_gte)); to_be_removed.push_back(old_gte); } for (auto old_gte : to_be_removed) { TF_CHECK_OK(parent()->RemoveInstruction(old_gte)); } } else { HloInstruction* new_gte = parent()->AddInstruction(HloInstruction::CreateGetTupleElement( clone->shape(), this, index - 1)); TF_CHECK_OK(instruction_to_fuse->ReplaceAllUsesWith(new_gte)); } } if (clone != instruction_to_fuse) { VLOG(2) << "New clone:\n" << clone->ToString(); } return clone; } std::vector<string> HloFusionInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { return {StrCat("kind=", xla::ToString(fusion_kind()))}; } bool HloFusionInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { return fusion_kind() == other.fusion_kind() && eq_computations(fused_instructions_computation(), other.fused_instructions_computation()); } std::unique_ptr<HloInstruction> HloFusionInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { HloModule* module = context != nullptr ? context->module() : GetModule(); HloComputation* new_fused_computation = nullptr; if (context != nullptr) { new_fused_computation = context->FindComputation(fused_instructions_computation()); } if (new_fused_computation == nullptr) { new_fused_computation = module->AddEmbeddedComputation( fused_instructions_computation()->Clone("clone", context)); } return MakeUnique<HloFusionInstruction>(shape, fusion_kind(), new_operands, new_fused_computation); } Status HloFusionInstruction::DeduplicateFusionOperands() { tensorflow::gtl::FlatMap<const HloInstruction*, int> operand_indices; std::vector<int> operands_to_remove; for (int i = 0; i < operand_count(); ++i) { auto emplace_result = operand_indices.emplace(operand(i), i); if (!emplace_result.second) { TF_RETURN_IF_ERROR(fused_parameter(i)->ReplaceAllUsesWith( fused_parameter(emplace_result.first->second))); operands_to_remove.push_back(i); } } if (operands_to_remove.empty()) { return Status::OK(); } TF_RETURN_IF_ERROR( fused_instructions_computation()->RemoveUnusedParameters()); RemoveOperandsAtAscendingIndices(operands_to_remove); return Status::OK(); } HloRngInstruction::HloRngInstruction( const Shape& shape, RandomDistribution distribution, tensorflow::gtl::ArraySlice<HloInstruction*> parameters) : HloInstruction(HloOpcode::kRng, shape), distribution_(distribution) { for (HloInstruction* param : parameters) { AppendOperand(param); } } HloInstructionProto HloRngInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); proto.set_distribution(distribution_); return proto; } std::vector<string> HloRngInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { return {StrCat("distribution=", RandomDistributionToString(distribution_))}; } bool HloRngInstruction::IsElementwiseImpl( const tensorflow::gtl::optional<int64>& operand_idx) const { return true; } bool HloRngInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { return false; } std::unique_ptr<HloInstruction> HloRngInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { return MakeUnique<HloRngInstruction>(shape, distribution_, new_operands); } HloParameterInstruction::HloParameterInstruction(int64 parameter_number, const Shape& shape, const string& name) : HloInstruction(HloOpcode::kParameter, shape), parameter_number_(parameter_number) { SetAndSanitizeName(name); } HloInstructionProto HloParameterInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); proto.set_parameter_number(parameter_number_); return proto; } string HloParameterInstruction::OperandsToStringWithCanonicalNameMap( const HloPrintOptions& options, CanonicalNameMap* canonical_name_map) const { return StrCat(parameter_number_); } bool HloParameterInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { const auto& casted_other = static_cast<const HloParameterInstruction&>(other); return parameter_number() == casted_other.parameter_number(); } std::unique_ptr<HloInstruction> HloParameterInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { return MakeUnique<HloParameterInstruction>(parameter_number_, shape, name()); } HloGetTupleElementInstruction::HloGetTupleElementInstruction( const Shape& shape, HloInstruction* operand, int64 index) : HloInstruction(HloOpcode::kGetTupleElement, shape), tuple_index_(index) { CHECK(ShapeUtil::IsTuple(operand->shape())); AppendOperand(operand); } HloInstructionProto HloGetTupleElementInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); proto.set_tuple_index(tuple_index_); return proto; } std::vector<string> HloGetTupleElementInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { return {StrCat("index=", tuple_index())}; } bool HloGetTupleElementInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { const auto& casted_other = static_cast<const HloGetTupleElementInstruction&>(other); return tuple_index() == casted_other.tuple_index(); } std::unique_ptr<HloInstruction> HloGetTupleElementInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { CHECK_EQ(new_operands.size(), 1); return MakeUnique<HloGetTupleElementInstruction>(shape, new_operands[0], tuple_index()); } HloReducePrecisionInstruction::HloReducePrecisionInstruction( const Shape& shape, HloInstruction* operand, const int exponent_bits, const int mantissa_bits) : HloInstruction(HloOpcode::kReducePrecision, shape), exponent_bits_(exponent_bits), mantissa_bits_(mantissa_bits) { AppendOperand(operand); } HloInstructionProto HloReducePrecisionInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); proto.set_exponent_bits(exponent_bits_); proto.set_mantissa_bits(mantissa_bits_); return proto; } std::vector<string> HloReducePrecisionInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { return {StrCat("exponent_bits=", exponent_bits_), StrCat("mantissa_bits=", mantissa_bits_)}; } bool HloReducePrecisionInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { const auto& casted_other = static_cast<const HloReducePrecisionInstruction&>(other); // A reduce-precision operation is determined by the bit sizes. return exponent_bits() == casted_other.exponent_bits() && mantissa_bits() == casted_other.mantissa_bits(); } std::unique_ptr<HloInstruction> HloReducePrecisionInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { CHECK_EQ(new_operands.size(), 1); return MakeUnique<HloReducePrecisionInstruction>( shape, new_operands[0], exponent_bits(), mantissa_bits()); } HloInfeedInstruction::HloInfeedInstruction(const Shape& infeed_shape, HloInstruction* token_operand, const string& config) : HloInstruction(HloOpcode::kInfeed, ShapeUtil::MakeTupleShape( {infeed_shape, ShapeUtil::MakeTokenShape()})), infeed_config_(config) { AppendOperand(token_operand); } HloInfeedInstruction::HloInfeedInstruction(const Shape& infeed_shape, const string& config) : HloInstruction(HloOpcode::kInfeed, ShapeUtil::MakeTupleShape( {infeed_shape, ShapeUtil::MakeTokenShape()})), infeed_config_(config) {} HloInstructionProto HloInfeedInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); proto.set_infeed_config(infeed_config_); return proto; } std::vector<string> HloInfeedInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { if (infeed_config_.empty()) { return {}; } return {StrCat("infeed_config=\"", CEscape(infeed_config_), "\"")}; } bool HloInfeedInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { // Not yet supported. return false; } std::unique_ptr<HloInstruction> HloInfeedInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { if (new_operands.empty()) { return MakeUnique<HloInfeedInstruction>(infeed_shape(), infeed_config()); } else { CHECK_EQ(new_operands.size(), 1); return MakeUnique<HloInfeedInstruction>(infeed_shape(), new_operands[0], infeed_config()); } } HloOutfeedInstruction::HloOutfeedInstruction( const Shape& outfeed_shape, HloInstruction* operand, HloInstruction* token_operand, tensorflow::StringPiece outfeed_config) : HloInstruction(HloOpcode::kOutfeed, ShapeUtil::MakeTokenShape()), outfeed_shape_(outfeed_shape), outfeed_config_(outfeed_config.begin(), outfeed_config.end()) { CHECK(ShapeUtil::Compatible(operand->shape(), outfeed_shape)) << "Outfeed shape " << outfeed_shape << " must be compatible with operand shape " << operand->shape(); AppendOperand(operand); AppendOperand(token_operand); } HloOutfeedInstruction::HloOutfeedInstruction( const Shape& outfeed_shape, HloInstruction* operand, tensorflow::StringPiece outfeed_config) : HloInstruction(HloOpcode::kOutfeed, ShapeUtil::MakeTokenShape()), outfeed_shape_(outfeed_shape), outfeed_config_(outfeed_config.begin(), outfeed_config.end()) { CHECK(ShapeUtil::Compatible(operand->shape(), outfeed_shape)) << "Outfeed shape " << outfeed_shape << " must be compatible with operand shape " << operand->shape(); AppendOperand(operand); } HloInstructionProto HloOutfeedInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); proto.set_outfeed_config(outfeed_config()); *proto.mutable_outfeed_shape() = outfeed_shape(); return proto; } std::vector<string> HloOutfeedInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { if (outfeed_config_.empty()) { return {}; } return {StrCat("outfeed_config=\"", CEscape(outfeed_config_), "\"")}; } bool HloOutfeedInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { // Not yet supported. return false; } std::unique_ptr<HloInstruction> HloOutfeedInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { if (new_operands.size() == 1) { return MakeUnique<HloOutfeedInstruction>(outfeed_shape(), new_operands[0], outfeed_config()); } else { CHECK_EQ(new_operands.size(), 2); return MakeUnique<HloOutfeedInstruction>(outfeed_shape(), new_operands[0], new_operands[1], outfeed_config()); } } HloConvolutionInstruction::HloConvolutionInstruction( const Shape& shape, HloInstruction* lhs, HloInstruction* rhs, const Window& window, const ConvolutionDimensionNumbers& dimension_numbers) : HloInstruction(HloOpcode::kConvolution, shape), window_(window), convolution_dimension_numbers_(dimension_numbers) { if (window_util::HasBaseDilation(window)) { SetAndSanitizeName(StrCat(name(), "-base-dilated")); } if (window_util::HasWindowDilation(window)) { SetAndSanitizeName(StrCat(name(), "-window-dilated")); } AppendOperand(lhs); AppendOperand(rhs); } string HloConvolutionInstruction::ToCategory() const { string category = "convolution"; if (window_util::HasBaseDilation(window())) { category += " base-dilated"; } if (window_util::HasWindowDilation(window())) { category += " window-dilated"; } return category; } HloInstructionProto HloConvolutionInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); *proto.mutable_window() = window_; *proto.mutable_convolution_dimension_numbers() = convolution_dimension_numbers_; return proto; } std::vector<string> HloConvolutionInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { std::vector<string> extra; if (window_.dimensions_size() != 0) { extra.push_back(StrCat("window={", window_util::ToString(window()), "}")); } extra.push_back(StrCat("dim_labels=", ConvolutionDimensionNumbersToString( convolution_dimension_numbers_))); return extra; } bool HloConvolutionInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { const auto& casted_other = static_cast<const HloConvolutionInstruction&>(other); return protobuf_util::ProtobufEquals(window(), casted_other.window()) && protobuf_util::ProtobufEquals( convolution_dimension_numbers(), casted_other.convolution_dimension_numbers()); } std::unique_ptr<HloInstruction> HloConvolutionInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { CHECK_EQ(new_operands.size(), 2); return MakeUnique<HloConvolutionInstruction>(shape, new_operands[0], new_operands[1], window(), convolution_dimension_numbers_); } HloReduceWindowInstruction::HloReduceWindowInstruction( const Shape& shape, HloInstruction* operand, HloInstruction* init_value, const Window& window, HloComputation* reduce_computation) : HloInstruction(HloOpcode::kReduceWindow, shape), window_(window) { AppendOperand(operand); AppendOperand(init_value); AppendComputation(reduce_computation); } HloInstructionProto HloReduceWindowInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); *proto.mutable_window() = window_; return proto; } std::vector<string> HloReduceWindowInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { std::vector<string> extra; if (window_.dimensions_size() != 0) { extra.push_back(StrCat("window={", window_util::ToString(window()), "}")); } return extra; } bool HloReduceWindowInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { const auto& casted_other = static_cast<const HloReduceWindowInstruction&>(other); return eq_computations(to_apply(), casted_other.to_apply()) && protobuf_util::ProtobufEquals(window(), casted_other.window()); } std::unique_ptr<HloInstruction> HloReduceWindowInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { CHECK_EQ(new_operands.size(), 2); return MakeUnique<HloReduceWindowInstruction>( shape, new_operands[0], new_operands[1], window(), to_apply()); } HloSelectAndScatterInstruction::HloSelectAndScatterInstruction( const Shape& shape, HloInstruction* operand, HloComputation* select, const Window& window, HloInstruction* source, HloInstruction* init_value, HloComputation* scatter) : HloInstruction(HloOpcode::kSelectAndScatter, shape), window_(window) { AppendOperand(operand); AppendOperand(source); AppendOperand(init_value); // Select comes before scatter in the vector. AppendComputation(select); AppendComputation(scatter); } HloInstructionProto HloSelectAndScatterInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); *proto.mutable_window() = window_; return proto; } std::vector<string> HloSelectAndScatterInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { std::vector<string> extra; if (window_.dimensions_size() != 0) { extra.push_back(StrCat("window={", window_util::ToString(window()), "}")); } return extra; } bool HloSelectAndScatterInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { const auto& casted_other = static_cast<const HloSelectAndScatterInstruction&>(other); return eq_computations(select(), casted_other.select()) && eq_computations(scatter(), casted_other.scatter()) && protobuf_util::ProtobufEquals(window(), casted_other.window()); } std::unique_ptr<HloInstruction> HloSelectAndScatterInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { CHECK_EQ(new_operands.size(), 3); return MakeUnique<HloSelectAndScatterInstruction>( shape, new_operands[0], select(), window(), new_operands[1], new_operands[2], scatter()); } HloCustomCallInstruction::HloCustomCallInstruction( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> operands, tensorflow::StringPiece custom_call_target) : HloInstruction(HloOpcode::kCustomCall, shape), custom_call_target_(custom_call_target.begin(), custom_call_target.end()) { for (auto operand : operands) { AppendOperand(operand); } } HloInstructionProto HloCustomCallInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); if (window_ != nullptr) { *proto.mutable_window() = *window_; } if (convolution_dimension_numbers_ != nullptr) { *proto.mutable_convolution_dimension_numbers() = *convolution_dimension_numbers_; } proto.set_custom_call_target(custom_call_target_); return proto; } std::vector<string> HloCustomCallInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { std::vector<string> extra; if (window_ != nullptr && window_->dimensions_size() != 0) { extra.push_back(StrCat("window={", window_util::ToString(*window_), "}")); } if (convolution_dimension_numbers_ != nullptr) { extra.push_back(StrCat( "dim_labels=", ConvolutionDimensionNumbersToString(*convolution_dimension_numbers_))); } // By contract, we print the custom call target even if // options.print_subcomputation_mode() == kOff, because the call target is not // an HloComputation. extra.push_back( StrCat("custom_call_target=\"", CEscape(custom_call_target_), "\"")); return extra; } bool HloCustomCallInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { const auto& casted_other = static_cast<const HloCustomCallInstruction&>(other); if ((window_ == nullptr) != (casted_other.window_ == nullptr) || (window_ != nullptr && !protobuf_util::ProtobufEquals(*window_, *casted_other.window_))) { return false; } if ((convolution_dimension_numbers_ == nullptr) != (casted_other.convolution_dimension_numbers_ == nullptr) || (convolution_dimension_numbers_ != nullptr && !protobuf_util::ProtobufEquals( convolution_dimension_numbers(), casted_other.convolution_dimension_numbers()))) { return false; } return custom_call_target_ == casted_other.custom_call_target_; } std::unique_ptr<HloInstruction> HloCustomCallInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { auto cloned = MakeUnique<HloCustomCallInstruction>(shape, new_operands, custom_call_target()); if (window_ != nullptr) { cloned->set_window(*window_); } if (convolution_dimension_numbers_ != nullptr) { cloned->set_convolution_dimension_numbers(*convolution_dimension_numbers_); } return std::move(cloned); } HloHostComputeInstruction::HloHostComputeInstruction( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> operands, tensorflow::StringPiece channel_name, const int64 cost_estimate_ns) : HloInstruction(HloOpcode::kHostCompute, shape), channel_name_(channel_name.begin(), channel_name.end()), cost_estimate_ns_(cost_estimate_ns) { for (auto operand : operands) { AppendOperand(operand); } } HloInstructionProto HloHostComputeInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); proto.set_channel_name(channel_name_); proto.set_cost_estimate_ns(cost_estimate_ns_); return proto; } bool HloHostComputeInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { // Not yet supported. return false; } std::unique_ptr<HloInstruction> HloHostComputeInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { return MakeUnique<HloHostComputeInstruction>( shape, new_operands, channel_name_, cost_estimate_ns_); } HloPadInstruction::HloPadInstruction(const Shape& shape, HloInstruction* operand, HloInstruction* padding_value, const PaddingConfig& padding_config) : HloInstruction(HloOpcode::kPad, shape), padding_config_(padding_config) { AppendOperand(operand); AppendOperand(padding_value); } HloInstructionProto HloPadInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); *proto.mutable_padding_config() = padding_config_; return proto; } std::vector<string> HloPadInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { return {StrCat("padding=", xla::PaddingConfigToString(padding_config_))}; } bool HloPadInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { const auto& casted_other = static_cast<const HloPadInstruction&>(other); return protobuf_util::ProtobufEquals(padding_config(), casted_other.padding_config()); } std::unique_ptr<HloInstruction> HloPadInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { CHECK_EQ(new_operands.size(), 2); return MakeUnique<HloPadInstruction>(shape, new_operands[0], new_operands[1], padding_config_); } HloDynamicSliceInstruction::HloDynamicSliceInstruction( const Shape& shape, HloInstruction* operand, HloInstruction* start_indices, tensorflow::gtl::ArraySlice<int64> slice_sizes) : HloInstruction(HloOpcode::kDynamicSlice, shape), dynamic_slice_sizes_(slice_sizes.begin(), slice_sizes.end()) { AppendOperand(operand); AppendOperand(start_indices); } HloInstructionProto HloDynamicSliceInstruction::ToProto() const { HloInstructionProto proto = HloInstruction::ToProto(); for (int64 slice_size : dynamic_slice_sizes_) { proto.add_dynamic_slice_sizes(slice_size); } return proto; } std::vector<string> HloDynamicSliceInstruction::ExtraAttributesToStringImpl( const HloPrintOptions& options) const { return { StrCat("dynamic_slice_sizes={", Join(dynamic_slice_sizes(), ","), "}")}; } bool HloDynamicSliceInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { return true; } std::unique_ptr<HloInstruction> HloDynamicSliceInstruction::CloneWithNewOperandsImpl( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> new_operands, HloCloneContext* context) const { CHECK_EQ(new_operands.size(), 2); return MakeUnique<HloDynamicSliceInstruction>( shape, new_operands[0], new_operands[1], dynamic_slice_sizes_); } } // namespace xla
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
b82def8410554f78089ed4b763edd016077bc78c
38971dd6c0d87a47138f1e3f171deebb34778402
/StrokeDraw.hpp
0c0a8963858c0e83f02755fa515b3926d3f63bfc
[ "LicenseRef-scancode-public-domain" ]
permissive
ixchow/Soft-Stacking
c55c301c4a3955b8d7c61eedd530ad81e8c7ff28
cbcc7fdd63b69f5a8cb64f9bcb9c13e45814cf3f
refs/heads/master
2021-01-21T00:44:11.459148
2012-05-11T18:58:50
2012-05-11T18:58:50
4,300,368
2
0
null
null
null
null
UTF-8
C++
false
false
1,173
hpp
#ifndef STROKE_DRAW_HPP #define STROKE_DRAW_HPP #include "Tiled.hpp" #include <QtOpenGL> #include <vector> class StrokeBrush { public: StrokeBrush(float softness = 0.5f, float radius = 10.0f); float rate; //stamps / radius float flow; //paint / stamp float radius; //radius, in pixels //These require re-rendering tex: float softness; GLuint get_tex(); private: GLuint tex; //GL_TEXTURE_2D texture for brush; updated, if needed, when you call 'get_tex()'. NOTE: always use in same GL context! float tex_softness; }; //NOTE: call StrokeDraw functions with a consistent current GL context! class StrokeDraw { public: StrokeDraw(StrokeBrush *brush, Stroke *into); ~StrokeDraw(); void start(Vector3f const &first_point, TileSet &changed); void add_point(Vector3f const &); //actually, it's okay to call 'add_point' without a context. void commit(TileSet &changed); //draw accumulated points so far. void finish(TileSet &changed); //finish off acculated points std::vector< Vector4f > acc; //z,y,radius,opacity float along; ScalarTiled< QGLFramebufferObject * > fbs; StrokeBrush *brush; Stroke *into; bool eraser; }; #endif //STROKE_DRAW_HPP
[ "jmccann@cs.cmu.edu" ]
jmccann@cs.cmu.edu
4785cd8c62d84ae17e7edb1da8c776385ddad269
a5c097df386a44c0c05e606189949b04a447d7b0
/IQ-TREE/main/phyloanalysis.h
fb58c74492c068423e970f51bcd16abbc354b30f
[ "GPL-2.0-only", "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
joshlvmh/iqtree_arm_neon
f4855b3fa6de75c7d0ff3e46993e07c32b2be1ce
7bc67d3449428b0b683fb7359c8945da218f5775
refs/heads/master
2023-01-06T02:25:47.293773
2020-10-21T20:12:15
2020-10-21T20:12:15
289,253,476
2
1
MIT
2020-10-20T08:10:22
2020-08-21T11:30:06
C++
UTF-8
C++
false
false
4,942
h
/*************************************************************************** * Copyright (C) 2009-2015 by * * BUI Quang Minh <minh.bui@univie.ac.at> * * Lam-Tung Nguyen <nltung@gmail.com> * * * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef PHYLOANALYSIS_H #define PHYLOANALYSIS_H #include "utils/tools.h" #include "tree/mexttree.h" #include "phylotesting.h" #include "tree/upperbounds.h" // Olga: functions for Upper Bounds analysis #include "utils/pllnni.h" class PhyloTree; class IQTree; /** main function to carry out phylogenetic inference @param params program parameters */ void runPhyloAnalysis(Params &params, Checkpoint *checkpoint); void startTreeReconstruction(Params &params, IQTree* &iqtree, ModelCheckpoint &model_info); void runTreeReconstruction(Params &params, IQTree* &tree); /** take the collection of trees from input_trees, it assign support values to target_tree and print resulting tree to output_tree. @param input_trees collection of input trees to infer split supports @param burnin the number trees at the beginning of input_trees to be discarded @param max_count max number of trees to load @param target_tree tree to assign support value @param output_tree (OUT, OVERWRITE IF EXIST) Resulting will be written to this file. If NULL, output_tree will be named target_tree appended with ".suptree" */ void assignBootstrapSupport(const char *input_trees, int burnin, int max_count, const char *target_tree, bool rooted, const char *output_tree, const char *out_prefix, MExtTree &mytree, const char* tree_weight_file, Params *params); /** * assign branch supports from params.user_tree trees file to params.second_tree * @param params program parameters */ void assignBranchSupportNew(Params &params); /** Compute the consensus tree from the collection of trees from input_trees and print resulting tree to output_tree. @param phylo_tree used to optimize branch lengths of the consensus tree. Can be NULL @param input_trees collection of input trees to infer split supports @param burnin the number trees at the beginning of input_trees to be discarded @param max_count max number of trees to load @param cutoff only incorporate those splits that have support values more than cutoff @param weight_threshold minimum weight cutoff @param output_tree (OUT, OVERWRITE IF EXIST) Resulting consensus tree will be written to this file. If NULL, output_tree will be named input_trees appended with ".contree" */ void computeConsensusTree(const char *input_trees, int burnin, int max_count, double cutoff, double weight_threshold, const char *output_tree, const char *out_prefix, const char* tree_weight_file, Params *params); /** Compute the consensus network from the collection of trees in input_trees. print consensus network to output_tree @param input_trees collection of input trees to infer split supports @param burnin the number trees at the beginning of input_trees to be discarded @param max_count max number of trees to load @param cutoff only incorporate those splits that have support values more than cutoff @param weight_threshold minimum weight cutoff @param output_tree (OUT, OVERWRITE IF EXIST) Resulting consensus tree will be written to this file. If NULL, output_tree will be named input_trees appended with ".connetwork" */ void computeConsensusNetwork(const char *input_trees, int burnin, int max_count, double cutoff, int weight_summary, double weight_threshold, const char *output_tree, const char *out_prefix, const char* tree_weight_file); #endif
[ "jm17923@bristol.ac.uk" ]
jm17923@bristol.ac.uk
2b0731ae47bc4d84c5eab5a8178ded3ae3714db7
c0c9d8404fe97f53095060540ae8a9031a82d3b5
/actor.cpp
3fa398608727e31a5b9b2cf0d9443a5275180d24
[]
no_license
nindwen/BeneathTheSurface
34702a5cacac502c052b8e85acf9fd2ac5de12be
9c5c1ab263aa61abb09b98495e472f0a0c97ba02
refs/heads/master
2020-04-03T15:38:29.755744
2014-05-11T09:54:37
2014-05-11T09:54:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,029
cpp
#include "Library.h" #include "actor.h" #include "level.h" Actor::Actor(int x, int y) { this->x=x; this->y=y; destinationX=x; destinationY=y; moving=0; speed=5; dx=dy=0; lightLevel=12; selected=false; } int Actor::update() { if(library->lClicked) { int x,y; SDL_GetMouseState(&x,&y); x-=library->cameraX; y-=library->cameraY; if( (x>=this->x*library->TILE_SIZE && x<=this->x*library->TILE_SIZE+library->TILE_SIZE) && (y>=this->y*library->TILE_SIZE && y<= this->y*library->TILE_SIZE+library->TILE_SIZE)) { selected=true; library->lClicked=false; } else { selected=false; } } if(library->rClicked && selected) { int x,y; SDL_GetMouseState(&x,&y); x-=library->cameraX; y-=library->cameraY; selected=false; setDestination(x/library->TILE_SIZE,y/library->TILE_SIZE); } if(moving) { if(dx==0 && dy==0) { moving=0; } else { if(dx!=0) { if(dx<0) { dx+=speed; } else { dx-=speed; } } if(dy!=0) { if(dy<0) {dy+=speed; } else { dy-=speed; } } } } else { //If we are not moving and are not ind destination, search path if(x != destinationX || y != destinationY) { listMap* closed = library->currentlevel->findPath(x,y,destinationX,destinationY); if(closed==nullptr) { return 0; } nodeMap* temp = closed->first; while(1) { if(temp->parent->x==x && temp->parent->y==y) { move(temp->x-x,temp->y-y); return 1; } temp=temp->parent; } delete closed; } } return 1; } void Actor::move(int x, int y) { this->x+=x; this->y+=y; //Smooth movement-stuff: dx-=library->TILE_SIZE*x; dy-=library->TILE_SIZE*y; moving=1; //Update lightleve lightLevel=library->currentlevel->level[this->x][this->y].lightLevel; } int Actor::setDestination(int x, int y) { //If accesible if(library->currentlevel->level[x][y].Solid || (x==0 || y==0) || (x==library->LEVEL_SIZE-1 || y==library->LEVEL_SIZE-1) ) { return 0; } destinationX=x; destinationY=y; return 1; }
[ "lumolk@gmail.com" ]
lumolk@gmail.com
aeb53329e98cb89363830dfb90565d212913ff39
9f6c390325504934e6851a64a6c549382f847aa2
/esphome/dscKeybusInterface/dscKeybusProcessData.cpp
d8c3c347d8f067532499827df63ab81100c59472
[]
no_license
JVoogt/bianca-conf
ba9d3af034e6495a760437bd27384d8c88c2285e
ec1a1a8b9c09cfbc518adfb38faaabca97e07850
refs/heads/master
2023-03-01T18:35:01.518525
2021-02-01T12:09:24
2021-02-01T12:09:24
326,715,481
0
0
null
null
null
null
UTF-8
C++
false
false
44,714
cpp
/* DSC Keybus Interface https://github.com/taligentx/dscKeybusInterface This library is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "dscKeybusInterface.h" // Resets the state of all status components as changed for sketches to get the current status void dscKeybusInterface::resetStatus() { statusChanged = true; keybusChanged = true; //troubleChanged = true; powerChanged = true; batteryChanged = true; for (byte partition = 0; partition < dscPartitions; partition++) { readyChanged[partition] = true; armedChanged[partition] = true; alarmChanged[partition] = true; fireChanged[partition] = true; troubleChanged = true; disabled[partition] = true; } openZonesStatusChanged = true; alarmZonesStatusChanged = true; for (byte zoneGroup = 0; zoneGroup < dscZones; zoneGroup++) { openZonesChanged[zoneGroup] = 0xFF; alarmZonesChanged[zoneGroup] = 0xFF; } } // Sets the panel time bool dscKeybusInterface::setTime(unsigned int year, byte month, byte day, byte hour, byte minute, const char* accessCode) { // Loops if a previous write is in progress while(writeKeyPending || writeKeysPending) { loop(); #if defined(ESP8266) yield(); #endif } if (!ready[0]) return false; // Skips if partition 1 is not ready if (hour > 23 || minute > 59 || month > 12 || day > 31 || year > 2099 || (year > 99 && year < 1900)) return false; // Skips if input date/time is invalid static char timeEntry[21]; strcpy(timeEntry, "*6"); strcat(timeEntry, accessCode); strcat(timeEntry, "1"); char timeChar[3]; if (hour < 10) strcat(timeEntry, "0"); itoa(hour, timeChar, 10); strcat(timeEntry, timeChar); if (minute < 10) strcat(timeEntry, "0"); itoa(minute, timeChar, 10); strcat(timeEntry, timeChar); if (month < 10) strcat(timeEntry, "0"); itoa(month, timeChar, 10); strcat(timeEntry, timeChar); if (day < 10) strcat(timeEntry, "0"); itoa(day, timeChar, 10); strcat(timeEntry, timeChar); if (year >= 2000) year -= 2000; else if (year >= 1900) year -= 1900; if (year < 10) strcat(timeEntry, "0"); itoa(year, timeChar, 10); strcat(timeEntry, timeChar); strcat(timeEntry, "#"); write(timeEntry); return true; } // Processes status commands: 0x05 (Partitions 1-4) and 0x1B (Partitions 5-8) void dscKeybusInterface::processPanelStatus() { // Trouble status if (panelData[3] <= 0x05) { // Ignores trouble light status in intermittent states if (bitRead(panelData[2],4)) trouble = true; else trouble = false; if (trouble != previousTrouble) { previousTrouble = trouble; troubleChanged = true; if (!pauseStatus) statusChanged = true; } } // Sets partition counts based on the status command and generation of panel byte partitionStart = 0; byte partitionCount = 0; if (panelData[0] == 0x05) { partitionStart = 0; if (panelByteCount < 9) partitionCount = 2; // Handles earlier panels that support up to 2 partitions else partitionCount = 4; if (dscPartitions < partitionCount) partitionCount = dscPartitions; } else if (dscPartitions > 4 && panelData[0] == 0x1B) { partitionStart = 4; partitionCount = 8; } // Sets status per partition for (byte partitionIndex = partitionStart; partitionIndex < partitionCount; partitionIndex++) { byte statusByte, messageByte; if (partitionIndex < 4) { statusByte = (partitionIndex * 2) + 2; messageByte = (partitionIndex * 2) + 3; } else { statusByte = ((partitionIndex - 4) * 2) + 2; messageByte = ((partitionIndex - 4) * 2) + 3; } // Partition disabled status if (panelData[messageByte] == 0xC7) disabled[partitionIndex] = true; else disabled[partitionIndex] = false; // Status lights lights[partitionIndex] = panelData[statusByte]; if (lights[partitionIndex] != previousLights[partitionIndex]) { previousLights[partitionIndex] = lights[partitionIndex]; if (!pauseStatus) statusChanged = true; } // Status messages status[partitionIndex] = panelData[messageByte]; if (status[partitionIndex] != previousStatus[partitionIndex]) { previousStatus[partitionIndex] = status[partitionIndex]; if (!pauseStatus) statusChanged = true; } // Fire status if (panelData[messageByte] < 0x12) { // Ignores fire light status in intermittent states if (bitRead(panelData[statusByte],6)) fire[partitionIndex] = true; else fire[partitionIndex] = false; if (fire[partitionIndex] != previousFire[partitionIndex]) { previousFire[partitionIndex] = fire[partitionIndex]; fireChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } } // Messages switch (panelData[messageByte]) { // Ready case 0x01: // Partition ready case 0x02: { // Stay/away zones open ready[partitionIndex] = true; if (ready[partitionIndex] != previousReady[partitionIndex]) { previousReady[partitionIndex] = ready[partitionIndex]; readyChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } noEntryDelay[partitionIndex] = false; entryDelay[partitionIndex] = false; if (entryDelay[partitionIndex] != previousEntryDelay[partitionIndex]) { previousEntryDelay[partitionIndex] = entryDelay[partitionIndex]; entryDelayChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } armedStay[partitionIndex] = false; armedAway[partitionIndex] = false; armed[partitionIndex] = false; if (armed[partitionIndex] != previousArmed[partitionIndex]) { previousArmed[partitionIndex] = armed[partitionIndex]; armedChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } alarm[partitionIndex] = false; if (alarm[partitionIndex] != previousAlarm[partitionIndex]) { previousAlarm[partitionIndex] = alarm[partitionIndex]; alarmChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } break; } // Zones open case 0x03: { ready[partitionIndex] = false; if (ready[partitionIndex] != previousReady[partitionIndex]) { previousReady[partitionIndex] = ready[partitionIndex]; readyChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } noEntryDelay[partitionIndex] = false; entryDelay[partitionIndex] = false; if (entryDelay[partitionIndex] != previousEntryDelay[partitionIndex]) { previousEntryDelay[partitionIndex] = entryDelay[partitionIndex]; entryDelayChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } break; } // Armed case 0x04: // Armed stay case 0x05: { // Armed away writeArm[partitionIndex] = false; if (bitRead(panelData[statusByte],1) ) { // look for armed light being set to ensure valid arm message if (panelData[messageByte] == 0x04) { armedStay[partitionIndex] = true; armedAway[partitionIndex] = false; } else { armedStay[partitionIndex] = false; armedAway[partitionIndex] = true; } armed[partitionIndex] = true; if (armed[partitionIndex] != previousArmed[partitionIndex] || armedStay[partitionIndex] != previousArmedStay[partitionIndex]) { previousArmed[partitionIndex] = armed[partitionIndex]; previousArmedStay[partitionIndex] = armedStay[partitionIndex]; armedChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } } ready[partitionIndex] = false; if (ready[partitionIndex] != previousReady[partitionIndex]) { previousReady[partitionIndex] = ready[partitionIndex]; readyChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } exitDelay[partitionIndex] = false; if (exitDelay[partitionIndex] != previousExitDelay[partitionIndex]) { previousExitDelay[partitionIndex] = exitDelay[partitionIndex]; exitDelayChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } exitState[partitionIndex] = 0; entryDelay[partitionIndex] = false; if (entryDelay[partitionIndex] != previousEntryDelay[partitionIndex]) { previousEntryDelay[partitionIndex] = entryDelay[partitionIndex]; entryDelayChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } break; } // Exit delay in progress case 0x08: { writeArm[partitionIndex] = false; accessCodePrompt = false; exitDelay[partitionIndex] = true; if (exitDelay[partitionIndex] != previousExitDelay[partitionIndex]) { previousExitDelay[partitionIndex] = exitDelay[partitionIndex]; exitDelayChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } if (exitState[partitionIndex] != DSC_EXIT_NO_ENTRY_DELAY) { if (bitRead(lights[partitionIndex],3)) exitState[partitionIndex] = DSC_EXIT_STAY; else exitState[partitionIndex] = DSC_EXIT_AWAY; if (exitState[partitionIndex] != previousExitState[partitionIndex]) { previousExitState[partitionIndex] = exitState[partitionIndex]; exitDelayChanged[partitionIndex] = true; exitStateChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } } ready[partitionIndex] = true; if (ready[partitionIndex] != previousReady[partitionIndex]) { previousReady[partitionIndex] = ready[partitionIndex]; readyChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } break; } // Arming with no entry delay case 0x09: { ready[partitionIndex] = true; if (ready[partitionIndex] != previousReady[partitionIndex]) { previousReady[partitionIndex] = ready[partitionIndex]; readyChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } exitState[partitionIndex] = DSC_EXIT_NO_ENTRY_DELAY; break; } // Entry delay in progress case 0x0C: { ready[partitionIndex] = false; if (ready[partitionIndex] != previousReady[partitionIndex]) { previousReady[partitionIndex] = ready[partitionIndex]; readyChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } entryDelay[partitionIndex] = true; if (entryDelay[partitionIndex] != previousEntryDelay[partitionIndex]) { previousEntryDelay[partitionIndex] = entryDelay[partitionIndex]; entryDelayChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } break; } // Partition in alarm case 0x11: { ready[partitionIndex] = false; if (ready[partitionIndex] != previousReady[partitionIndex]) { previousReady[partitionIndex] = ready[partitionIndex]; readyChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } entryDelay[partitionIndex] = false; if (entryDelay[partitionIndex] != previousEntryDelay[partitionIndex]) { previousEntryDelay[partitionIndex] = entryDelay[partitionIndex]; entryDelayChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } alarm[partitionIndex] = true; if (alarm[partitionIndex] != previousAlarm[partitionIndex]) { previousAlarm[partitionIndex] = alarm[partitionIndex]; alarmChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } break; } // Arming with bypassed zones case 0x15: { ready[partitionIndex] = true; if (ready[partitionIndex] != previousReady[partitionIndex]) { previousReady[partitionIndex] = ready[partitionIndex]; readyChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } break; } // Partition armed with no entry delay case 0x06: case 0x16: { noEntryDelay[partitionIndex] = true; // Sets an armed mode if not already set, used if interface is initialized while the panel is armed if (!armedStay[partitionIndex] && !armedAway[partitionIndex]) armedStay[partitionIndex] = true; armed[partitionIndex] = true; if (armed[partitionIndex] != previousArmed[partitionIndex]) { previousArmed[partitionIndex] = armed[partitionIndex]; previousArmedStay[partitionIndex] = armedStay[partitionIndex]; armedChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } ready[partitionIndex] = false; if (ready[partitionIndex] != previousReady[partitionIndex]) { previousReady[partitionIndex] = ready[partitionIndex]; readyChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } break; } // possible power failure. Do not set state unavailable case 0x17: break; // Partition disarmed case 0x3D: case 0x3E: { if (panelData[messageByte] == 0x3E) { // Sets ready only during Partition disarmed ready[partitionIndex] = true; if (ready[partitionIndex] != previousReady[partitionIndex]) { previousReady[partitionIndex] = ready[partitionIndex]; readyChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } } exitDelay[partitionIndex] = false; if (exitDelay[partitionIndex] != previousExitDelay[partitionIndex]) { previousExitDelay[partitionIndex] = exitDelay[partitionIndex]; exitDelayChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } exitState[partitionIndex] = 0; noEntryDelay[partitionIndex] = false; entryDelay[partitionIndex] = false; if (entryDelay[partitionIndex] != previousEntryDelay[partitionIndex]) { previousEntryDelay[partitionIndex] = entryDelay[partitionIndex]; entryDelayChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } armedStay[partitionIndex] = false; armedAway[partitionIndex] = false; armed[partitionIndex] = false; if (armed[partitionIndex] != previousArmed[partitionIndex]) { previousArmed[partitionIndex] = armed[partitionIndex]; armedChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } alarm[partitionIndex] = false; if (alarm[partitionIndex] != previousAlarm[partitionIndex]) { previousAlarm[partitionIndex] = alarm[partitionIndex]; alarmChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } break; } // Invalid access code case 0x8F: { if (!armed[partitionIndex]) { ready[partitionIndex] = true; if (ready[partitionIndex] != previousReady[partitionIndex]) { previousReady[partitionIndex] = ready[partitionIndex]; readyChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } } break; } // Enter * function code case 0x9E: { wroteAsterisk = false; // Resets the flag that delays writing after '*' is pressed writeAsterisk = false; writeKeyPending = false; ready[partitionIndex] = false; if (ready[partitionIndex] != previousReady[partitionIndex]) { previousReady[partitionIndex] = ready[partitionIndex]; readyChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } break; } // Enter access code case 0x9F: { if (writeArm[partitionIndex]) { // Ensures access codes are only sent when an arm command is sent through this interface accessCodePrompt = true; if (!pauseStatus) statusChanged = true; } ready[partitionIndex] = false; if (ready[partitionIndex] != previousReady[partitionIndex]) { previousReady[partitionIndex] = ready[partitionIndex]; readyChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } break; } default: { ready[partitionIndex] = false; if (ready[partitionIndex] != previousReady[partitionIndex]) { previousReady[partitionIndex] = ready[partitionIndex]; readyChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } break; } } } } // Panel status and zones 1-8 status void dscKeybusInterface::processPanel_0x27() { if (!validCRC()) return; // Messages for (byte partitionIndex = 0; partitionIndex < 2; partitionIndex++) { byte messageByte = (partitionIndex * 2) + 3; // Armed if (panelData[messageByte] == 0x04 || panelData[messageByte] == 0x05) { ready[partitionIndex] = false; if (ready[partitionIndex] != previousReady[partitionIndex]) { previousReady[partitionIndex] = ready[partitionIndex]; readyChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } if (panelData[messageByte] == 0x04) { armedStay[partitionIndex] = true; armedAway[partitionIndex] = false; } else if (panelData[messageByte] == 0x05) { armedStay[partitionIndex] = false; armedAway[partitionIndex] = true; } armed[partitionIndex] = true; if (armed[partitionIndex] != previousArmed[partitionIndex] || armedStay[partitionIndex] != previousArmedStay[partitionIndex]) { previousArmed[partitionIndex] = armed[partitionIndex]; previousArmedStay[partitionIndex] = armedStay[partitionIndex]; armedChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } exitDelay[partitionIndex] = false; if (exitDelay[partitionIndex] != previousExitDelay[partitionIndex]) { previousExitDelay[partitionIndex] = exitDelay[partitionIndex]; exitDelayChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } exitState[partitionIndex] = 0; } // Armed with no entry delay else if (panelData[messageByte] == 0x16 || panelData[messageByte] == 0x06) { noEntryDelay[partitionIndex] = true; // Sets an armed mode if not already set, used if interface is initialized while the panel is armed if (!armedStay[partitionIndex] && !armedAway[partitionIndex]) armedStay[partitionIndex] = true; armed[partitionIndex] = true; if (armed[partitionIndex] != previousArmed[partitionIndex]) { previousArmed[partitionIndex] = armed[partitionIndex]; previousArmedStay[partitionIndex] = armedStay[partitionIndex]; armedChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } exitDelay[partitionIndex] = false; if (exitDelay[partitionIndex] != previousExitDelay[partitionIndex]) { previousExitDelay[partitionIndex] = exitDelay[partitionIndex]; exitDelayChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } exitState[partitionIndex] = 0; ready[partitionIndex] = false; if (ready[partitionIndex] != previousReady[partitionIndex]) { previousReady[partitionIndex] = ready[partitionIndex]; readyChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } } } // Open zones 1-8 status is stored in openZones[0] and openZonesChanged[0]: Bit 0 = Zone 1 ... Bit 7 = Zone 8 openZones[0] = panelData[6]; byte zonesChanged = openZones[0] ^ previousOpenZones[0]; if (zonesChanged != 0) { previousOpenZones[0] = openZones[0]; openZonesStatusChanged = true; if (!pauseStatus) statusChanged = true; for (byte zoneBit = 0; zoneBit < 8; zoneBit++) { if (bitRead(zonesChanged, zoneBit)) { bitWrite(openZonesChanged[0], zoneBit, 1); if (bitRead(panelData[6], zoneBit)) bitWrite(openZones[0], zoneBit, 1); else bitWrite(openZones[0], zoneBit, 0); } } } } // Zones 9-16 status void dscKeybusInterface::processPanel_0x2D() { if (!validCRC()) return; if (dscZones < 2) return; // Open zones 9-16 status is stored in openZones[1] and openZonesChanged[1]: Bit 0 = Zone 9 ... Bit 7 = Zone 16 openZones[1] = panelData[6]; byte zonesChanged = openZones[1] ^ previousOpenZones[1]; if (zonesChanged != 0) { previousOpenZones[1] = openZones[1]; openZonesStatusChanged = true; if (!pauseStatus) statusChanged = true; for (byte zoneBit = 0; zoneBit < 8; zoneBit++) { if (bitRead(zonesChanged, zoneBit)) { bitWrite(openZonesChanged[1], zoneBit, 1); if (bitRead(panelData[6], zoneBit)) bitWrite(openZones[1], zoneBit, 1); else bitWrite(openZones[1], zoneBit, 0); } } } } // Zones 17-24 status void dscKeybusInterface::processPanel_0x34() { if (!validCRC()) return; if (dscZones < 3) return; // Open zones 17-24 status is stored in openZones[2] and openZonesChanged[2]: Bit 0 = Zone 17 ... Bit 7 = Zone 24 openZones[2] = panelData[6]; byte zonesChanged = openZones[2] ^ previousOpenZones[2]; if (zonesChanged != 0) { previousOpenZones[2] = openZones[2]; openZonesStatusChanged = true; if (!pauseStatus) statusChanged = true; for (byte zoneBit = 0; zoneBit < 8; zoneBit++) { if (bitRead(zonesChanged, zoneBit)) { bitWrite(openZonesChanged[2], zoneBit, 1); if (bitRead(panelData[6], zoneBit)) bitWrite(openZones[2], zoneBit, 1); else bitWrite(openZones[2], zoneBit, 0); } } } } // Zones 25-32 status void dscKeybusInterface::processPanel_0x3E() { if (!validCRC()) return; if (dscZones < 4) return; // Open zones 25-32 status is stored in openZones[3] and openZonesChanged[3]: Bit 0 = Zone 25 ... Bit 7 = Zone 32 openZones[3] = panelData[6]; byte zonesChanged = openZones[3] ^ previousOpenZones[3]; if (zonesChanged != 0) { previousOpenZones[3] = openZones[3]; openZonesStatusChanged = true; if (!pauseStatus) statusChanged = true; for (byte zoneBit = 0; zoneBit < 8; zoneBit++) { if (bitRead(zonesChanged, zoneBit)) { bitWrite(openZonesChanged[3], zoneBit, 1); if (bitRead(panelData[6], zoneBit)) bitWrite(openZones[3], zoneBit, 1); else bitWrite(openZones[3], zoneBit, 0); } } } } void dscKeybusInterface::processPanel_0xA5() { if (!validCRC()) return; byte dscYear3 = panelData[2] >> 4; byte dscYear4 = panelData[2] & 0x0F; year = (dscYear3 * 10) + dscYear4; if (dscYear3 >= 7) year += 1900; else year += 2000; month = panelData[3] << 2; month >>= 4; byte dscDay1 = panelData[3] << 6; dscDay1 >>= 3; byte dscDay2 = panelData[4] >> 5; day = dscDay1 | dscDay2; hour = panelData[4] & 0x1F; minute = panelData[5] >> 2; // Timestamp if (panelData[6] == 0 && panelData[7] == 0) { statusChanged = true; timestampChanged = true; return; } byte partition = panelData[3] >> 6; switch (panelData[5] & 0x03) { case 0x00: processPanelStatus0(partition, 6); break; case 0x02: processPanelStatus2(partition, 6); break; } } void dscKeybusInterface::processPanel_0xEB() { if (!validCRC()) return; if (dscPartitions < 3) return; byte dscYear3 = panelData[3] >> 4; byte dscYear4 = panelData[3] & 0x0F; year = (dscYear3 * 10) + dscYear4; if (dscYear3 >= 7) year += 1900; else year += 2000; month = panelData[4] << 2; month >>=4; byte dscDay1 = panelData[4] << 6; dscDay1 >>= 3; byte dscDay2 = panelData[5] >> 5; day = dscDay1 | dscDay2; hour = panelData[5] & 0x1F; minute = panelData[6] >> 2; byte partition; switch (panelData[2]) { case 0x01: partition = 1; break; case 0x02: partition = 2; break; case 0x04: partition = 3; break; case 0x08: partition = 4; break; case 0x10: partition = 5; break; case 0x20: partition = 6; break; case 0x40: partition = 7; break; case 0x80: partition = 8; break; default: partition = 0; break; } switch (panelData[7] & 0x07) { case 0x00: processPanelStatus0(partition, 8); break; case 0x02: processPanelStatus2(partition, 8); break; case 0x04: processPanelStatus4(partition, 8); break; } } void dscKeybusInterface::processPanelStatus0(byte partition, byte panelByte) { // Processes status messages that are not partition-specific if ( panelData[0] == 0xA5) { switch (panelData[panelByte]) { // Keypad Fire alarm case 0x4E: { keypadFireAlarm = true; if (!pauseStatus) statusChanged = true; return; } // Keypad Aux alarm case 0x4F: { keypadAuxAlarm = true; if (!pauseStatus) statusChanged = true; return; } // Keypad Panic alarm case 0x50: { keypadPanicAlarm = true; if (!pauseStatus) statusChanged =true; return; } // Panel battery trouble case 0xE7: { batteryTrouble = true; batteryChanged = true; if (!pauseStatus) statusChanged = true; return; } // Panel AC power failure case 0xE8: { powerTrouble = true; powerChanged = true; if (!pauseStatus) statusChanged = true; return; } // Panel battery restored case 0xEF: { batteryTrouble = false; batteryChanged = true; if (!pauseStatus) statusChanged = true; return; } // Panel AC power restored case 0xF0: { powerTrouble = false; powerChanged = true; if (!pauseStatus) statusChanged = true; return; } default: if (partition == 0) return; } } // Processes partition-specific status if (partition > dscPartitions) return; // Ensures that only the configured number of partitions are processed byte partitionIndex = partition - 1; // Disarmed if (panelData[panelByte] == 0x4A || // Disarmed after alarm in memory panelData[panelByte] == 0xE6 || // Disarmed special: keyswitch/wireless key/DLS (panelData[panelByte] >= 0xC0 && panelData[panelByte] <= 0xE4)) { // Disarmed by access code noEntryDelay[partitionIndex] = false; armedAway[partitionIndex] = false; armedStay[partitionIndex] = false; armed[partitionIndex] = false; if (armed[partitionIndex] != previousArmed[partitionIndex]) { previousArmed[partitionIndex] = armed[partitionIndex]; armedChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } alarm[partitionIndex] = false; if (alarm[partitionIndex] != previousAlarm[partitionIndex]) { previousAlarm[partitionIndex] = alarm[partitionIndex]; alarmChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } entryDelay[partitionIndex] = false; if (entryDelay[partitionIndex] != previousEntryDelay[partitionIndex]) { previousEntryDelay[partitionIndex] = entryDelay[partitionIndex]; entryDelayChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } return; } // Partition in alarm if (panelData[panelByte] == 0x4B) { alarm[partitionIndex] = true; if (alarm[partitionIndex] != previousAlarm[partitionIndex]) { previousAlarm[partitionIndex] = alarm[partitionIndex]; alarmChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } return; } // Zone alarm, zones 1-32 // Zone alarm status is stored using 1 bit per zone in alarmZones[] and alarmZonesChanged[]: // alarmZones[0] and alarmZonesChanged[0]: Bit 0 = Zone 1 ... Bit 7 = Zone 8 // alarmZones[1] and alarmZonesChanged[1]: Bit 0 = Zone 9 ... Bit 7 = Zone 16 // ... // alarmZones[7] and alarmZonesChanged[7]: Bit 0 = Zone 57 ... Bit 7 = Zone 64 if (panelData[panelByte] >= 0x09 && panelData[panelByte] <= 0x28) { alarm[partitionIndex] = true; if (alarm[partitionIndex] != previousAlarm[partitionIndex]) { previousAlarm[partitionIndex] = alarm[partitionIndex]; alarmChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } entryDelay[partitionIndex] = false; if (entryDelay[partitionIndex] != previousEntryDelay[partitionIndex]) { previousEntryDelay[partitionIndex] = entryDelay[partitionIndex]; entryDelayChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } byte maxZones = dscZones * 8; if (maxZones > 32) maxZones = 32; for (byte zoneCount = 0; zoneCount < maxZones; zoneCount++) { if (panelData[panelByte] == 0x09 + zoneCount) { if (zoneCount < 8) { bitWrite(alarmZones[0], zoneCount, 1); if (bitRead(previousAlarmZones[0], zoneCount) != 1) { bitWrite(previousAlarmZones[0], zoneCount, 1); bitWrite(alarmZonesChanged[0], zoneCount, 1); alarmZonesStatusChanged = true; if (!pauseStatus) statusChanged = true; } } else if (zoneCount >= 8 && zoneCount < 16) { bitWrite(alarmZones[1], (zoneCount - 8), 1); if (bitRead(previousAlarmZones[1], (zoneCount - 8)) != 1) { bitWrite(previousAlarmZones[1], (zoneCount - 8), 1); bitWrite(alarmZonesChanged[1], (zoneCount - 8), 1); alarmZonesStatusChanged = true; if (!pauseStatus) statusChanged = true; } } else if (zoneCount >= 16 && zoneCount < 24) { bitWrite(alarmZones[2], (zoneCount - 16), 1); if (bitRead(previousAlarmZones[2], (zoneCount - 16)) != 1) { bitWrite(previousAlarmZones[2], (zoneCount - 16), 1); bitWrite(alarmZonesChanged[2], (zoneCount - 16), 1); alarmZonesStatusChanged = true; if (!pauseStatus) statusChanged = true; } } else if (zoneCount >= 24 && zoneCount < 32) { bitWrite(alarmZones[3], (zoneCount - 24), 1); if (bitRead(previousAlarmZones[3], (zoneCount - 24)) != 1) { bitWrite(previousAlarmZones[3], (zoneCount - 24), 1); bitWrite(alarmZonesChanged[3], (zoneCount - 24), 1); alarmZonesStatusChanged = true; if (!pauseStatus) statusChanged = true; } } } } return; } // Zone alarm restored, zones 1-32 // Zone alarm status is stored using 1 bit per zone in alarmZones[] and alarmZonesChanged[]: // alarmZones[0] and alarmZonesChanged[0]: Bit 0 = Zone 1 ... Bit 7 = Zone 8 // alarmZones[1] and alarmZonesChanged[1]: Bit 0 = Zone 9 ... Bit 7 = Zone 16 // ... // alarmZones[7] and alarmZonesChanged[7]: Bit 0 = Zone 57 ... Bit 7 = Zone 64 if (panelData[panelByte] >= 0x29 && panelData[panelByte] <= 0x48) { byte maxZones = dscZones * 8; if (maxZones > 32) maxZones = 32; for (byte zoneCount = 0; zoneCount < maxZones; zoneCount++) { if (panelData[panelByte] == 0x29 + zoneCount) { if (zoneCount < 8) { bitWrite(alarmZones[0], zoneCount, 0); if (bitRead(previousAlarmZones[0], zoneCount) != 0) { bitWrite(previousAlarmZones[0], zoneCount, 0); bitWrite(alarmZonesChanged[0], zoneCount, 1); alarmZonesStatusChanged = true; if (!pauseStatus) statusChanged = true; } } else if (zoneCount >= 8 && zoneCount < 16) { bitWrite(alarmZones[1], (zoneCount - 8), 0); if (bitRead(previousAlarmZones[1], (zoneCount - 8)) != 0) { bitWrite(previousAlarmZones[1], (zoneCount - 8), 0); bitWrite(alarmZonesChanged[1], (zoneCount - 8), 1); alarmZonesStatusChanged = true; if (!pauseStatus) statusChanged = true; } } else if (zoneCount >= 16 && zoneCount < 24) { bitWrite(alarmZones[2], (zoneCount - 16), 0); if (bitRead(previousAlarmZones[2], (zoneCount - 16)) != 0) { bitWrite(previousAlarmZones[2], (zoneCount - 16), 0); bitWrite(alarmZonesChanged[2], (zoneCount - 16), 1); alarmZonesStatusChanged = true; if (!pauseStatus) statusChanged = true; } } else if (zoneCount >= 24 && zoneCount < 32) { bitWrite(alarmZones[3], (zoneCount - 24), 0); if (bitRead(previousAlarmZones[3], (zoneCount - 24)) != 0) { bitWrite(previousAlarmZones[3], (zoneCount - 24), 0); bitWrite(alarmZonesChanged[3], (zoneCount - 24), 1); alarmZonesStatusChanged = true; if (!pauseStatus) statusChanged = true; } } } } return; } // Armed by access code if (panelData[panelByte] >= 0x99 && panelData[panelByte] <= 0xBD) { accessCode[partitionIndex] = panelData[panelByte] - 0x98; if (accessCode[partitionIndex] >= 35) accessCode[partitionIndex] += 5; if (accessCode[partitionIndex] != previousAccessCode[partitionIndex]) { previousAccessCode[partitionIndex] = accessCode[partitionIndex]; accessCodeChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } return; } // Disarmed by access code if (panelData[panelByte] >= 0xC0 && panelData[panelByte] <= 0xE4) { accessCode[partitionIndex] = panelData[panelByte] - 0xBF; if (accessCode[partitionIndex] >= 35) accessCode[partitionIndex] += 5; if (accessCode[partitionIndex] != previousAccessCode[partitionIndex]) { previousAccessCode[partitionIndex] = accessCode[partitionIndex]; accessCodeChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } return; } } void dscKeybusInterface::processPanelStatus2(byte partition, byte panelByte) { if (partition == 0 || partition > dscPartitions) return; byte partitionIndex = partition - 1; // Armed: stay and Armed: away if (panelData[panelByte] == 0x9A || panelData[panelByte] == 0x9B) { if (panelData[panelByte] == 0x9A) { armedStay[partitionIndex] = true; armedAway[partitionIndex] = false; } else if (panelData[panelByte] == 0x9B) { armedStay[partitionIndex] = false; armedAway[partitionIndex] = true; } armed[partitionIndex] = true; if (armed[partitionIndex] != previousArmed[partitionIndex] || armedStay[partitionIndex] != previousArmedStay[partitionIndex]) { previousArmed[partitionIndex] = armed[partitionIndex]; previousArmedStay[partitionIndex] = armedStay[partitionIndex]; armedChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } exitDelay[partitionIndex] = false; if (exitDelay[partitionIndex] != previousExitDelay[partitionIndex]) { previousExitDelay[partitionIndex] = exitDelay[partitionIndex]; exitDelayChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } exitState[partitionIndex] = 0; ready[partitionIndex] = false; if (ready[partitionIndex] != previousReady[partitionIndex]) { previousReady[partitionIndex] = ready[partitionIndex]; readyChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } return; } if (panelData[panelByte] == 0xA5) { switch (panelData[panelByte]) { // Activate stay/away zones case 0x99: { armed[partitionIndex] = true; armedAway[partitionIndex] = true; armedStay[partitionIndex] = false; armedChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; return; } // Armed with no entry delay case 0x9C: { noEntryDelay[partitionIndex] = true; ready[partitionIndex] = false; if (ready[partitionIndex] != previousReady[partitionIndex]) { previousReady[partitionIndex] = ready[partitionIndex]; readyChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } return; } } } } void dscKeybusInterface::processPanelStatus4(byte partition, byte panelByte) { if (partition == 0 || partition > dscPartitions) return; byte partitionIndex = partition - 1; // Zone alarm, zones 33-64 // Zone alarm status is stored using 1 bit per zone in alarmZones[] and alarmZonesChanged[]: // alarmZones[0] and alarmZonesChanged[0]: Bit 0 = Zone 1 ... Bit 7 = Zone 8 // alarmZones[1] and alarmZonesChanged[1]: Bit 0 = Zone 9 ... Bit 7 = Zone 16 // ... // alarmZones[7] and alarmZonesChanged[7]: Bit 0 = Zone 57 ... Bit 7 = Zone 64 if (panelData[panelByte] <= 0x1F) { alarmZonesStatusChanged = true; alarm[partitionIndex] = true; if (alarm[partitionIndex] != previousAlarm[partitionIndex]) { previousAlarm[partitionIndex] = alarm[partitionIndex]; alarmChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } entryDelay[partitionIndex] = false; if (entryDelay[partitionIndex] != previousEntryDelay[partitionIndex]) { previousEntryDelay[partitionIndex] = entryDelay[partitionIndex]; entryDelayChanged[partitionIndex] = true; if (!pauseStatus) statusChanged = true; } byte maxZones = dscZones * 8; if (maxZones > 32) maxZones -= 32; else return; for (byte zoneCount = 0; zoneCount < maxZones; zoneCount++) { if (panelData[panelByte] == zoneCount) { if (zoneCount < 8) { bitWrite(alarmZones[4], zoneCount, 1); bitWrite(alarmZonesChanged[4], zoneCount, 1); if (!pauseStatus) statusChanged = true; } else if (zoneCount >= 8 && zoneCount < 16) { bitWrite(alarmZones[5], (zoneCount - 8), 1); bitWrite(alarmZonesChanged[5], (zoneCount - 8), 1); if (!pauseStatus) statusChanged = true; } else if (zoneCount >= 16 && zoneCount < 24) { bitWrite(alarmZones[6], (zoneCount - 16), 1); bitWrite(alarmZonesChanged[6], (zoneCount - 16), 1); if (!pauseStatus) statusChanged = true; } else if (zoneCount >= 24 && zoneCount < 32) { bitWrite(alarmZones[7], (zoneCount - 24), 1); bitWrite(alarmZonesChanged[7], (zoneCount - 24), 1); if (!pauseStatus) statusChanged = true; } } } return; } // Zone alarm restored, zones 33-64 // Zone alarm status is stored using 1 bit per zone in alarmZones[] and alarmZonesChanged[]: // alarmZones[0] and alarmZonesChanged[0]: Bit 0 = Zone 1 ... Bit 7 = Zone 8 // alarmZones[1] and alarmZonesChanged[1]: Bit 0 = Zone 9 ... Bit 7 = Zone 16 // ... // alarmZones[7] and alarmZonesChanged[7]: Bit 0 = Zone 57 ... Bit 7 = Zone 64 if (panelData[panelByte] >= 0x20 && panelData[panelByte] <= 0x3F) { alarmZonesStatusChanged = true; byte maxZones = dscZones * 8; if (maxZones > 32) maxZones -= 32; else return; for (byte zoneCount = 0; zoneCount < maxZones; zoneCount++) { if (panelData[panelByte] == 0x20 + zoneCount) { if (zoneCount < 8) { bitWrite(alarmZones[4], zoneCount, 0); bitWrite(alarmZonesChanged[4], zoneCount, 1); if (!pauseStatus) statusChanged = true; } else if (zoneCount >= 8 && zoneCount < 16) { bitWrite(alarmZones[5], (zoneCount - 8), 0); bitWrite(alarmZonesChanged[5], (zoneCount - 8), 1); if (!pauseStatus) statusChanged = true; } else if (zoneCount >= 16 && zoneCount < 24) { bitWrite(alarmZones[6], (zoneCount - 16), 0); bitWrite(alarmZonesChanged[6], (zoneCount - 16), 1); if (!pauseStatus) statusChanged = true; } else if (zoneCount >= 24 && zoneCount < 32) { bitWrite(alarmZones[7], (zoneCount - 24), 0); bitWrite(alarmZonesChanged[7], (zoneCount - 24), 1); if (!pauseStatus) statusChanged = true; } } } return; } } // Processes zones 33-64 status void dscKeybusInterface::processPanel_0xE6() { if (!validCRC()) return; switch (panelData[2]) { case 0x09: processPanel_0xE6_0x09(); return; case 0x0B: processPanel_0xE6_0x0B(); return; case 0x0D: processPanel_0xE6_0x0D(); return; case 0x0F: processPanel_0xE6_0x0F(); return; } } // Open zones 33-40 status is stored in openZones[4] and openZonesChanged[4]: Bit 0 = Zone 33 ... Bit 7 = Zone 40 void dscKeybusInterface::processPanel_0xE6_0x09() { if (dscZones > 4) { openZones[4] = panelData[3]; byte zonesChanged = openZones[4] ^ previousOpenZones[4]; if (zonesChanged != 0) { previousOpenZones[4] = openZones[4]; openZonesStatusChanged = true; if (!pauseStatus) statusChanged = true; for (byte zoneBit = 0; zoneBit < 8; zoneBit++) { if (bitRead(zonesChanged, zoneBit)) { bitWrite(openZonesChanged[4], zoneBit, 1); if (bitRead(panelData[3], zoneBit)) bitWrite(openZones[4], zoneBit, 1); else bitWrite(openZones[4], zoneBit, 0); } } } } } // Open zones 41-48 status is stored in openZones[5] and openZonesChanged[5]: Bit 0 = Zone 41 ... Bit 7 = Zone 48 void dscKeybusInterface::processPanel_0xE6_0x0B() { if (dscZones > 5) { openZones[5] = panelData[3]; byte zonesChanged = openZones[5] ^ previousOpenZones[5]; if (zonesChanged != 0) { previousOpenZones[5] = openZones[5]; openZonesStatusChanged = true; if (!pauseStatus) statusChanged = true; for (byte zoneBit = 0; zoneBit < 8; zoneBit++) { if (bitRead(zonesChanged, zoneBit)) { bitWrite(openZonesChanged[5], zoneBit, 1); if (bitRead(panelData[3], zoneBit)) bitWrite(openZones[5], zoneBit, 1); else bitWrite(openZones[5], zoneBit, 0); } } } } } // Open zones 49-56 status is stored in openZones[6] and openZonesChanged[6]: Bit 0 = Zone 49 ... Bit 7 = Zone 56 void dscKeybusInterface::processPanel_0xE6_0x0D() { if (dscZones > 6) { openZones[6] = panelData[3]; byte zonesChanged = openZones[6] ^ previousOpenZones[6]; if (zonesChanged != 0) { previousOpenZones[6] = openZones[6]; openZonesStatusChanged = true; if (!pauseStatus) statusChanged = true; for (byte zoneBit = 0; zoneBit < 8; zoneBit++) { if (bitRead(zonesChanged, zoneBit)) { bitWrite(openZonesChanged[6], zoneBit, 1); if (bitRead(panelData[3], zoneBit)) bitWrite(openZones[6], zoneBit, 1); else bitWrite(openZones[6], zoneBit, 0); } } } } } // Open zones 57-64 status is stored in openZones[7] and openZonesChanged[7]: Bit 0 = Zone 57 ... Bit 7 = Zone 64 void dscKeybusInterface::processPanel_0xE6_0x0F() { if (dscZones > 7) { openZones[7] = panelData[3]; byte zonesChanged = openZones[7] ^ previousOpenZones[7]; if (zonesChanged != 0) { previousOpenZones[7] = openZones[7]; openZonesStatusChanged = true; if (!pauseStatus) statusChanged = true; for (byte zoneBit = 0; zoneBit < 8; zoneBit++) { if (bitRead(zonesChanged, zoneBit)) { bitWrite(openZonesChanged[7], zoneBit, 1); if (bitRead(panelData[3], zoneBit)) bitWrite(openZones[7], zoneBit, 1); else bitWrite(openZones[7], zoneBit, 0); } } } } }
[ "joogt1@outlook.com" ]
joogt1@outlook.com
1dfe2111bdac418868dbf52fa117f4761612d296
3ed0c4be5a53506d54654412c567617c7377d008
/kissnet.cpp
2ebbef01f7f98d442e7bf1fe440dcdf106e4f2f2
[]
no_license
zackgomez/kissnet
e9c8cf85fad91667ddef29bffaa2e1df4a869865
a608322c45e185f8a1b968ad8cde494323aa8ad0
refs/heads/master
2020-04-10T04:33:16.320016
2011-04-26T05:35:23
2011-04-26T05:35:23
14,060,889
0
0
null
null
null
null
UTF-8
C++
false
false
5,103
cpp
#include "kissnet.h" #include <iostream> #include <cstring> // for strerror #include <cstdlib> #include <errno.h> #ifndef _MSC_VER #include <sys/socket.h> #include <sys/types.h> #include <sys/select.h> #include <sys/time.h> #include <netdb.h> #else #include <WinSock2.h> #include <ws2tcpip.h> #endif namespace kissnet { // ----------------------------------------------------------------------------- // Utility Functions // ----------------------------------------------------------------------------- void init_networking() { #ifdef _MSC_VER // Initialize Winsock WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) throw socket_exception("WSAStartup failed\n"); #endif } // ----------------------------------------------------------------------------- // Socket Exception // ----------------------------------------------------------------------------- socket_exception::socket_exception(const std::string& what, bool include_syserr) : msg(what) { if (include_syserr) { msg += ": "; msg += strerror(errno); } } socket_exception::~socket_exception() throw() { // empty } const char * socket_exception::what() const throw() { return msg.c_str(); } // ----------------------------------------------------------------------------- tcp_socket_ptr tcp_socket::create() { tcp_socket_ptr ret(new tcp_socket()); return ret; } tcp_socket_ptr tcp_socket::create(int sockfd) { tcp_socket_ptr ret(new tcp_socket(sockfd)); return ret; } tcp_socket::tcp_socket() { // Create socket // TODO move this elsewhere so that it doesn't have to be AF_INET sock = socket(AF_INET, SOCK_STREAM, 0); } tcp_socket::tcp_socket(int sock_fd) : sock(sock_fd) { } tcp_socket::~tcp_socket() { // Make sure we clean up close(); } void tcp_socket::connect(const std::string &addr, const std::string& port) { struct addrinfo *res = NULL, hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; getaddrinfo(addr.c_str(), port.c_str(), &hints, &res); if (::connect(sock, res->ai_addr, res->ai_addrlen) < 0) throw socket_exception("Unable to connect", true); } void tcp_socket::close() { #ifdef _MSC_VER ::closesocket(sock); #else ::close(sock); #endif } void tcp_socket::listen(const std::string &port, int backlog) { // set reuseaddr char yes = 1; if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) < 0) { throw socket_exception("Unable to set reuseaddr", true); } // Fill structs struct addrinfo *res, hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; if (::getaddrinfo(NULL, port.c_str(), &hints, &res) < 0) throw socket_exception("Unable to getaddrinfo", false); // Bind to local port if (::bind(sock, res->ai_addr, res->ai_addrlen) < 0) throw socket_exception("Unable to bind", true); // Now listen if (::listen(sock, backlog) < 0) throw socket_exception("Unable to listen", true); } tcp_socket_ptr tcp_socket::accept() { int newsock; if ((newsock = ::accept(sock, NULL, NULL)) < 0) throw socket_exception("Unable to accept", true); return create(newsock); } int tcp_socket::send(const std::string& data) { int bytes_sent; if ((bytes_sent = ::send(sock, data.c_str(), data.size(), 0)) < 0) throw socket_exception("Unable to send", true); return bytes_sent; } int tcp_socket::recv(char *buffer, int buffer_len) { int bytes_received; if ((bytes_received = ::recv(sock, buffer, buffer_len, 0)) < 0) throw socket_exception("Unable to recv", true); return bytes_received; } int tcp_socket::getSocket() const { return sock; } bool tcp_socket::operator==(const tcp_socket &rhs) const { return sock == rhs.sock; } // ----------------------------------------------------------------------------- // socket_set definitions // ----------------------------------------------------------------------------- socket_set::socket_set() : socks() { // Empty } socket_set::~socket_set() { // Empty } void socket_set::add_socket(tcp_socket *sock) { socks.push_back(sock); } void socket_set::remove_socket(tcp_socket *sock) { socks.remove(sock); } std::vector<tcp_socket*> socket_set::poll_sockets() { fd_set rset; FD_ZERO(&rset); int maxfd = -1; for (std::list<tcp_socket*>::iterator it = socks.begin(); it != socks.end(); it++) { int curfd = (*it)->getSocket(); FD_SET(curfd, &rset); if (curfd > maxfd) maxfd = curfd; } ::select(maxfd + 1, &rset, NULL, NULL, NULL); std::vector<tcp_socket*> ret; for (std::list<tcp_socket*>::iterator it = socks.begin(); it != socks.end(); it++) { int curfd = (*it)->getSocket(); if (FD_ISSET(curfd, &rset)) ret.push_back(*it); } return ret; } // End namespace kissnet };
[ "zacharyg@caltech.edu" ]
zacharyg@caltech.edu
b77aef920e4b804f94d3407bf2a7736d538831f8
fc38a55144a0ad33bd94301e2d06abd65bd2da3c
/thirdparty/cgal/CGAL-4.13/include/CGAL/Hilbert_sort_middle_base.h
0d8901b15d5c7a0321583272551c1f0de4014dc3
[ "LGPL-2.0-or-later", "LGPL-3.0-or-later", "GPL-1.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-commercial-license", "MIT", "LicenseRef-scancode-free-unknown", "LGPL-3.0-only", "GPL-3.0-only", "LGPL-2.1-or-later", "LicenseRef-scancode-proprietary-license", "Licens...
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
1,288
h
// Copyright (c) 2011 INRIA Sophia-Antipolis (France). // 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. // // $URL$ // $Id$ // SPDX-License-Identifier: LGPL-3.0+ // // Author(s) : Olivier Devillers #ifndef CGAL_HILBERT_SORT_MIDDLE_BASE_H #define CGAL_HILBERT_SORT_MIDDLE_BASE_H #include <CGAL/config.h> #include <algorithm> namespace CGAL { namespace internal { template <class RandomAccessIterator, class Cmp> RandomAccessIterator fixed_hilbert_split (RandomAccessIterator begin, RandomAccessIterator end, Cmp cmp = Cmp ()) { if (begin >= end) return begin; return std::partition (begin, end, cmp); } } } // namespace CGAL #endif//CGAL_HILBERT_SORT_MIDDLE_BASE_H
[ "huxingyi@msn.com" ]
huxingyi@msn.com
b0694662cfc45697803bbe11fece661bdefd2569
8c2d730129120da873db8db5a2c3418767946541
/include/plusres/result.hpp
30d457e61e0c825df4525d77ad18f111caea7e02
[ "BSL-1.0" ]
permissive
kkAyataka/plusres
3e44e8b19fe05ff4530e140487274ab8ebcf463b
56a837b7cf08847c0564e55ccb337364abd9806e
refs/heads/main
2023-03-04T20:49:11.808286
2021-02-06T02:58:01
2021-02-06T02:58:01
334,339,469
0
0
null
null
null
null
UTF-8
C++
false
false
2,031
hpp
// Copyright (C) 2020 kkAyataka // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef PLUSRES_RESULT_HPP__ #define PLUSRES_RESULT_HPP__ #include "error.hpp" namespace plusres { /** Base class of the Result */ template<typename V, typename E> class ResultBase { public: ResultBase( const V & v, const E & e ) noexcept : value_(v), error_(e) { } ResultBase( const V && v, const E && e ) noexcept : value_(std::move(v)), error_(std::move(e)) { } virtual ~ResultBase() {} public: inline bool ok() const { return error_.ok(); } inline bool failed() const { return error_.failed(); } /** @throws E */ inline operator V() const noexcept(false) { if (error_) { throw error_; } else { return value_; } } /** @throws E */ inline void throw_error() const noexcept(false) { if (error_) { throw error_; } } inline V no_throw(const V & v) const noexcept { if (error_) { return v; } else { return value_; } } public: inline const E & error() const { return error_; } inline const V & value() const { return value_; } inline V & value() { return value_; } private: V value_; E error_; }; /** Default empty value class */ struct Void { }; /** * Default Result class with plusres::Error */ template<typename V = Void> class Result : public ResultBase<V, plusres::Error> { public: Result(const V & v) noexcept : ResultBase<V, Error>(v, Error(plusres::Succeeded)) {} Result(const V && v) noexcept : ResultBase<V, Error>(std::move(v), Error(plusres::Succeeded)) {} Result(const Error & e) noexcept : ResultBase<V, Error>(V(), e) {} virtual ~Result() {} }; } // namespace plusres #endif // PLUSRES_RESULT_HPP__
[ "kk.ayataka@gmail.com" ]
kk.ayataka@gmail.com
c4d6875bd8c095d96e36960da503444dbbed3d8e
3a04465af3de9ecc58711140a825947bb603df3c
/skse64/NiObjects.h
9a964fd51f6866f0927d140c0bc3152bd55b538c
[ "MIT" ]
permissive
clayne/Undaunted
59d77ec265209cf3d0ffc3b79eebac6ac18e81b4
76515249be217e865eae05b1656b3aeb32283fdc
refs/heads/master
2023-01-12T08:19:59.253760
2022-11-25T07:55:49
2022-11-25T07:55:49
279,496,032
0
0
MIT
2020-07-14T05:57:15
2020-07-14T05:57:15
null
UTF-8
C++
false
false
10,725
h
#pragma once #include "skse64/NiRTTI.h" #include "skse64/NiTypes.h" #include "skse64_common/Utilities.h" #include "skse64/GameTypes.h" // NiRefObject/NiObject and important children // generally other children should go in other files // especially if they can be grouped class NiCloningProcess; class NiStream; class NiObjectGroup; class NiExtraData; class NiTimeController; class NiNode; class NiGeometry; class BSGeometry; class NiRenderedTexture; class NiSwitchNode; class NiTriBasedGeom; class NiTriShape; class NiTriStrips; class BSSegmentedTriShape; class NiRenderTargetGroup; class NiProperty; class NiSourceTexture; class BSTriShape; class TESObjectCELL; class TESModelTri; class BSFaceGenMorphData; class TESObjectREFR; extern RelocPtr<float> g_worldToCamMatrix; extern RelocPtr<NiRect<float>> g_viewPort; typedef bool (* _WorldPtToScreenPt3_Internal)(float * worldToCamMatrix, NiRect<float> * port, NiPoint3 * p_in, float * x_out, float * y_out, float * z_out, float zeroTolerance); extern RelocAddr<_WorldPtToScreenPt3_Internal> WorldPtToScreenPt3_Internal; typedef void * (*_NiAllocate)(size_t size); extern RelocAddr<_NiAllocate> NiAllocate; typedef void(*_NiFree)(void * ptr); extern RelocAddr<_NiFree> NiFree; // 10 class NiRefObject { public: NiRefObject(); virtual ~NiRefObject(); virtual void DeleteThis(void); // calls virtual dtor void IncRef(void); void DecRef(void); bool Release(void); // void ** _vtbl; // 00 volatile SInt32 m_uiRefCount; // 08 UInt32 pad0C; // 0C }; // ### not all of this is verified, I'm just assuming that little has changed from other // ### games using previous versions of NetImmerse that have released .pdb files for reference // 10 class NiObject : public NiRefObject { public: // standard NetImmerse virtual NiRTTI* GetRTTI(void); // then a bunch of attempts to avoid dynamic_cast? // unverified, do not use virtual NiNode * GetAsNiNode(void); virtual NiSwitchNode * GetAsNiSwitchNode(void); virtual void * Unk_05(void); virtual UInt32 Unk_06(void); virtual BSGeometry * GetAsBSGeometry(void); virtual void * Unk_08(void); virtual BSTriShape * GetAsBSTriShape(void); virtual void * Unk_0A(void); virtual void * Unk_0B(void); virtual void * Unk_0C(void); virtual NiGeometry * GetAsNiGeometry(void); virtual NiTriBasedGeom * GetAsNiTriBasedGeom(void); virtual NiTriShape * GetAsNiTriShape(void); virtual void * Unk_10(void); virtual void * Unk_11(void); virtual void * Unk_12(void); // SE: these 4 were added virtual UInt32 Unk_13(void); virtual UInt32 Unk_14(void); virtual UInt32 Unk_15(void); virtual UInt32 Unk_16(void); // then back to NetImmerse virtual NiObject * CreateClone(NiCloningProcess cloner); virtual void LoadBinary(NiStream * stream); virtual void LinkObject(NiStream * stream); virtual bool RegisterStreamables(NiStream * stream); virtual void SaveBinary(NiStream * stream); virtual bool IsEqual(NiObject * object); // viewer appears to be disabled sadly // why did you do that? it was really useful for figuring out class data // and it's not like it totally bloated up the executa... er never mind virtual void ProcessClone(NiCloningProcess * cloner); virtual void PostLinkObject(NiStream * stream); virtual bool StreamCanSkip(void); virtual const /*NiRTTI*/void * GetStreamableRTTI(void) const; virtual UInt32 GetBlockAllocationSize(void) const; virtual NiObjectGroup * GetGroup(void) const; virtual void SetGroup(NiObjectGroup * group); // begin bethesda extensions? possibly just stuff we can't match up virtual UInt32 Unk_20(void); // SE: function 24 MEMBER_FN_PREFIX(NiObject); DEFINE_MEMBER_FN(DeepCopy, NiStream *, 0x00C8CA90, NiObject ** result); }; STATIC_ASSERT(sizeof(NiObject) == 0x10); // 30 class NiObjectNET : public NiObject { public: const char * m_name; // 10 NiTimeController * m_controller; // 18 next pointer at +0x30 NiExtraData ** m_extraData; // 20 extra data UInt16 m_extraDataLen; // 28 max valid entry UInt16 m_extraDataCapacity; // 2A array len UInt32 pad2C; // UNTESTED void AddExtraData(NiExtraData * extraData); bool RemoveExtraData(NiExtraData * extraData); SInt32 GetIndexOf(NiExtraData * extraData); NiExtraData * GetExtraData(BSFixedString name); }; STATIC_ASSERT(sizeof(NiObjectNET) == 0x30); // 110 class NiAVObject : public NiObjectNET { public: enum { kFlag_SelectiveUpdate = 0x00000002, kFlag_UpdatePropertyControllers = 0x00000004, kFlag_SelectiveUpdateRigid = 0x00000010, kFlag_OverrideSelectiveTransforms = 0x00000080, }; struct ControllerUpdateContext { enum { kDirty = 1 << 0, }; float delta; UInt32 flags; }; virtual void UpdateControllers(ControllerUpdateContext * ctx); // calls controller vtbl+0x8C virtual void UpdateNodeBound(ControllerUpdateContext * ctx); // SE: one of these 4 functions was deleted. Until figuring out which one, assuming it was Unk_26 virtual void ApplyTransform(NiMatrix33 * mtx, NiPoint3 * translate, bool postTransform); virtual void SetPropertyState(NiProperty * prop); virtual void Unk_25(UInt32 arg0); // SE: function 29 //virtual void Unk_26(UInt32 arg0); virtual NiAVObject * GetObjectByName(const char ** name); // BSFixedString? alternatively BSFixedString is a typedef of a netimmerse type virtual void SetSelectiveUpdateFlags(bool * selectiveUpdate, bool selectiveUpdateTransforms, bool * rigid); virtual void UpdateDownwardPass(ControllerUpdateContext * ctx, void *unk1); // SE: changed unk to void* virtual void UpdateSelectedDownwardPass(ControllerUpdateContext * ctx, void *unk1); // SE: changed unk to void* virtual void UpdateRigidDownwardPass(ControllerUpdateContext * ctx, void *unk1); // SE: changed unk to void* virtual void UpdateWorldBound(void); virtual void UpdateWorldData(ControllerUpdateContext * ctx); // SE: function 30 (vtable+0x180) virtual void UpdateNoControllers(ControllerUpdateContext * ctx); virtual void UpdateDownwardPassTempParent(NiNode * parent, ControllerUpdateContext * ctx); virtual void Unk_30(void); // calls virtual function on parent - SE: function 33 // SE: one of these functions was deleted. Doesn't matter which, they are unks, assuming Unk_32. virtual void Unk_31(UInt32 arg0); // SE: function 34 //virtual void Unk_32(UInt32 arg0); NiNode * m_parent; // 30 UInt32 unk038; // 38 - New in SE, init'd to FFFFFFFF UInt32 pad03C; // 3C NiAVObject * unk040; // 40 NiTransform m_localTransform; // 48 NiTransform m_worldTransform; // 7C NiTransform m_oldWorldTransform; // B0 - SE: this one is new float unkE4; // E4 float unkE8; // E8 float unkEC; // EC float unkF0; // F0 UInt32 m_flags; // F4 - bitfield TESObjectREFR* m_owner; // F8 float unk100; // 100 - New in SE? init's to 1.0 UInt32 unk104; // 104 - New in SE? init'd to 0 UInt8 unk108; // 108 UInt8 unk109; // 109 - bitfield UInt8 pad10A[6]; // 10A MEMBER_FN_PREFIX(NiAVObject); // A5B2FC7D42E72BA4F6A679BAC0BAE17C12A4AFE1+E3 DEFINE_MEMBER_FN(UpdateNode, void, 0x00C90980, ControllerUpdateContext * ctx); }; STATIC_ASSERT(offsetof(NiAVObject, m_localTransform) == 0x48); STATIC_ASSERT(offsetof(NiAVObject, m_worldTransform) == 0x7C); STATIC_ASSERT(sizeof(NiAVObject) == 0x110); MAKE_NI_POINTER(NiAVObject); // SE: TODO this class needs update, if it still exists // Bethesda class, unknown name class BSRenderTargetGroup : public NiObject { public: virtual ~BSRenderTargetGroup(); NiRenderTargetGroup * unk08[6]; // 08 UInt32 unk20; // 20 UInt32 unk24; // 24 UInt32 unk28; // 28 UInt32 unk2C; // 2C inited to FFFFFFFF NiRenderedTexture * renderedTexture[4]; // 30 }; // 20 class BSFaceGenModel : public NiRefObject { public: struct Data10 { UInt32 unk00; // 00 UInt32 pad04; // 04 NiAVObject * unk08; // 08 NiAVObject * unk10; // 10 void * unk18; // 18 BSFaceGenMorphData * unk20; // 20 }; Data10 * unk10; // 10 UInt32 unk18; // 18 UInt32 pad1C; // 1C MEMBER_FN_PREFIX(BSFaceGenModel); DEFINE_MEMBER_FN(ctor, void, 0x003EE300); DEFINE_MEMBER_FN(CopyFrom, void, 0x003EE3A0, BSFaceGenModel * other); DEFINE_MEMBER_FN(SetModelData, bool, 0x003EEB20, const char * meshPath, void * unk1, UInt8 unk2); DEFINE_MEMBER_FN(ApplyMorph, UInt8, 0x003EE980, BSFixedString * morphName, TESModelTri * triModel, NiAVObject ** headNode, float relative, UInt8 unk1); DEFINE_MEMBER_FN(ApplyRaceMorph, UInt8, 0x003EE830, BSFixedString* morphName, TESModelTri* triModel, NiAVObject** headNode, float relative, UInt8 unk1); }; // 18 class BSFaceGenMorphData : public NiRefObject { public: void * unk10; // 10 MEMBER_FN_PREFIX(BSFaceGenMorphData); DEFINE_MEMBER_FN(ApplyMorph, UInt8, 0x003F1820, const char ** morphName, NiAVObject * faceTrishape, float relative, UInt8 unk2); }; // 20 class BSFaceGenModelMap : public NiRefObject { public: struct Entry { BSFaceGenModel * unk00; // 00 UInt64 unk08; // 08 }; Entry unk10; // 10 }; // A0 class LoadedAreaBound : public NiRefObject { public: virtual ~LoadedAreaBound(); UInt64 unk10[6]; // 10 UInt64 unk40; // 40 TESObjectCELL * cell; // 48 UInt32 unk50; UInt32 unk54; UInt32 unk58; UInt32 unk5C; void* unk60; // 60 - inited 0xDEADBEEF UInt64 unk68; UInt64 unk70; NiPoint3 boundsMax; // 78 NiPoint3 boundsMin; // 84 float unk90; // 90 - init'd from constructor arg (xmm1) float unk94; // 94 - init'd from constructor arg (xmm2) float unk98; // 98 - init'd from constructor arg (xmm3) float unk9C; // 9C - init'd from constructor last arg (stack) }; STATIC_ASSERT(sizeof(LoadedAreaBound) == 0xA0); STATIC_ASSERT(offsetof(LoadedAreaBound, boundsMax) == 0x78); // 68 class BSFaceGenMorphDataHead : public BSFaceGenMorphData { public: UInt8 unk18[0x50 - 0x18]; // 18 - 18-4A -> init'd to FF UInt64 unk50; UInt64 unk58; UInt32 unk60; }; STATIC_ASSERT(sizeof(BSFaceGenMorphDataHead) == 0x68); // 20 class BSFaceGenMorphDataHair : public BSFaceGenMorphData { public: UInt32 unk18; UInt32 pad; }; STATIC_ASSERT(sizeof(BSFaceGenMorphDataHair) == 0x20); // 188 class NiCamera : public NiAVObject { public: float m_aafWorldToCam[4][4]; // 110 NiFrustum m_frustum; // 150 float m_fMinNearPlaneDist; // 16C float m_fMaxFarNearRatio; // 170 NiRect<float> m_kPort; // 174 float m_fLODAdjust; // 184 bool WorldPtToScreenPt3(NiPoint3 * p_in, float * x_out, float * y_out, float * z_out, float zeroTolerance = 1e-5); }; STATIC_ASSERT(offsetof(NiCamera, m_frustum) == 0x150); STATIC_ASSERT(offsetof(NiCamera, m_fMinNearPlaneDist) == 0x16C); STATIC_ASSERT(offsetof(NiCamera, m_fLODAdjust) == 0x184);
[ "kaos.nyrb@gmail.com" ]
kaos.nyrb@gmail.com
cbb2bf53274bad041029a2d050e2d70e162b6fec
954f4e5cd07f55e80994fbd73ac1b4a98c212415
/main.cpp
a878636b61f118ef27b06761b5c8a633b7107e9f
[]
no_license
Tono2713/app_pilas_colas_listas_c-
c73898cc3e7af2466a42655f80011617d4893a5a
f0080180c65bef7e7f3cb3f7a2b2842b30967757
refs/heads/master
2021-07-16T08:00:41.012179
2019-10-30T18:28:57
2019-10-30T18:28:57
218,595,553
0
0
null
null
null
null
UTF-8
C++
false
false
3,057
cpp
using namespace std; #include<iostream> #include "Ensayos.h" #include "NodoEnsayos.h" #include "ListaDobleEnsayo.h" #include "Estudiante.h" #include "NodoEstudiantes.h" #include "PilaEstudiante.h" #include "Materias.h" #include "NodoMaterias.h" #include "colaMaterias.h" int main (int argc, char *argv[]) { colaMaterias *cola = new colaMaterias(); /*Ensayos Z; Estudiante Y; Materias X;*/ //variables clase ensayo string nombre=""; int cantH=0; //variables clase Estudiante //string nombreEstudiante=""; string sexo=""; //variables clase materias int codigo=0, codigoE=0; int opcion=0; do{ system("cls"); cout<<"***Menu***"<<endl <<"1. Insertar una materia "<<endl <<"2. Imprimir lista de materias "<<endl <<"3. Insertar un estudiante "<<endl <<"4. Imprimir lista de estudiantes de una materia"<<endl <<"5. Insertar un ensayo a un estudiante"<<endl <<"6. Imprimir lista de ensayos de un estudiante"<<endl <<"7. Imprimir todo"<<endl <<"8. Calcular y listar promedio de estudiantes"<<endl <<"0. Salir"<<endl <<"Presione el numero con la opcion que quiere utilizar"<<endl; cin>>opcion; switch(opcion){ case 1: cout<<"Digite el codigo de la materia. Redaccion: 123. Ortografia: 124. Caligrafia: 125"<<endl; cin>>codigo; cout<<"Digite el nombre de la materia. Redaccion, ortografia o caligrafia"<<endl; cin>>nombre; cola->poner(new NodoMaterias(new Materias(codigo, nombre))); cola->imprimir(); system("pause"); break; case 2: cola->imprimir(); system("pause"); break; case 3: cout<<"Digite el codigo de la materia a introducir estudiantes"<<endl; cin>>codigo; cout<<"Digite el codigo del estudiante"<<endl; cin>>codigoE; cout<<"Digite el nombre del estudiante"<<endl; cin>>nombre; cout<<"Digite el sexo del estudiante (F o M)"<<endl; cin>>sexo; sexo = toupper(sexo[0]); cola->apilarEstudiante(codigo,new NodoEstudiantes(new Estudiante(codigoE,nombre,sexo))); cola->imprimirMateriaEstudiante(); system("pause"); break; case 4: cout<<"Digite el codigo de la materia a imprimir listado de estudiantes"<<endl; cin>>codigo; cola->imprimirEstudantesMateria(codigo); system("pause"); break; case 5: cout<<"Digite el codigo del estudiante a insertar ensayo"<<endl; cin>>codigo; cout<<"Digite el nombre del enseyo"<<endl; cin>>nombre; cout<<"Digite la cantidad de hojas"<<endl; cin>>cantH; cola->apilarEnsayo(codigo, new NodoEnsayos(new Ensayos(nombre,cantH,0))); system("pause"); break; case 6: cout<<"Digite el codigo del estudiante a imprimir listado de ensayos"<<endl; cin>>codigo; cola->imprimirEnsayoEstudiante(codigo); system("pause"); break; case 7: cola->imprimirTodo(); system("pause"); break; case 8: cola->calcularListarPromedio(); system("pause"); break; default: break; } } while(opcion!=0); return 0; }
[ "Tono2713@gmail.com" ]
Tono2713@gmail.com
c309fe0eb7b0d6de5dc71c6e92ce4f2d23bb0288
407707d8e5065e162627164593e4b7f753adc6f7
/Test_2015_1_31/histogram1d.cpp
f53096070810463b78ad00bebc5b44d0765804c4
[]
no_license
Andromeda2333/ImageProcessing
5cf7ce1c9160bac4d15dfc0c83be0961af0e7962
8000384233dfe066dbe0b127ae7de43151e4c025
refs/heads/master
2020-05-04T19:28:13.522050
2015-10-22T17:03:49
2015-10-22T17:03:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
954
cpp
#include "histogram1d.h" Histogram1D::Histogram1D() { histSize[0]=256; hranges[0]=0; hranges[1]=255; ranges[0]=hranges; channels[0]=0; } Histogram1D::~Histogram1D() { } cv::MatND Histogram1D::getHistogram(const cv::Mat &image) { cv::MatND hist; cv::calcHist(&image,1,channels,cv::Mat(),hist,1,histSize,ranges); return hist; } cv::MatND Histogram1D::getHistogramImg(const cv::Mat &image) { cv::MatND hist=getHistogram(image); double maxVal=0; double minVal=0; cv::minMaxLoc(hist,&minVal,&maxVal,0,0); cv::Mat histImg(histSize[0],histSize[0],CV_8U,cv::Scalar(255)); int hpt=static_cast<int>(0.9*histSize[0]); for( int h = 0; h < histSize[0]; h++ ) { float binVal = hist.at<float>(h); int intensity = static_cast<int>(binVal*hpt/maxVal); cv::line(histImg,cv::Point(h,histSize[0]),cv::Point(h,histSize[0]-intensity),cv::Scalar::all(0)); } return histImg; }
[ "zcc136314853@hotmail.com" ]
zcc136314853@hotmail.com
f1b9942fc140aca0da272aaa90bc569d47ad54c0
09e691cd33d9eab57b903d717e8e65194aedcca7
/SDK/PUBG_Item_Ammo_300Magnum_classes.hpp
fa7d30daecc63663ddd854782b256c090ce5ecb5
[]
no_license
violarulan/PUBG-SDK
8a6ed46abe103147c772cd31cf1e07541a99e844
148a48829ef23355a2a6a3ecb286985677f4e274
refs/heads/master
2021-01-06T20:40:15.064387
2017-08-03T16:24:22
2017-08-03T16:24:22
99,541,605
1
0
null
2017-08-07T05:55:34
2017-08-07T05:55:34
null
UTF-8
C++
false
false
663
hpp
#pragma once // PLAYERUNKNOWN'S BATTLEGROUNDS (2.5.26) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace Classes { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Item_Ammo_300Magnum.Item_Ammo_300Magnum_C // 0x0000 (0x0198 - 0x0198) class UItem_Ammo_300Magnum_C : public UAmmoItem { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Item_Ammo_300Magnum.Item_Ammo_300Magnum_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "pubgsdk@gmail.com" ]
pubgsdk@gmail.com
071ac706a8735257c5d75c6256a03df737fe4d47
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir7941/dir22441/dir22442/dir26291/file26478.cpp
e73c85f392095aecad26bd179311061f9005650c
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
#ifndef file26478 #error "macro file26478 must be defined" #endif static const char* file26478String = "file26478";
[ "tgeng@google.com" ]
tgeng@google.com
7719f0c658f0637533540ded2059c5d6ce85a989
3e44c87bb77d39a91a865d8d8db18181f1b1effa
/LANQIAO/ALGO/ALGO-020.cpp
e22cc5abed0e6ff236a331949c16b0e85916186e
[]
no_license
kainzhang/kz-algo-cpp
e6386ec3d29104f21a15401ace96db869662afc8
12947152289802915a65c793687e6008b5f2cd76
refs/heads/master
2023-01-23T23:56:10.541532
2020-11-23T02:40:03
2020-11-23T02:40:03
247,682,344
0
0
null
null
null
null
UTF-8
C++
false
false
474
cpp
// // Created by LOKKA on 2020/4/12. // 求先序排列 #include <iostream> using namespace std; string in, post, pre = ""; void getPreorder(int root, int l, int r) { if (l > r) return; int i = r; while (post[root] != in[i]) i--; pre += post[root]; getPreorder(root - 1 + i - r, l, i - 1); getPreorder(root - 1, i + 1, r); } int main() { cin >> in >> post; getPreorder(post.length() - 1, 0, in.length() - 1); cout << pre; }
[ "luvwind@qq.com" ]
luvwind@qq.com
5260520b2acc2168bda52c2ac4b53bace027cb86
a09400aa22a27c7859030ec470b5ddee93e0fdf0
/stalkersoc/source/poltergeist_flame_thrower.cpp
0e0ce53971baf1f1fd84a829caf547fe3797595e
[]
no_license
BearIvan/Stalker
4f1af7a9d6fc5ed1597ff13bd4a34382e7fdaab1
c0008c5103049ce356793b37a9d5890a996eed23
refs/heads/master
2022-04-04T02:07:11.747666
2020-02-16T10:51:57
2020-02-16T10:51:57
160,668,112
1
1
null
null
null
null
WINDOWS-1251
C++
false
false
11,338
cpp
#include "StdAfx.h" #include "ai/monsters/poltergeist/poltergeist.h" #include "xrmessages.h" #include "ai_object_location.h" #include "level_graph.h" #include "level.h" #include "ai_space.h" #include "restricted_object.h" #include "actor.h" #include "ai/monsters/ai_monster_effector.h" CPolterFlame::CPolterFlame(CPoltergeist *polter) : inherited (polter) { } CPolterFlame::~CPolterFlame() { } void CPolterFlame::load(LPCSTR section) { inherited::load(section); m_sound.create (pSettings->r_string(section,"flame_sound"), st_Effect,SOUND_TYPE_WORLD); m_particles_prepare = pSettings->r_string(section,"flame_particles_prepare"); m_particles_fire = pSettings->r_string(section,"flame_particles_fire"); m_particles_stop = pSettings->r_string(section,"flame_particles_stop"); m_time_fire_delay = pSettings->r_u32(section,"flame_fire_time_delay"); m_time_fire_play = pSettings->r_u32(section,"flame_fire_time_play"); m_length = pSettings->r_float(section,"flame_length"); m_hit_value = pSettings->r_float(section,"flame_hit_value"); m_hit_delay = pSettings->r_u32(section,"flame_hit_delay"); m_count = pSettings->r_u32(section,"flames_count"); m_delay = pSettings->r_u32(section,"flames_delay"); m_min_flame_dist = pSettings->r_float(section,"flame_min_dist"); m_max_flame_dist = pSettings->r_float(section,"flame_max_dist"); m_min_flame_height = pSettings->r_float(section,"flame_min_height"); m_max_flame_height = pSettings->r_float(section,"flame_max_height"); m_pmt_aura_radius = pSettings->r_float(section,"flame_aura_radius"); //----------------------------------------------------------------------------------------- // Scanner m_scan_radius = pSettings->r_float(section,"flame_scan_radius"); read_delay (section,"flame_scan_delay_min_max",m_scan_delay_min, m_scan_delay_max); // load scan effector LPCSTR ppi_section = pSettings->r_string(section, "flame_scan_effector_section"); m_scan_effector_info.duality.h = pSettings->r_float(ppi_section,"duality_h"); m_scan_effector_info.duality.v = pSettings->r_float(ppi_section,"duality_v"); m_scan_effector_info.gray = pSettings->r_float(ppi_section,"gray"); m_scan_effector_info.blur = pSettings->r_float(ppi_section,"blur"); m_scan_effector_info.noise.intensity = pSettings->r_float(ppi_section,"noise_intensity"); m_scan_effector_info.noise.grain = pSettings->r_float(ppi_section,"noise_grain"); m_scan_effector_info.noise.fps = pSettings->r_float(ppi_section,"noise_fps"); VERIFY(!XrMath::fis_zero(m_scan_effector_info.noise.fps)); BearString::Scanf(pSettings->r_string(ppi_section,"color_base"), "%f,%f,%f", &m_scan_effector_info.color_base.r, &m_scan_effector_info.color_base.g, &m_scan_effector_info.color_base.b); BearString::Scanf(pSettings->r_string(ppi_section,"color_gray"), "%f,%f,%f", &m_scan_effector_info.color_gray.r, &m_scan_effector_info.color_gray.g, &m_scan_effector_info.color_gray.b); BearString::Scanf(pSettings->r_string(ppi_section,"color_add"), "%f,%f,%f", &m_scan_effector_info.color_add.r, &m_scan_effector_info.color_add.g, &m_scan_effector_info.color_add.b); m_scan_effector_time = pSettings->r_float(ppi_section,"time"); m_scan_effector_time_attack = pSettings->r_float(ppi_section,"time_attack"); m_scan_effector_time_release = pSettings->r_float(ppi_section,"time_release"); m_scan_sound.create (pSettings->r_string(section,"flame_scan_sound"), st_Effect,SOUND_TYPE_WORLD); //----------------------------------------------------------------------------------------- m_state_scanning = false; m_scan_next_time = 0; m_time_flame_started = 0; } void CPolterFlame::create_flame(const CObject *target_object) { Fvector position; if (!get_valid_flame_position(target_object, position)) return; SFlameElement *element = xr_new<SFlameElement>(); element->position = position; element->target_object = target_object; element->time_started = time(); element->sound.clone (m_sound, st_Effect,SOUND_TYPE_WORLD); element->sound.play_at_pos (m_object,element->position); element->particles_object = 0; element->time_last_hit = 0; Fvector target_point = get_head_position(const_cast<CObject*>(target_object)); element->target_dir.sub (target_point, element->position); element->target_dir.normalize (); m_flames.push_back (element); select_state (element, ePrepare); m_time_flame_started = time(); } void CPolterFlame::select_state(SFlameElement *elem, EFlameState state) { elem->state = state; elem->time_started = time(); switch(elem->state) { case ePrepare: // start prepare particles m_object->PlayParticles(m_particles_prepare,elem->position,elem->target_dir,TRUE); break; case eFire: // start fire particles elem->particles_object = m_object->PlayParticles(m_particles_fire,elem->position,elem->target_dir,FALSE); break; case eStop: // stop fire particles if (elem->particles_object) CParticlesObject::Destroy(elem->particles_object); // start finish particles m_object->PlayParticles(m_particles_stop,elem->position,elem->target_dir,TRUE); break; } } struct remove_predicate { bool operator() (CPolterFlame::SFlameElement *element) { return (!element); } }; void CPolterFlame::update_schedule() { inherited::update_schedule(); //--------------------------------------------------------------------- // Update Scanner if (m_object->g_Alive()) { // check the start of scanning if (!m_state_scanning && !m_object->EnemyMan.get_enemy()) { // check radius if (Actor()->Position().distance_to(m_object->Position()) < m_scan_radius) { // check timing if (m_scan_next_time < time()) { // start here m_state_scanning = true; // играть звук //m_scan_sound.play_at_pos(m_object, get_head_position(Actor()),sm_2D); ::Sound->play_at_pos(m_scan_sound, 0, Actor()->Position()); // постпроцесс Actor()->Cameras().AddPPEffector(xr_new<CMonsterEffector>(m_scan_effector_info, m_scan_effector_time, m_scan_effector_time_attack, m_scan_effector_time_release)); } } } // check stop of scanning (it currently scans) else { if (!m_scan_sound._feedback()) { // stop here m_state_scanning = false; // count next scan time m_scan_next_time = time() + Random.randI(m_scan_delay_min,m_scan_delay_max); } } } //--------------------------------------------------------------------- // check all flames for (FLAME_ELEMS_IT it = m_flames.begin();it != m_flames.end();it++) { SFlameElement *elem = *it; // test switches to states switch(elem->state) { case ePrepare: // check if time_out if (elem->time_started + m_time_fire_delay < time()) select_state(elem,eFire); break; case eFire: if (elem->time_started + m_time_fire_play < time()) select_state(elem,eStop); else { // check if we need test hit to enemy if (elem->time_last_hit + m_hit_delay < time()) { // test hit collide::rq_result rq; if (Level().ObjectSpace.RayPick(elem->position, elem->target_dir, m_length, collide::rqtBoth, rq, NULL)) { if ((rq.O == elem->target_object) && (rq.range < m_length)) { float hit_value; hit_value = m_hit_value - m_hit_value * rq.range / m_length; NET_Packet P; SHit HS; HS.GenHeader (GE_HIT, elem->target_object->ID()); // u_EventGen (P,GE_HIT, element->target_object->ID()); HS.whoID = (m_object->ID()); // P.w_u16 (ID()); HS.weaponID = (m_object->ID()); // P.w_u16 (ID()); HS.dir = (elem->target_dir); // P.w_dir (element->target_dir); HS.power = (hit_value); // P.w_float (m_flame_hit_value); HS.boneID = (BI_NONE); // P.w_s16 (BI_NONE); HS.p_in_bone_space = (Fvector().set(0.f,0.f,0.f)); // P.w_vec3 (Fvector().set(0.f,0.f,0.f)); HS.impulse = (0.f); // P.w_float (0.f); HS.hit_type = (ALife::eHitTypeBurn); // P.w_u16 (u16(ALife::eHitTypeBurn)); HS.Write_Packet (P); m_object->u_EventSend (P); elem->time_last_hit = time(); } } } } break; case eStop: xr_delete(*it); break; } } // remove all flames in state stop // удалить все элементы, выполнение которых закончено m_flames.erase ( std::remove_if( m_flames.begin(), m_flames.end(), remove_predicate() ), m_flames.end() ); // check if we can create another flame if (m_object->g_Alive() && m_object->EnemyMan.get_enemy() && (m_flames.size() < m_count)) { // check aura radius and accessibility float dist = m_object->EnemyMan.get_enemy()->Position().distance_to(m_object->Position()); if ((dist < m_pmt_aura_radius) && m_object->control().path_builder().accessible(m_object->EnemyMan.get_enemy()->Position())) { // check timing if (m_time_flame_started + m_delay < time()) { create_flame(m_object->EnemyMan.get_enemy()); } } } } void CPolterFlame::on_destroy() { inherited::on_destroy(); FLAME_ELEMS_IT I = m_flames.begin(); FLAME_ELEMS_IT E = m_flames.end(); // Пройти по всем объектам и проверить на хит врага for ( ;I != E; ++I) { if ((*I)->sound._feedback()) (*I)->sound.stop(); if ((*I)->particles_object) CParticlesObject::Destroy((*I)->particles_object); xr_delete((*I)); } m_flames.clear(); if (m_scan_sound._feedback()) m_scan_sound.stop(); } void CPolterFlame::on_die() { inherited::on_die(); if (m_scan_sound._feedback()) m_scan_sound.stop(); } #define FIND_POINT_ATTEMPT_COUNT 5 bool CPolterFlame::get_valid_flame_position(const CObject *target_object, Fvector &res_pos) { const CGameObject *Obj = smart_cast<const CGameObject *>(target_object); if (!Obj) return (false); Fvector dir; float h,p; Fvector vertex_position; Fvector new_pos; for (u32 i=0; i<FIND_POINT_ATTEMPT_COUNT; i++) { target_object->Direction().getHP(h,p); h = Random.randF(0, XrMath::PI_MUL_2); dir.setHP(h,p); dir.normalize(); vertex_position = ai().level_graph().vertex_position(Obj->ai_location().level_vertex_id()); new_pos.mad(vertex_position, dir, Random.randF(m_min_flame_dist, m_max_flame_dist)); u32 node = ai().level_graph().check_position_in_direction(Obj->ai_location().level_vertex_id(), vertex_position, new_pos); if (node != u32(-1)) { res_pos = ai().level_graph().vertex_position(node); res_pos.y += Random.randF(m_min_flame_height, m_max_flame_height); return (true); } } float angle = ai().level_graph().vertex_cover_angle(Obj->ai_location().level_vertex_id(),XrMath::PI_DIV_6,std::less<float>()); dir.set(1.f,0.f,0.f); dir.setHP(angle + XrMath::M_PI, 0.f); dir.normalize(); vertex_position = ai().level_graph().vertex_position(Obj->ai_location().level_vertex_id()); new_pos.mad(vertex_position, dir, Random.randF(m_min_flame_dist, m_max_flame_dist)); u32 node = ai().level_graph().check_position_in_direction(Obj->ai_location().level_vertex_id(), vertex_position, new_pos); if (node != u32(-1)) { res_pos = ai().level_graph().vertex_position(node); res_pos.y += Random.randF(m_min_flame_height, m_max_flame_height); return (true); } return (false); }
[ "i-sobolevskiy@mail.ru" ]
i-sobolevskiy@mail.ru
de38453fa35bbc8e98404c957b1e336cfbb200a7
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium/chrome/browser/webdata/web_data_service.cc
30d3f333338b3bdccc37fac54f448eb68e49e703
[ "BSD-3-Clause", "MIT" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
46,726
cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/webdata/web_data_service.h" #include "base/message_loop.h" #include "base/stl_util-inl.h" #include "base/task.h" #include "base/threading/thread.h" #include "chrome/browser/autofill/autofill_profile.h" #include "chrome/browser/autofill/credit_card.h" #include "chrome/browser/search_engines/template_url.h" #include "chrome/browser/ui/profile_error_dialog.h" #include "chrome/browser/webdata/autofill_change.h" #include "chrome/browser/webdata/autofill_entry.h" #include "chrome/browser/webdata/web_database.h" #include "chrome/common/chrome_constants.h" #include "content/common/notification_details.h" #include "content/common/notification_service.h" #include "content/common/notification_source.h" #include "content/common/notification_type.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "third_party/skia/include/core/SkBitmap.h" #include "webkit/glue/form_field.h" #include "webkit/glue/password_form.h" //////////////////////////////////////////////////////////////////////////////// // // WebDataService implementation. // //////////////////////////////////////////////////////////////////////////////// using base::Time; using webkit_glue::FormField; using webkit_glue::PasswordForm; WDAppImagesResult::WDAppImagesResult() : has_all_images(false) {} WDAppImagesResult::~WDAppImagesResult() {} WDKeywordsResult::WDKeywordsResult() : default_search_provider_id(0), builtin_keyword_version(0) { } WDKeywordsResult::~WDKeywordsResult() {} WebDataService::WebDataService() : is_running_(false), db_(NULL), failed_init_(false), should_commit_(false), next_request_handle_(1), main_loop_(MessageLoop::current()) { } bool WebDataService::Init(const FilePath& profile_path) { FilePath path = profile_path; path = path.Append(chrome::kWebDataFilename); return InitWithPath(path); } void WebDataService::Shutdown() { UnloadDatabase(); } bool WebDataService::IsRunning() const { return is_running_; } void WebDataService::UnloadDatabase() { ScheduleTask(NewRunnableMethod(this, &WebDataService::ShutdownDatabase)); } void WebDataService::CancelRequest(Handle h) { base::AutoLock l(pending_lock_); RequestMap::iterator i = pending_requests_.find(h); if (i == pending_requests_.end()) { NOTREACHED() << "Canceling a nonexistent web data service request"; return; } i->second->Cancel(); } bool WebDataService::IsDatabaseLoaded() { return db_ != NULL; } WebDatabase* WebDataService::GetDatabase() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); return db_; } ////////////////////////////////////////////////////////////////////////////// // // Keywords. // ////////////////////////////////////////////////////////////////////////////// void WebDataService::AddKeyword(const TemplateURL& url) { // Ensure that the keyword is already generated (and cached) before caching // the TemplateURL for use on another keyword. url.EnsureKeyword(); GenericRequest<TemplateURL>* request = new GenericRequest<TemplateURL>(this, GetNextRequestHandle(), NULL, url); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::AddKeywordImpl, request)); } void WebDataService::RemoveKeyword(const TemplateURL& url) { GenericRequest<TemplateURLID>* request = new GenericRequest<TemplateURLID>(this, GetNextRequestHandle(), NULL, url.id()); RegisterRequest(request); ScheduleTask( NewRunnableMethod(this, &WebDataService::RemoveKeywordImpl, request)); } void WebDataService::UpdateKeyword(const TemplateURL& url) { // Ensure that the keyword is already generated (and cached) before caching // the TemplateURL for use on another keyword. url.EnsureKeyword(); GenericRequest<TemplateURL>* request = new GenericRequest<TemplateURL>(this, GetNextRequestHandle(), NULL, url); RegisterRequest(request); ScheduleTask( NewRunnableMethod(this, &WebDataService::UpdateKeywordImpl, request)); } WebDataService::Handle WebDataService::GetKeywords( WebDataServiceConsumer* consumer) { WebDataRequest* request = new WebDataRequest(this, GetNextRequestHandle(), consumer); RegisterRequest(request); ScheduleTask( NewRunnableMethod(this, &WebDataService::GetKeywordsImpl, request)); return request->GetHandle(); } void WebDataService::SetDefaultSearchProvider(const TemplateURL* url) { GenericRequest<TemplateURLID>* request = new GenericRequest<TemplateURLID>(this, GetNextRequestHandle(), NULL, url ? url->id() : 0); RegisterRequest(request); ScheduleTask( NewRunnableMethod(this, &WebDataService::SetDefaultSearchProviderImpl, request)); } void WebDataService::SetBuiltinKeywordVersion(int version) { GenericRequest<int>* request = new GenericRequest<int>(this, GetNextRequestHandle(), NULL, version); RegisterRequest(request); ScheduleTask( NewRunnableMethod(this, &WebDataService::SetBuiltinKeywordVersionImpl, request)); } ////////////////////////////////////////////////////////////////////////////// // // Web Apps // ////////////////////////////////////////////////////////////////////////////// void WebDataService::SetWebAppImage(const GURL& app_url, const SkBitmap& image) { GenericRequest2<GURL, SkBitmap>* request = new GenericRequest2<GURL, SkBitmap>(this, GetNextRequestHandle(), NULL, app_url, image); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::SetWebAppImageImpl, request)); } void WebDataService::SetWebAppHasAllImages(const GURL& app_url, bool has_all_images) { GenericRequest2<GURL, bool>* request = new GenericRequest2<GURL, bool>(this, GetNextRequestHandle(), NULL, app_url, has_all_images); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::SetWebAppHasAllImagesImpl, request)); } void WebDataService::RemoveWebApp(const GURL& app_url) { GenericRequest<GURL>* request = new GenericRequest<GURL>(this, GetNextRequestHandle(), NULL, app_url); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::RemoveWebAppImpl, request)); } WebDataService::Handle WebDataService::GetWebAppImages( const GURL& app_url, WebDataServiceConsumer* consumer) { GenericRequest<GURL>* request = new GenericRequest<GURL>(this, GetNextRequestHandle(), consumer, app_url); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::GetWebAppImagesImpl, request)); return request->GetHandle(); } //////////////////////////////////////////////////////////////////////////////// // // Token Service // //////////////////////////////////////////////////////////////////////////////// void WebDataService::SetTokenForService(const std::string& service, const std::string& token) { GenericRequest2<std::string, std::string>* request = new GenericRequest2<std::string, std::string>( this, GetNextRequestHandle(), NULL, service, token); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::SetTokenForServiceImpl, request)); } void WebDataService::RemoveAllTokens() { GenericRequest<std::string>* request = new GenericRequest<std::string>( this, GetNextRequestHandle(), NULL, std::string()); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::RemoveAllTokensImpl, request)); } // Null on failure. Success is WDResult<std::string> WebDataService::Handle WebDataService::GetAllTokens( WebDataServiceConsumer* consumer) { GenericRequest<std::string>* request = new GenericRequest<std::string>( this, GetNextRequestHandle(), consumer, std::string()); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::GetAllTokensImpl, request)); return request->GetHandle(); } //////////////////////////////////////////////////////////////////////////////// // // Password manager. // //////////////////////////////////////////////////////////////////////////////// void WebDataService::AddLogin(const PasswordForm& form) { GenericRequest<PasswordForm>* request = new GenericRequest<PasswordForm>(this, GetNextRequestHandle(), NULL, form); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::AddLoginImpl, request)); } void WebDataService::UpdateLogin(const PasswordForm& form) { GenericRequest<PasswordForm>* request = new GenericRequest<PasswordForm>(this, GetNextRequestHandle(), NULL, form); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::UpdateLoginImpl, request)); } void WebDataService::RemoveLogin(const PasswordForm& form) { GenericRequest<PasswordForm>* request = new GenericRequest<PasswordForm>(this, GetNextRequestHandle(), NULL, form); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::RemoveLoginImpl, request)); } void WebDataService::RemoveLoginsCreatedBetween(const Time& delete_begin, const Time& delete_end) { GenericRequest2<Time, Time>* request = new GenericRequest2<Time, Time>(this, GetNextRequestHandle(), NULL, delete_begin, delete_end); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::RemoveLoginsCreatedBetweenImpl, request)); } void WebDataService::RemoveLoginsCreatedAfter(const Time& delete_begin) { RemoveLoginsCreatedBetween(delete_begin, Time()); } WebDataService::Handle WebDataService::GetLogins( const PasswordForm& form, WebDataServiceConsumer* consumer) { GenericRequest<PasswordForm>* request = new GenericRequest<PasswordForm>(this, GetNextRequestHandle(), consumer, form); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::GetLoginsImpl, request)); return request->GetHandle(); } WebDataService::Handle WebDataService::GetAutofillableLogins( WebDataServiceConsumer* consumer) { WebDataRequest* request = new WebDataRequest(this, GetNextRequestHandle(), consumer); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::GetAutofillableLoginsImpl, request)); return request->GetHandle(); } WebDataService::Handle WebDataService::GetBlacklistLogins( WebDataServiceConsumer* consumer) { WebDataRequest* request = new WebDataRequest(this, GetNextRequestHandle(), consumer); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::GetBlacklistLoginsImpl, request)); return request->GetHandle(); } //////////////////////////////////////////////////////////////////////////////// // // Autofill. // //////////////////////////////////////////////////////////////////////////////// void WebDataService::AddFormFields( const std::vector<FormField>& fields) { GenericRequest<std::vector<FormField> >* request = new GenericRequest<std::vector<FormField> >( this, GetNextRequestHandle(), NULL, fields); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::AddFormElementsImpl, request)); } WebDataService::Handle WebDataService::GetFormValuesForElementName( const string16& name, const string16& prefix, int limit, WebDataServiceConsumer* consumer) { WebDataRequest* request = new WebDataRequest(this, GetNextRequestHandle(), consumer); RegisterRequest(request); ScheduleTask( NewRunnableMethod(this, &WebDataService::GetFormValuesForElementNameImpl, request, name, prefix, limit)); return request->GetHandle(); } void WebDataService::RemoveFormElementsAddedBetween(const Time& delete_begin, const Time& delete_end) { GenericRequest2<Time, Time>* request = new GenericRequest2<Time, Time>(this, GetNextRequestHandle(), NULL, delete_begin, delete_end); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::RemoveFormElementsAddedBetweenImpl, request)); } void WebDataService::RemoveFormValueForElementName( const string16& name, const string16& value) { GenericRequest2<string16, string16>* request = new GenericRequest2<string16, string16>(this, GetNextRequestHandle(), NULL, name, value); RegisterRequest(request); ScheduleTask( NewRunnableMethod(this, &WebDataService::RemoveFormValueForElementNameImpl, request)); } void WebDataService::AddAutofillProfile(const AutofillProfile& profile) { GenericRequest<AutofillProfile>* request = new GenericRequest<AutofillProfile>( this, GetNextRequestHandle(), NULL, profile); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::AddAutofillProfileImpl, request)); } void WebDataService::UpdateAutofillProfile(const AutofillProfile& profile) { GenericRequest<AutofillProfile>* request = new GenericRequest<AutofillProfile>( this, GetNextRequestHandle(), NULL, profile); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::UpdateAutofillProfileImpl, request)); } void WebDataService::RemoveAutofillProfile(const std::string& guid) { GenericRequest<std::string>* request = new GenericRequest<std::string>( this, GetNextRequestHandle(), NULL, guid); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::RemoveAutofillProfileImpl, request)); } WebDataService::Handle WebDataService::GetAutofillProfiles( WebDataServiceConsumer* consumer) { WebDataRequest* request = new WebDataRequest(this, GetNextRequestHandle(), consumer); RegisterRequest(request); ScheduleTask( NewRunnableMethod(this, &WebDataService::GetAutofillProfilesImpl, request)); return request->GetHandle(); } void WebDataService::EmptyMigrationTrash(bool notify_sync) { GenericRequest<bool>* request = new GenericRequest<bool>( this, GetNextRequestHandle(), NULL, notify_sync); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::EmptyMigrationTrashImpl, request)); } void WebDataService::AddCreditCard(const CreditCard& credit_card) { GenericRequest<CreditCard>* request = new GenericRequest<CreditCard>( this, GetNextRequestHandle(), NULL, credit_card); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::AddCreditCardImpl, request)); } void WebDataService::UpdateCreditCard(const CreditCard& credit_card) { GenericRequest<CreditCard>* request = new GenericRequest<CreditCard>( this, GetNextRequestHandle(), NULL, credit_card); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::UpdateCreditCardImpl, request)); } void WebDataService::RemoveCreditCard(const std::string& guid) { GenericRequest<std::string>* request = new GenericRequest<std::string>( this, GetNextRequestHandle(), NULL, guid); RegisterRequest(request); ScheduleTask(NewRunnableMethod(this, &WebDataService::RemoveCreditCardImpl, request)); } WebDataService::Handle WebDataService::GetCreditCards( WebDataServiceConsumer* consumer) { WebDataRequest* request = new WebDataRequest(this, GetNextRequestHandle(), consumer); RegisterRequest(request); ScheduleTask( NewRunnableMethod(this, &WebDataService::GetCreditCardsImpl, request)); return request->GetHandle(); } void WebDataService::RemoveAutofillProfilesAndCreditCardsModifiedBetween( const Time& delete_begin, const Time& delete_end) { GenericRequest2<Time, Time>* request = new GenericRequest2<Time, Time>(this, GetNextRequestHandle(), NULL, delete_begin, delete_end); RegisterRequest(request); ScheduleTask(NewRunnableMethod( this, &WebDataService::RemoveAutofillProfilesAndCreditCardsModifiedBetweenImpl, request)); } WebDataService::~WebDataService() { if (is_running_ && db_) { DLOG_ASSERT("WebDataService dtor called without Shutdown"); } } bool WebDataService::InitWithPath(const FilePath& path) { path_ = path; is_running_ = true; ScheduleTask(NewRunnableMethod(this, &WebDataService::InitializeDatabaseIfNecessary)); return true; } void WebDataService::RequestCompleted(Handle h) { pending_lock_.Acquire(); RequestMap::iterator i = pending_requests_.find(h); if (i == pending_requests_.end()) { NOTREACHED() << "Request completed called for an unknown request"; pending_lock_.Release(); return; } // Take ownership of the request object and remove it from the map. scoped_ptr<WebDataRequest> request(i->second); pending_requests_.erase(i); pending_lock_.Release(); // Notify the consumer if needed. WebDataServiceConsumer* consumer; if (!request->IsCancelled() && (consumer = request->GetConsumer())) { consumer->OnWebDataServiceRequestDone(request->GetHandle(), request->GetResult()); } else { // Nobody is taken ownership of the result, either because it is canceled // or there is no consumer. Destroy results that require special handling. WDTypedResult const *result = request->GetResult(); if (result) { if (result->GetType() == AUTOFILL_PROFILES_RESULT) { const WDResult<std::vector<AutofillProfile*> >* r = static_cast<const WDResult<std::vector<AutofillProfile*> >*>( result); std::vector<AutofillProfile*> profiles = r->GetValue(); STLDeleteElements(&profiles); } else if (result->GetType() == AUTOFILL_CREDITCARDS_RESULT) { const WDResult<std::vector<CreditCard*> >* r = static_cast<const WDResult<std::vector<CreditCard*> >*>(result); std::vector<CreditCard*> credit_cards = r->GetValue(); STLDeleteElements(&credit_cards); } } } } void WebDataService::RegisterRequest(WebDataRequest* request) { base::AutoLock l(pending_lock_); pending_requests_[request->GetHandle()] = request; } //////////////////////////////////////////////////////////////////////////////// // // The following methods are executed in Chrome_WebDataThread. // //////////////////////////////////////////////////////////////////////////////// void WebDataService::DBInitFailed(sql::InitStatus init_status) { ShowProfileErrorDialog( (init_status == sql::INIT_FAILURE) ? IDS_COULDNT_OPEN_PROFILE_ERROR : IDS_PROFILE_TOO_NEW_ERROR); } void WebDataService::InitializeDatabaseIfNecessary() { if (db_ || failed_init_ || path_.empty()) return; // In the rare case where the db fails to initialize a dialog may get shown // that blocks the caller, yet allows other messages through. For this reason // we only set db_ to the created database if creation is successful. That // way other methods won't do anything as db_ is still NULL. WebDatabase* db = new WebDatabase(); sql::InitStatus init_status = db->Init(path_); if (init_status != sql::INIT_OK) { LOG(ERROR) << "Cannot initialize the web database: " << init_status; failed_init_ = true; delete db; if (main_loop_) { main_loop_->PostTask(FROM_HERE, NewRunnableMethod(this, &WebDataService::DBInitFailed, init_status)); } return; } BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &WebDataService::NotifyDatabaseLoadedOnUIThread)); db_ = db; db_->BeginTransaction(); } void WebDataService::NotifyDatabaseLoadedOnUIThread() { // Notify that the database has been initialized. NotificationService::current()->Notify(NotificationType::WEB_DATABASE_LOADED, Source<WebDataService>(this), NotificationService::NoDetails()); } void WebDataService::ShutdownDatabase() { should_commit_ = false; if (db_) { db_->CommitTransaction(); delete db_; db_ = NULL; } } void WebDataService::Commit() { if (should_commit_) { should_commit_ = false; if (db_) { db_->CommitTransaction(); db_->BeginTransaction(); } } } void WebDataService::ScheduleTask(Task* t) { if (is_running_) BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, t); else NOTREACHED() << "Task scheduled after Shutdown()"; } void WebDataService::ScheduleCommit() { if (should_commit_ == false) { should_commit_ = true; ScheduleTask(NewRunnableMethod(this, &WebDataService::Commit)); } } int WebDataService::GetNextRequestHandle() { base::AutoLock l(pending_lock_); return ++next_request_handle_; } //////////////////////////////////////////////////////////////////////////////// // // Keywords implementation. // //////////////////////////////////////////////////////////////////////////////// void WebDataService::AddKeywordImpl(GenericRequest<TemplateURL>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { db_->GetKeywordTable()->AddKeyword(request->GetArgument()); ScheduleCommit(); } request->RequestComplete(); } void WebDataService::RemoveKeywordImpl( GenericRequest<TemplateURLID>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { DCHECK(request->GetArgument()); db_->GetKeywordTable()->RemoveKeyword(request->GetArgument()); ScheduleCommit(); } request->RequestComplete(); } void WebDataService::UpdateKeywordImpl(GenericRequest<TemplateURL>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { if (!db_->GetKeywordTable()->UpdateKeyword(request->GetArgument())) { NOTREACHED(); return; } ScheduleCommit(); } request->RequestComplete(); } void WebDataService::GetKeywordsImpl(WebDataRequest* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { WDKeywordsResult result; db_->GetKeywordTable()->GetKeywords(&result.keywords); result.default_search_provider_id = db_->GetKeywordTable()->GetDefaulSearchProviderID(); result.builtin_keyword_version = db_->GetKeywordTable()->GetBuitinKeywordVersion(); request->SetResult( new WDResult<WDKeywordsResult>(KEYWORDS_RESULT, result)); } request->RequestComplete(); } void WebDataService::SetDefaultSearchProviderImpl( GenericRequest<TemplateURLID>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { if (!db_->GetKeywordTable()->SetDefaultSearchProviderID( request->GetArgument())) { NOTREACHED(); return; } ScheduleCommit(); } request->RequestComplete(); } void WebDataService::SetBuiltinKeywordVersionImpl( GenericRequest<int>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { if (!db_->GetKeywordTable()->SetBuitinKeywordVersion( request->GetArgument())) { NOTREACHED(); return; } ScheduleCommit(); } request->RequestComplete(); } //////////////////////////////////////////////////////////////////////////////// // // Web Apps implementation. // //////////////////////////////////////////////////////////////////////////////// void WebDataService::SetWebAppImageImpl( GenericRequest2<GURL, SkBitmap>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { db_->GetWebAppsTable()->SetWebAppImage( request->GetArgument1(), request->GetArgument2()); ScheduleCommit(); } request->RequestComplete(); } void WebDataService::SetWebAppHasAllImagesImpl( GenericRequest2<GURL, bool>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { db_->GetWebAppsTable()->SetWebAppHasAllImages(request->GetArgument1(), request->GetArgument2()); ScheduleCommit(); } request->RequestComplete(); } void WebDataService::RemoveWebAppImpl(GenericRequest<GURL>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { db_->GetWebAppsTable()->RemoveWebApp(request->GetArgument()); ScheduleCommit(); } request->RequestComplete(); } void WebDataService::GetWebAppImagesImpl(GenericRequest<GURL>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { WDAppImagesResult result; result.has_all_images = db_->GetWebAppsTable()->GetWebAppHasAllImages(request->GetArgument()); db_->GetWebAppsTable()->GetWebAppImages( request->GetArgument(), &result.images); request->SetResult( new WDResult<WDAppImagesResult>(WEB_APP_IMAGES, result)); } request->RequestComplete(); } //////////////////////////////////////////////////////////////////////////////// // // Token Service implementation. // //////////////////////////////////////////////////////////////////////////////// // argument std::string is unused void WebDataService::RemoveAllTokensImpl( GenericRequest<std::string>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { if (db_->GetTokenServiceTable()->RemoveAllTokens()) { ScheduleCommit(); } } request->RequestComplete(); } void WebDataService::SetTokenForServiceImpl( GenericRequest2<std::string, std::string>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { if (db_->GetTokenServiceTable()->SetTokenForService( request->GetArgument1(), request->GetArgument2())) { ScheduleCommit(); } } request->RequestComplete(); } // argument is unused void WebDataService::GetAllTokensImpl( GenericRequest<std::string>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { std::map<std::string, std::string> map; db_->GetTokenServiceTable()->GetAllTokens(&map); request->SetResult( new WDResult<std::map<std::string, std::string> >(TOKEN_RESULT, map)); } request->RequestComplete(); } //////////////////////////////////////////////////////////////////////////////// // // Password manager implementation. // //////////////////////////////////////////////////////////////////////////////// void WebDataService::AddLoginImpl(GenericRequest<PasswordForm>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { if (db_->GetLoginsTable()->AddLogin(request->GetArgument())) ScheduleCommit(); } request->RequestComplete(); } void WebDataService::UpdateLoginImpl(GenericRequest<PasswordForm>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { if (db_->GetLoginsTable()->UpdateLogin(request->GetArgument())) ScheduleCommit(); } request->RequestComplete(); } void WebDataService::RemoveLoginImpl(GenericRequest<PasswordForm>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { if (db_->GetLoginsTable()->RemoveLogin(request->GetArgument())) ScheduleCommit(); } request->RequestComplete(); } void WebDataService::RemoveLoginsCreatedBetweenImpl( GenericRequest2<Time, Time>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { if (db_->GetLoginsTable()->RemoveLoginsCreatedBetween( request->GetArgument1(), request->GetArgument2())) { ScheduleCommit(); } } request->RequestComplete(); } void WebDataService::GetLoginsImpl(GenericRequest<PasswordForm>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { std::vector<PasswordForm*> forms; db_->GetLoginsTable()->GetLogins(request->GetArgument(), &forms); request->SetResult( new WDResult<std::vector<PasswordForm*> >(PASSWORD_RESULT, forms)); } request->RequestComplete(); } void WebDataService::GetAutofillableLoginsImpl(WebDataRequest* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { std::vector<PasswordForm*> forms; db_->GetLoginsTable()->GetAllLogins(&forms, false); request->SetResult( new WDResult<std::vector<PasswordForm*> >(PASSWORD_RESULT, forms)); } request->RequestComplete(); } void WebDataService::GetBlacklistLoginsImpl(WebDataRequest* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { std::vector<PasswordForm*> all_forms; db_->GetLoginsTable()->GetAllLogins(&all_forms, true); std::vector<PasswordForm*> blacklist_forms; for (std::vector<PasswordForm*>::iterator i = all_forms.begin(); i != all_forms.end(); ++i) { scoped_ptr<PasswordForm> form(*i); if (form->blacklisted_by_user) { blacklist_forms.push_back(form.release()); } } all_forms.clear(); request->SetResult( new WDResult<std::vector<PasswordForm*> >(PASSWORD_RESULT, blacklist_forms)); } request->RequestComplete(); } //////////////////////////////////////////////////////////////////////////////// // // Autofill implementation. // //////////////////////////////////////////////////////////////////////////////// void WebDataService::AddFormElementsImpl( GenericRequest<std::vector<FormField> >* request) { InitializeDatabaseIfNecessary(); const std::vector<FormField>& form_fields = request->GetArgument(); if (db_ && !request->IsCancelled()) { AutofillChangeList changes; if (!db_->GetAutofillTable()->AddFormFieldValues(form_fields, &changes)) { NOTREACHED(); return; } request->SetResult( new WDResult<AutofillChangeList>(AUTOFILL_CHANGES, changes)); ScheduleCommit(); // Post the notifications including the list of affected keys. // This is sent here so that work resulting from this notification will be // done on the DB thread, and not the UI thread. NotificationService::current()->Notify( NotificationType::AUTOFILL_ENTRIES_CHANGED, Source<WebDataService>(this), Details<AutofillChangeList>(&changes)); } request->RequestComplete(); } void WebDataService::GetFormValuesForElementNameImpl(WebDataRequest* request, const string16& name, const string16& prefix, int limit) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { std::vector<string16> values; db_->GetAutofillTable()->GetFormValuesForElementName( name, prefix, &values, limit); request->SetResult( new WDResult<std::vector<string16> >(AUTOFILL_VALUE_RESULT, values)); } request->RequestComplete(); } void WebDataService::RemoveFormElementsAddedBetweenImpl( GenericRequest2<Time, Time>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { AutofillChangeList changes; if (db_->GetAutofillTable()->RemoveFormElementsAddedBetween( request->GetArgument1(), request->GetArgument2(), &changes)) { if (!changes.empty()) { request->SetResult( new WDResult<AutofillChangeList>(AUTOFILL_CHANGES, changes)); // Post the notifications including the list of affected keys. // This is sent here so that work resulting from this notification // will be done on the DB thread, and not the UI thread. NotificationService::current()->Notify( NotificationType::AUTOFILL_ENTRIES_CHANGED, Source<WebDataService>(this), Details<AutofillChangeList>(&changes)); } ScheduleCommit(); } } request->RequestComplete(); } void WebDataService::RemoveFormValueForElementNameImpl( GenericRequest2<string16, string16>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { const string16& name = request->GetArgument1(); const string16& value = request->GetArgument2(); if (db_->GetAutofillTable()->RemoveFormElement(name, value)) { AutofillChangeList changes; changes.push_back(AutofillChange(AutofillChange::REMOVE, AutofillKey(name, value))); request->SetResult( new WDResult<AutofillChangeList>(AUTOFILL_CHANGES, changes)); ScheduleCommit(); // Post the notifications including the list of affected keys. NotificationService::current()->Notify( NotificationType::AUTOFILL_ENTRIES_CHANGED, Source<WebDataService>(this), Details<AutofillChangeList>(&changes)); } } request->RequestComplete(); } void WebDataService::AddAutofillProfileImpl( GenericRequest<AutofillProfile>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { const AutofillProfile& profile = request->GetArgument(); if (!db_->GetAutofillTable()->AddAutofillProfile(profile)) { NOTREACHED(); return; } ScheduleCommit(); // Send GUID-based notification. AutofillProfileChange change(AutofillProfileChange::ADD, profile.guid(), &profile); NotificationService::current()->Notify( NotificationType::AUTOFILL_PROFILE_CHANGED, Source<WebDataService>(this), Details<AutofillProfileChange>(&change)); } request->RequestComplete(); } void WebDataService::UpdateAutofillProfileImpl( GenericRequest<AutofillProfile>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { const AutofillProfile& profile = request->GetArgument(); // Only perform the update if the profile exists. It is currently // valid to try to update a missing profile. We simply drop the write and // the caller will detect this on the next refresh. AutofillProfile* original_profile = NULL; if (!db_->GetAutofillTable()->GetAutofillProfile(profile.guid(), &original_profile)) { request->RequestComplete(); return; } scoped_ptr<AutofillProfile> scoped_profile(original_profile); if (!db_->GetAutofillTable()->UpdateAutofillProfileMulti(profile)) { NOTREACHED(); return; } ScheduleCommit(); // Send GUID-based notification. AutofillProfileChange change(AutofillProfileChange::UPDATE, profile.guid(), &profile); NotificationService::current()->Notify( NotificationType::AUTOFILL_PROFILE_CHANGED, Source<WebDataService>(this), Details<AutofillProfileChange>(&change)); } request->RequestComplete(); } void WebDataService::RemoveAutofillProfileImpl( GenericRequest<std::string>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { std::string guid = request->GetArgument(); AutofillProfile* profile = NULL; if (!db_->GetAutofillTable()->GetAutofillProfile(guid, &profile)) { NOTREACHED(); return; } scoped_ptr<AutofillProfile> scoped_profile(profile); if (!db_->GetAutofillTable()->RemoveAutofillProfile(guid)) { NOTREACHED(); return; } ScheduleCommit(); // Send GUID-based notification. AutofillProfileChange change(AutofillProfileChange::REMOVE, guid, NULL); NotificationService::current()->Notify( NotificationType::AUTOFILL_PROFILE_CHANGED, Source<WebDataService>(this), Details<AutofillProfileChange>(&change)); } request->RequestComplete(); } void WebDataService::GetAutofillProfilesImpl(WebDataRequest* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { std::vector<AutofillProfile*> profiles; db_->GetAutofillTable()->GetAutofillProfiles(&profiles); request->SetResult( new WDResult<std::vector<AutofillProfile*> >(AUTOFILL_PROFILES_RESULT, profiles)); } request->RequestComplete(); } void WebDataService::EmptyMigrationTrashImpl( GenericRequest<bool>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { bool notify_sync = request->GetArgument(); if (notify_sync) { std::vector<std::string> guids; if (!db_->GetAutofillTable()->GetAutofillProfilesInTrash(&guids)) { NOTREACHED(); return; } for (std::vector<std::string>::const_iterator iter = guids.begin(); iter != guids.end(); ++iter) { // Send GUID-based notification. AutofillProfileChange change(AutofillProfileChange::REMOVE, *iter, NULL); NotificationService::current()->Notify( NotificationType::AUTOFILL_PROFILE_CHANGED, Source<WebDataService>(this), Details<AutofillProfileChange>(&change)); } // If we trashed any profiles they may have been merged, so send out // update notifications as well. if (!guids.empty()) { std::vector<AutofillProfile*> profiles; db_->GetAutofillTable()->GetAutofillProfiles(&profiles); for (std::vector<AutofillProfile*>::const_iterator iter = profiles.begin(); iter != profiles.end(); ++iter) { AutofillProfileChange change(AutofillProfileChange::UPDATE, (*iter)->guid(), *iter); NotificationService::current()->Notify( NotificationType::AUTOFILL_PROFILE_CHANGED, Source<WebDataService>(this), Details<AutofillProfileChange>(&change)); } STLDeleteElements(&profiles); } } if (!db_->GetAutofillTable()->EmptyAutofillProfilesTrash()) { NOTREACHED(); return; } ScheduleCommit(); } request->RequestComplete(); } void WebDataService::AddCreditCardImpl( GenericRequest<CreditCard>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { const CreditCard& credit_card = request->GetArgument(); if (!db_->GetAutofillTable()->AddCreditCard(credit_card)) { NOTREACHED(); return; } ScheduleCommit(); // Send GUID-based notification. AutofillCreditCardChange change(AutofillCreditCardChange::ADD, credit_card.guid(), &credit_card); NotificationService::current()->Notify( NotificationType::AUTOFILL_CREDIT_CARD_CHANGED, Source<WebDataService>(this), Details<AutofillCreditCardChange>(&change)); } request->RequestComplete(); } void WebDataService::UpdateCreditCardImpl( GenericRequest<CreditCard>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { const CreditCard& credit_card = request->GetArgument(); // It is currently valid to try to update a missing profile. We simply drop // the write and the caller will detect this on the next refresh. CreditCard* original_credit_card = NULL; if (!db_->GetAutofillTable()->GetCreditCard(credit_card.guid(), &original_credit_card)) { request->RequestComplete(); return; } scoped_ptr<CreditCard> scoped_credit_card(original_credit_card); if (!db_->GetAutofillTable()->UpdateCreditCard(credit_card)) { NOTREACHED(); return; } ScheduleCommit(); // Send GUID-based notification. AutofillCreditCardChange change(AutofillCreditCardChange::UPDATE, credit_card.guid(), &credit_card); NotificationService::current()->Notify( NotificationType::AUTOFILL_CREDIT_CARD_CHANGED, Source<WebDataService>(this), Details<AutofillCreditCardChange>(&change)); } request->RequestComplete(); } void WebDataService::RemoveCreditCardImpl( GenericRequest<std::string>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { std::string guid = request->GetArgument(); if (!db_->GetAutofillTable()->RemoveCreditCard(guid)) { NOTREACHED(); return; } ScheduleCommit(); // Send GUID-based notification. AutofillCreditCardChange change(AutofillCreditCardChange::REMOVE, guid, NULL); NotificationService::current()->Notify( NotificationType::AUTOFILL_CREDIT_CARD_CHANGED, Source<WebDataService>(this), Details<AutofillCreditCardChange>(&change)); } request->RequestComplete(); } void WebDataService::GetCreditCardsImpl(WebDataRequest* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { std::vector<CreditCard*> credit_cards; db_->GetAutofillTable()->GetCreditCards(&credit_cards); request->SetResult( new WDResult<std::vector<CreditCard*> >(AUTOFILL_CREDITCARDS_RESULT, credit_cards)); } request->RequestComplete(); } void WebDataService::RemoveAutofillProfilesAndCreditCardsModifiedBetweenImpl( GenericRequest2<Time, Time>* request) { InitializeDatabaseIfNecessary(); if (db_ && !request->IsCancelled()) { std::vector<std::string> profile_guids; std::vector<std::string> credit_card_guids; if (db_->GetAutofillTable()-> RemoveAutofillProfilesAndCreditCardsModifiedBetween( request->GetArgument1(), request->GetArgument2(), &profile_guids, &credit_card_guids)) { for (std::vector<std::string>::iterator iter = profile_guids.begin(); iter != profile_guids.end(); ++iter) { AutofillProfileChange change(AutofillProfileChange::REMOVE, *iter, NULL); NotificationService::current()->Notify( NotificationType::AUTOFILL_PROFILE_CHANGED, Source<WebDataService>(this), Details<AutofillProfileChange>(&change)); } for (std::vector<std::string>::iterator iter = credit_card_guids.begin(); iter != credit_card_guids.end(); ++iter) { AutofillCreditCardChange change(AutofillCreditCardChange::REMOVE, *iter, NULL); NotificationService::current()->Notify( NotificationType::AUTOFILL_CREDIT_CARD_CHANGED, Source<WebDataService>(this), Details<AutofillCreditCardChange>(&change)); } // Note: It is the caller's responsibility to post notifications for any // changes, e.g. by calling the Refresh() method of PersonalDataManager. ScheduleCommit(); } } request->RequestComplete(); } //////////////////////////////////////////////////////////////////////////////// // // WebDataRequest implementation. // //////////////////////////////////////////////////////////////////////////////// WebDataService::WebDataRequest::WebDataRequest(WebDataService* service, Handle handle, WebDataServiceConsumer* consumer) : service_(service), handle_(handle), canceled_(false), consumer_(consumer), result_(NULL) { message_loop_ = MessageLoop::current(); } WebDataService::WebDataRequest::~WebDataRequest() { delete result_; } WebDataService::Handle WebDataService::WebDataRequest::GetHandle() const { return handle_; } WebDataServiceConsumer* WebDataService::WebDataRequest::GetConsumer() const { return consumer_; } bool WebDataService::WebDataRequest::IsCancelled() const { return canceled_; } void WebDataService::WebDataRequest::Cancel() { canceled_ = true; consumer_ = NULL; } void WebDataService::WebDataRequest::SetResult(WDTypedResult* r) { result_ = r; } const WDTypedResult* WebDataService::WebDataRequest::GetResult() const { return result_; } void WebDataService::WebDataRequest::RequestComplete() { WebDataService* s = service_; Task* t = NewRunnableMethod(s, &WebDataService::RequestCompleted, handle_); message_loop_->PostTask(FROM_HERE, t); }
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
2937c3be1c50184e25e9250ee3c62255738ac886
ea6cd39c2e335c5673b590ecae108f066fa7e59f
/luogu/1967(WA-DFS).cpp
1583c0d00816828179ba4600b669493f4c2667f8
[]
no_license
Xu-Xihe/codes-and-docs-xxh
73c7497e21bbcbce6b512b9a106e5e4a8b436a40
04a2cbe4416719e5c7ea3ee4ea9b46452d958b4c
refs/heads/main
2023-08-21T08:36:21.911043
2021-10-09T14:39:53
2021-10-09T14:39:53
415,333,666
0
0
null
null
null
null
UTF-8
C++
false
false
2,898
cpp
#include <cstdio> #include <queue> #include <vector> #include <cmath> int n, m; const int maxe = 10009; std::vector<int> fa; std::vector<short int> point[maxe]; std::queue<short int> single; std::vector<short int> nodes; bool ji[maxe]; int edge[maxe][maxe]; struct way { int city1, city2, weigh; bool friend operator<(way a, way b) { return a.weigh < b.weigh; } }; struct node { int next, weigh; }; std::priority_queue<way> ways; //std::queue<way> chosen; int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); } void together(int a, int b) { int x = find(a), y = find(b); fa[x] = y; return; } void dfs(int now, int last) { printf("\n\nchu: %d %d\n\n",now,last); int len = nodes.size(); for (int i = 0; i < len; i++) { int least = edge[nodes[i]][last] < edge[last][now] ? edge[nodes[i]][last] : edge[last][now]; edge[nodes[i]][now] = least; edge[now][nodes[i]] = least; } if (point[now].size() == 1) return; nodes.push_back(last); for (int i = 0; i < point[now].size(); i++) { if(point[now][i]!=last)dfs(point[now][i],now); } } void out() { printf("\n\nceshi:\n\n"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { printf("%10d ", edge[i + 1][j + 1]); } printf("\n\n"); } printf("\n\n"); return; } int main() { scanf("%d%d", &n, &m); for (int i = 0; i < n + 9; i++) { fa.push_back(i); for (int j = 0; j < n + 9; j++) { edge[i][j] = 2e9; } } for (int i = 0; i < m; i++) { way in; scanf("%d%d%d", &in.city1, &in.city2, &in.weigh); ways.push(in); } for (int i = 0; i < m; i++) { way top = ways.top(); ways.pop(); if (find(top.city1) != find(top.city2)) { together(top.city1, top.city2); //chosen.push(top); point[top.city1].push_back(top.city2); point[top.city2].push_back(top.city1); edge[top.city1][top.city2] = top.weigh; edge[top.city2][top.city1] = top.weigh; } } for (int i = 0; i < n; i++) { if (point[i + 1].size() == 1 && !ji[find(i + 1)]) { single.push(i + 1); ji[find(i + 1)] = true; } } fa.clear(); int len = single.size(); for (int i = 0; i < len; i++) { dfs(point[single.front()][0], single.front()); single.pop(); } out(); int le; scanf("%d", &le); for (int i = 0; i < le; i++) { int a, b; scanf("%d%d", &a, &b); printf("%d\n", edge[a][b] == 2e9 ? -1 : edge[a][b]); } return 0; }
[ "xxhsishi@outlook.com" ]
xxhsishi@outlook.com
ac98718317c8ab699274727e794b3c72e26622b2
6ab5eeb601c022adab666982143dfcf8e5d43b61
/AC Huffmann coding/AC Huffmann coding/InputParser.h
d5f558277b46188375004baf3de46275c41e5a45
[]
no_license
Bussler/Arithmetic-and-huffmann-coding
9a3b34c57834dc3cfdff9d075d9a7a83d4f53b9b
80c26eafea8ca6a9eeb7eb97bccb8a9c3ca905f7
refs/heads/main
2023-01-06T01:57:58.926568
2020-10-28T11:48:46
2020-10-28T11:48:46
304,291,508
0
0
null
null
null
null
UTF-8
C++
false
false
537
h
#pragma once #include <iostream> #include <fstream> namespace BitIO { extern struct RWWrapper rw; //wrapper class to hold information for read/write void writeData(unsigned char* data, int numBytes); void writeBit(uint64_t bits, int numBits); void writeRemainingBit(); void readData(uint8_t * buf, int numBytes); uint64_t readBit(int numBits); void openRead(char* name); void closeRead(); void openWrite(char* name); void closeWrite(); extern unsigned char * pData; extern int pSize; void parseData(char * txtName); }
[ "maarten.bussler@gmail.com" ]
maarten.bussler@gmail.com
42a0b5dd6ed5d82e724be1f86e09699bf50d530f
cea1e16ad0cc21ce8dd02a4933d6cd3e297abe06
/ww20020907e_fly!!!_snuconstest2002/Swing/DISP.BAK
b98943e79458787bb928a1b0e578a7c5d75b804d
[ "BSD-2-Clause" ]
permissive
wizest/wingwing
86b470d7cec4416d140d5a8b03cf14ddd40dae40
67390650c1f928d0e611f0e1339d58ba08c683d8
refs/heads/master
2021-01-19T09:45:22.493735
2015-01-06T15:44:22
2015-01-06T15:44:22
25,371,709
0
0
null
null
null
null
UTF-8
C++
false
false
5,190
bak
#include <graphics.h> #include <conio.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <dos.h> #include <string.h> #include "main.h" #include "disp.h" double ONESTEP = RADIUS*ANGLE0_9; //mm double TURNANGLE = ONESTEP/WIDTH; //rad double COSTURN = cos(TURNANGLE); double SINTURN = sin(TURNANGLE); int L_COLOR = LIGHTBLUE; int R_COLOR = LIGHTRED; int L_DIREC = FORWARD; int R_DIREC = FORWARD; double xl = XL, yl = YL, xl_old, yl_old; double xr = XR, yr = YR, xr_old, yr_old; double bx = 0 , by = 0; // base x,y double BLK_DIST ; // pixel double BLK_X ; // pixel double BLK_Y ; // pixel double XL ; double XR ; double YL ; double YR ; void init_scr() { BLK_DIST = 440; // pixel init_scr_size(); } void init_scr_size() { BLK_X = 5; // pixel BLK_Y = 5; // pixel XL =(double)BLK_DIST/2.+BLK_X-mm2pixel(WIDTH/2.); XR =XL+mm2pixel(WIDTH); YL =BLK_Y+BLK_DIST * 1; YR =YL; } void enlarge_scr() { BLK_DIST *= 1.1; init_scr_size(); } void delarge_scr() { BLK_DIST *= 0.9; init_scr_size(); } void exchange_color() { int temp_color; temp_color=L_COLOR; L_COLOR=R_COLOR; R_COLOR=temp_color; } void reverse_L() { L_DIREC *= -1; } void reverse_R() { R_DIREC *= -1; } void reverse_LR() { reverse_L(); reverse_R(); } void open_screen() { int gdriver = DETECT, gmode, errorcode; initgraph(&gdriver, &gmode, ""); errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* return with error code */ } /* clean up */ } void close_screen() { closegraph(); } void step_left(int f_or_b) { xl_old=xl; yl_old=yl; xl=xr+ (xl_old-xr)*COSTURN-f_or_b*(yl_old-yr)*SINTURN; yl=yr+f_or_b*(xl_old-xr)*SINTURN+ (yl_old-yr)*COSTURN; l_steps++; } void step_right(int f_or_b) { xr_old=xr; yr_old=yr; xr=xl+ (xr_old-xl)*COSTURN+f_or_b*(yr_old-yl)*SINTURN; yr=yl-f_or_b*(xr_old-xl)*SINTURN+ (yr_old-yl)*COSTURN; r_steps++; } void draw_trace() { putpixel(xl,yl,L_COLOR); putpixel(xr,yr,R_COLOR); putpixel((xl+xr)/2,(yl+yr)/2,LIGHTGREEN); } void draw_maze() { int blk_x=BLK_X; int blk_y=BLK_Y; // setfillstyle(SOLID_FILL,BLACK); // bar(0,0,639,479); cleardevice(); for (int i=0;i<5;i++) { for(int j=0;j<5;j++) { //block setcolor(GREEN); rectangle(blk_x,blk_y,blk_x+BLK_DIST,blk_y+BLK_DIST); //Compare Guide Line setcolor(DARKGRAY); setlinestyle(SOLID_LINE,0,NORM_WIDTH); //setlinestyle(DOTTED_LINE,0,NORM_WIDTH); for(double x=blk_x;x<=blk_x+BLK_DIST;x+=mm2pixel(10)) line(x,blk_y+mm2pixel(6),x,blk_y+BLK_DIST-mm2pixel(6)); for(double y=blk_y;y<=blk_y+BLK_DIST;y+=mm2pixel(10)) line(blk_x+mm2pixel(6),y,blk_x+BLK_DIST-mm2pixel(6),y); //Pole setcolor(LIGHTRED); setlinestyle(SOLID_LINE,0,NORM_WIDTH); rectangle(blk_x -mm2pixel(6),blk_y -mm2pixel(6),blk_x +mm2pixel(6),blk_y +mm2pixel(6) ); rectangle(blk_x+BLK_DIST -mm2pixel(6),blk_y -mm2pixel(6),blk_x+BLK_DIST +mm2pixel(6),blk_y +mm2pixel(6) ); rectangle(blk_x -mm2pixel(6),blk_y+BLK_DIST -mm2pixel(6),blk_x +mm2pixel(6),blk_y+BLK_DIST +mm2pixel(6) ); rectangle(blk_x+BLK_DIST -mm2pixel(6),blk_y+BLK_DIST -mm2pixel(6),blk_x+BLK_DIST +mm2pixel(6),blk_y+BLK_DIST +mm2pixel(6) ); //Diagonal setcolor(CYAN); setlinestyle(DOTTED_LINE,0,NORM_WIDTH); line(blk_x+BLK_DIST/2,blk_y,blk_x+BLK_DIST,blk_y+BLK_DIST/2); line(blk_x+BLK_DIST/2,blk_y,blk_x,blk_y+BLK_DIST/2); line(blk_x+BLK_DIST/2,blk_y+BLK_DIST,blk_x+BLK_DIST,blk_y+BLK_DIST/2); line(blk_x+BLK_DIST/2,blk_y+BLK_DIST,blk_x,blk_y+BLK_DIST/2); line(blk_x,blk_y,blk_x+BLK_DIST,blk_y+BLK_DIST); line(blk_x+BLK_DIST,blk_y,blk_x,blk_y+BLK_DIST); //edge line 90 setcolor(BLUE); setlinestyle(SOLID_LINE,0,NORM_WIDTH); rectangle(blk_x+EDGE_LINE_90,blk_y+EDGE_LINE_90,blk_x+BLK_DIST-EDGE_LINE_90,blk_y+BLK_DIST-EDGE_LINE_90); //after edge line 90 setcolor(GREEN); setlinestyle(SOLID_LINE,0,NORM_WIDTH); rectangle(blk_x+AFTER_EDGE_LINE_90,blk_y+AFTER_EDGE_LINE_90,blk_x+BLK_DIST-AFTER_EDGE_LINE_90,blk_y+BLK_DIST-AFTER_EDGE_LINE_90); blk_x+=BLK_DIST; } blk_x=BLK_X; blk_y+=BLK_DIST; } setcolor(WHITE); setlinestyle(SOLID_LINE,0,NORM_WIDTH); } void show_info() { char text[30]; // Show the count of the steps sprintf(text,"L:%d",l_steps); ks_outtextxy(520,2,text); sprintf(text,"R:%d",r_steps); ks_outtextxy(520+8*7,2,text); sprintf(text,"SL:%d",spd_ptr_L); ks_outtextxy(520,12,text); sprintf(text,"SR:%d",spd_ptr_R); ks_outtextxy(520,22,text); sprintf(text,"iS:%d",iSpd); ks_outtextxy(520,32,text); sprintf(text,"io:%d",ioS); ks_outtextxy(520,42,text); sprintf(text,"th:%d",thS); ks_outtextxy(520,52,text); sprintf(text,"tL:%d",l_steps*2); ks_outtextxy(520,62,text); sprintf(text,"tR:%d",r_steps*2); ks_outtextxy(520+8*7,62,text); } void ks_outtextxy(int x,int y, const char *text) { setfillstyle(SOLID_FILL,BLACK); bar(x,y,x+8*(strlen(text)+1),y+8); outtextxy(x,y,text); }
[ "wizest@gmail.com" ]
wizest@gmail.com
93b8276a1247044756674a920f2857c908fafca0
7d63d13b13d31143112fb1ff21158570c24e72d3
/Synth/LFOComponent.h
495babc1da55c603e0ee9671c5c0d3632690d6c5
[]
no_license
stawrocek/synth
60571c4065bef33fd5fa890d32ff48385ffc64bd
94f24b5d1b7b03a51b1de6d964b67760b39da587
refs/heads/main
2023-08-13T11:50:43.478413
2021-09-07T16:48:37
2021-09-07T16:48:37
354,365,554
1
0
null
null
null
null
UTF-8
C++
false
false
1,545
h
#pragma once #include <JuceHeader.h> #include "PluginProcessor.h" #include "SynthComponent.h" #include "RotarySlider.h" #include "WaveformButton.h" class LFOComponent : public SynthComponent { public: LFOComponent(SynthAudioProcessor& processor); void resized() override; private: WaveformButton btnOscSine; WaveformButton btnOscRect; WaveformButton btnOscTriangle; WaveformButton btnOscSawtooth; RotarySlider sliderLFORate; RotarySlider sliderLFOIntensity; GroupComponent lfoTargets; TextButton lfoTargetFilterCutoff; TextButton lfoTargetDetune; TextButton lfoTargetVolume; std::unique_ptr<juce::AudioProcessorValueTreeState::SliderAttachment> sliderAttachmentRate; std::unique_ptr<juce::AudioProcessorValueTreeState::SliderAttachment> sliderAttachmentIntensity; std::unique_ptr<juce::AudioProcessorValueTreeState::ButtonAttachment> buttonTarget1Attachment; std::unique_ptr<juce::AudioProcessorValueTreeState::ButtonAttachment> buttonTarget2Attachment; std::unique_ptr<juce::AudioProcessorValueTreeState::ButtonAttachment> buttonTarget3Attachment; std::unique_ptr<juce::AudioProcessorValueTreeState::ButtonAttachment> buttonWaveformSineAttachment; std::unique_ptr<juce::AudioProcessorValueTreeState::ButtonAttachment> buttonWaveformSquareAttachment; std::unique_ptr<juce::AudioProcessorValueTreeState::ButtonAttachment> buttonWaveformTriangleAttachment; std::unique_ptr<juce::AudioProcessorValueTreeState::ButtonAttachment> buttonWaveformSawtoothAttachment; };
[ "stasiukoza1234@gmail.com" ]
stasiukoza1234@gmail.com
d44f45eb55c3f37bc15e5ed2a9b594ad9f855b5b
dc9fa0ac2f9b918e29bd0ed66787c90d82a3857d
/impl/platform/mac/units/io/io_posix.hpp
375d2f26ed75db4868350ad7055889f5884be429
[ "MIT" ]
permissive
faustic/nexo
50db9dd7c77e4965ebbf81e6a3e37ca673f00131
94ef61c21670884208ce264da9eb307f0ffdb405
refs/heads/master
2023-05-09T06:19:54.598796
2023-03-21T08:58:45
2023-03-21T08:58:45
179,716,014
0
0
null
null
null
null
UTF-8
C++
false
false
1,434
hpp
// io_posix.hpp // Input/output: interface for POSIX // Intended compatibility: c++20 // // Created by Alejandro Castro García on 10 September 2021 /* Licensed under the MIT License. Copyright (c) 2021 Faustic Inferno SL 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 nexo_io_posix_h #define nexo_io_posix_h #include <nexo/io/io.hpp> namespace nexo { class Io_handler::Impl { public: int fd = -1; }; } #endif /* nexo_io_posix_h */
[ "47532786+castro67@users.noreply.github.com" ]
47532786+castro67@users.noreply.github.com
c6c47e29d8f6d819f731d70c153b7fe5b9cb247b
f0b7bcc41298354b471a72a7eeafe349aa8655bf
/codebase/apps/Radx/src/deprecated/RadxPersistentClutter/prototype/original/FrequencyCount.cc
cdf046871e5087360b1b27cd7237570bdae84f04
[ "BSD-3-Clause" ]
permissive
NCAR/lrose-core
23abeb4e4f1b287725dc659fb566a293aba70069
be0d059240ca442883ae2993b6aa112011755688
refs/heads/master
2023-09-01T04:01:36.030960
2023-08-25T00:41:16
2023-08-25T00:41:16
51,408,988
90
53
NOASSERTION
2023-08-18T21:59:40
2016-02-09T23:36:25
C++
UTF-8
C++
false
false
3,360
cc
// *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* // ** Copyright UCAR (c) 1990 - 2016 // ** University Corporation for Atmospheric Research (UCAR) // ** National Center for Atmospheric Research (NCAR) // ** Boulder, Colorado, USA // ** BSD licence applies - redistribution and use in source and binary // ** forms, with or without modification, are permitted provided that // ** the following conditions are met: // ** 1) If the software is modified to produce derivative works, // ** such modified software should be clearly marked, so as not // ** to confuse it with the version available from UCAR. // ** 2) Redistributions of source code must retain the above copyright // ** notice, this list of conditions and the following disclaimer. // ** 3) Redistributions in binary form must reproduce the above copyright // ** notice, this list of conditions and the following disclaimer in the // ** documentation and/or other materials provided with the distribution. // ** 4) Neither the name of UCAR nor the names of its contributors, // ** if any, may be used to endorse or promote products derived from // ** this software without specific prior written permission. // ** DISCLAIMER: THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS // ** OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED // ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* /** * @file FrequencyCount.cc */ #include <cstdio> #include <cmath> #include "FrequencyCount.hh" #include <Radx/RayxData.hh> #include <toolsa/LogMsg.hh> //------------------------------------------------------------------ FrequencyCount::FrequencyCount(const int nbins, const int nscan) { _nscan = nscan; _nbin = static_cast<double>(nbins); _totalCount = _nbin; for (int i=0; i<nbins; ++i) { double f = static_cast<double>(i)/_nbin; _frequency.push_back(f); _counts.push_back(1.0); } } //------------------------------------------------------------------ FrequencyCount::~FrequencyCount() { } //------------------------------------------------------------------ void FrequencyCount::update(const double count) { double v = count/_nscan; int bin = static_cast<int>(v*static_cast<double>(_nbin)); if (bin < 0) { bin = 0; } if (bin >= _nbin) { bin = _nbin - 1; } _counts[bin]++; ++_totalCount; } //------------------------------------------------------------------ void FrequencyCount::append(FILE *fp) { for (int i=0; i<_nbin; ++i) { fprintf(fp, "%12.10lf ", _counts[i]/_totalCount); } fprintf(fp, "\n"); } //------------------------------------------------------------------ void FrequencyCount::appendString(std::vector<std::string> &lines) { string s = ""; for (int i=0; i<_nbin; ++i) { char buf[1000]; sprintf(buf, "%12.10lf ", _counts[i]/_totalCount); // fprintf(fp, "%12.10lf ", _counts[i]/_totalCount); s += buf; } // fprintf(fp, "\n"); lines.push_back(s); }
[ "dixon@ucar.edu" ]
dixon@ucar.edu
d83f3517fe0a7925a905e61d367352841c57496a
bb8b224e6221d4eb4308ef518e986eb8a4633fde
/cpp/Neurons/Layer.cpp
b5fe8c3a5333b31b70af307b86777ed63f9e66d1
[]
no_license
JordanSlaman/neuralnetproject
ab07e23e349ccedca58a05fb2dc04cf3951ce8bf
8187029d04142bb2bd3c56bcbcc0134d58a4533b
refs/heads/master
2020-12-25T12:17:53.376961
2013-04-22T22:14:49
2013-04-22T22:14:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
775
cpp
#include "Layer.h" #include <iostream> using namespace std; bool Layer::collect() const { for(int m=base;m<base+length;m++) { //for all the neurons in this layer's juristiction, call collect(which sends a signal to that neuron's outConnections, to the next layer) ((Neuron*)allNeurons[m])->collect(); } //if this layer has a next layer that it knows about, tell it to collect. if(next) { next->collect(); } } void Layer::adjust(char expected) { for(int i=base;i<base+length;i++) { //for all the neurons in this layer's juristiction call adjust(which requires the getOmega from the next layer, so this too sends a signal forward, in a way) ((Neuron*)allNeurons[i])->adjust(expected); } if(next) { next->adjust(expected); } }
[ "geoff@geoff-Aspire-5251.(none)" ]
geoff@geoff-Aspire-5251.(none)
d658338237021fc916dbca6f0da13a3ffd0a421c
554d03e10f2723197afa67ada630e0f3fa324379
/MMVII/include/MMVII_Derivatives.h
8052285633e44c5ec1563e6c340818a269c4bb6c
[ "LicenseRef-scancode-cecill-b-en" ]
permissive
navigateai/micmac
479041dd9871cc6907f8d83ee324a587b4128a93
34ead0c155fa915e074f281d28f0285812adbb91
refs/heads/master
2021-01-05T18:23:51.924107
2020-02-13T09:04:51
2020-02-13T09:04:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,770
h
#ifndef _MMVII_Derivatives_H_ #define _MMVII_Derivatives_H_ #include "ExternalInclude/Eigen/Dense" namespace MMVII { /** \file MMVII_Derivatives.h \brief Contains stuff necessary for computing derivatives, dont know if MMVII will use jets or generate code, for now it's interface for test */ class cInterfaceTestCam; // Interface for tested derivative struct cVarEpsNum; // More or less like Ceres template<int N> struct cEpsNum; // Sparse implementation of jets /* *********************************************** */ /* */ /* :: */ /* */ /* *********************************************** */ /** Class that is can interface for computing derivative of a camera (projection fonction) derived are typically jets or generated code */ class cInterfaceTestCam { public : /// initialize parameteres from "raw" vector virtual void InitFromParams(const std::vector<double> &) = 0; /// compute values and derivatives and fill in VVals and VDer virtual void Compute(std::vector<double> & VVals,std::vector<std::vector<double> > & VDer)=0; /// Makes Nb computation (time bench ...) virtual void Compute(int aNb) =0; /// Allocate a MMV1 object static cInterfaceTestCam * AllocMMV1(); }; /* ************************************** */ /* */ /* cVarEpsNum */ /* */ /* ************************************** */ /** cVarEpsNum functionnaly equivalent to cEpsNum, but are a tentative of optimization taking into account the sparseness. The implementation use a vector of non null indexes. */ struct cVarEpsNum { // ====================== Data =========== private : // ----- static data for buffering static const int SzBuf = 1000; static double BufEps[SzBuf]; static bool IsInit; public : // ----- member data double mNum; ///< Real value std::vector<int> mVInd; ///< Index of non 0 epsilon value std::vector<double> mVEps; ///< Value of non 0 // ====================== Methods =========== /// Constructor for a "pure" number inline cVarEpsNum(double aNum) : mNum (aNum) { Init(); } /// Default Constructor convenient inline cVarEpsNum() : cVarEpsNum (0.0) { } /// Constructor for number + dXk inline cVarEpsNum(double aNum,int aK) : cVarEpsNum (aNum) { AddVal(1.0,aK); } /// Add aVal * dXk inline void AddVal(double aVal,int aK) { mVEps.push_back(aVal); mVInd.push_back(aK); } /** This constructor can be used in any "functionnal" composition for exemple cos(g) => (g,cos(g.mNum),-sin(g.mNum)) */ inline cVarEpsNum(const cVarEpsNum & aVEN,double aNum,double aMul) : mNum (aNum), mVInd (aVEN.mVInd), mVEps (aVEN.mVEps) { for (auto & aEps : mVEps) aEps *= aMul; } inline cVarEpsNum(const double & aNum,const std::vector<int>&aVInd,const std::vector<double>&aVEps) : mNum (aNum), mVInd (aVInd), mVEps (aVEps) { } /// som inline cVarEpsNum operator+(const cVarEpsNum& g) const { cVarEpsNum aRes(mNum+g.mNum); SetInBuf(); g.AddToBuf(); BuffAdd(aRes); g.BuffAdd(aRes); return aRes; } /// products inline cVarEpsNum operator*(const cVarEpsNum& g) const { cVarEpsNum aRes(mNum*g.mNum); AddToBuf(g.mNum); g.AddToBuf(mNum); BuffAdd(aRes); g.BuffAdd(aRes); return aRes; } /// Diff cVarEpsNum operator-(const cVarEpsNum& g) const { cVarEpsNum aRes(mNum-g.mNum); SetInBuf(); g.SubToBuf(); BuffAdd(aRes); g.BuffAdd(aRes); return aRes; } /// Div cVarEpsNum operator/(const cVarEpsNum& g) const { cVarEpsNum aRes(mNum/g.mNum); AddToBuf(1.0/g.mNum); g.AddToBuf(-mNum/Square(g.mNum)); BuffAdd(aRes); g.BuffAdd(aRes); return aRes; } /// Ensure that BufEps is clear static void Init() { if (IsInit) return; // If not first time, job already done IsInit = true; // next will not be first for (int aK=0 ; aK<SzBuf ; aK++) // clear buf now { BufEps[aK] = 0.0; } } /// Set the data in buf, only parse non 0, void SetInBuf() const { for (unsigned int aK=0 ; aK<mVEps.size(); aK++) { BufEps[mVInd[aK] ] = mVEps[aK]; } }; /// Add the data in buf, only parse non 0, void AddToBuf() const { for (unsigned int aK=0 ; aK<mVEps.size(); aK++) { BufEps[mVInd[aK] ] += mVEps[aK]; } }; /// Sub the data in buf, only parse non 0, void SubToBuf() const { for (unsigned int aK=0 ; aK<mVEps.size(); aK++) { BufEps[mVInd[aK] ] -= mVEps[aK]; } }; /// Add the data in buf with a multiplier, only parse non 0 void AddToBuf(const double & aMul) const { for (unsigned int aK=0 ; aK<mVEps.size(); aK++) { BufEps[mVInd[aK]] += mVEps[aK] * aMul; } }; /** Parse the index of non 0 value and : - put the non 0 corresponding value in Res - clear them in Buf */ void BuffAdd(cVarEpsNum & aRes) const { // Parse index of non 0 value for (unsigned int aK=0 ; aK<mVEps.size(); aK++) { int IndF = mVInd[aK]; double & aVal = BufEps[IndF]; if ( aVal) // if Buf is non 0 { aRes.AddVal(aVal,IndF); // Add it in res aVal = 0; // erase it } } }; }; // ========= Operation between constants and cVarEpsNum ===================== // +++++++++++++++++++++++++++++++++++ inline cVarEpsNum operator+(const cVarEpsNum& f,const double & aV) { cVarEpsNum aRes(f); aRes.mNum += aV; return aRes; } inline cVarEpsNum operator+(const double & aV,const cVarEpsNum& f) {return f+aV;} // ------------------------------------- inline cVarEpsNum operator-(const cVarEpsNum& f,const double & aV) { return cVarEpsNum (f.mNum-aV,f.mVInd,f.mVEps); } inline cVarEpsNum operator-(const double & aV,const cVarEpsNum& f) { return cVarEpsNum (aV-f.mNum,f.mVInd,f.mVEps); } // ************************************* inline cVarEpsNum operator*(const cVarEpsNum& f,const double & aV) { cVarEpsNum aRes(f); aRes.mNum *= aV; for (auto & aEps : aRes.mVEps) aEps *= aV; return aRes; } inline cVarEpsNum operator*(const double & aV,const cVarEpsNum& f) {return f*aV;} // ///////////////////////////////////// inline cVarEpsNum operator/(const cVarEpsNum& f,const double & aV) { return f * (1.0/aV); } inline cVarEpsNum operator/(const double & aV,const cVarEpsNum& f) { cVarEpsNum aRes(f); aRes.mNum = aV/f.mNum; double aMul = - 1.0/ Square(f.mNum); for (auto & aEps : aRes.mVEps) aEps *= aMul; return aRes; } // UNARY inline cVarEpsNum COS(const cVarEpsNum& g) { return cVarEpsNum(g,cos(g.mNum),-sin(g.mNum)); } // ========== /* ************************************** */ /* */ /* cEpsNum<int N> */ /* */ /* ************************************** */ /** cEpsNum are more or less equivalent to Ceres jets : it's a number + infininetely small in R^N Just wanted to be independant of Ceres during tests. */ template<int N> struct cEpsNum { // ====================== Data =========== double mNum; ///< The number Eigen::Matrix<double, 1, N> mEps; ///< The infinitely small part // ====================== Methods =========== /// Full constructor from Num + small cEpsNum(const double & aNum,const Eigen::Matrix<double, 1, N> & aEps) : mNum (aNum), mEps (aEps) { } /// constructor only numeric cEpsNum(double aNum) : cEpsNum (aNum,Eigen::Matrix<double, 1, N>::Zero()) { } /// constructor Num + dXk cEpsNum(const double & aNum,int aK) : cEpsNum (aNum) { mEps(aK) = 1.0; } /// sometime need a def constructor cEpsNum() : cEpsNum(0.0) { } cVarEpsNum ToVEN() const; static cEpsNum<N> Random(double Densite) { cEpsNum<N> aRes(N*RandUnif_C()); for (int aK=0 ; aK<N ; aK++) { if (RandUnif_0_1() < Densite) { aRes.mEps[aK] = RandUnif_C(); } } return aRes; } }; // ====== operator + ============= template<int N> cEpsNum<N> operator+(const cEpsNum<N>& f, const cEpsNum<N>& g) { return cEpsNum<N>(f.mNum + g.mNum, f.mEps + g.mEps); } template<int N> cEpsNum<N> operator+(const double & f, const cEpsNum<N>& g) { return cEpsNum<N>(f + g.mNum, g.mEps); } template<int N> cEpsNum<N> operator+(const cEpsNum<N>& g,const double & f) { return f+g; } // ====== operator - ============= template<int N> cEpsNum<N> operator-(const cEpsNum<N>& f, const cEpsNum<N>& g) { return cEpsNum<N>(f.mNum - g.mNum, f.mEps - g.mEps); } template<int N> cEpsNum<N> operator-(const double & f, const cEpsNum<N>& g) { return cEpsNum<N>(f - g.mNum, -g.mEps); } template<int N> cEpsNum<N> operator-(const cEpsNum<N>& g,const double & f) { return cEpsNum<N>(g.mNum -f, g.mEps); } // ====== operator * ============= template<int N> cEpsNum<N> operator*(const cEpsNum<N>& f, const cEpsNum<N>& g) { return cEpsNum<N>(f.mNum * g.mNum, g.mNum * f.mEps + f.mNum * g.mEps); } template<int N> cEpsNum<N> operator*(const double & f, const cEpsNum<N>& g) { return cEpsNum<N>(f*g.mNum,f*g.mEps); } template<int N> cEpsNum<N> operator*(const cEpsNum<N>& g,const double & f) { return f*g; } // ====== operator / ============= template<int N> cEpsNum<N> operator/(const cEpsNum<N>& f, const cEpsNum<N>& g) { return cEpsNum<N>(f.mNum / g.mNum, (f.mEps / g.mNum) - g.mEps *(f.mNum/Square(g.mNum))); } template<int N> cEpsNum<N> Square(const cEpsNum<N>& f) { return cEpsNum<N>(Square(f.mNum) , 2* f.mNum* f.mEps ); } template<int N> cEpsNum<N> Cube(const cEpsNum<N>& f) { return cEpsNum<N>(Cube(f.mNum) , (3*Square(f.mNum)) * f.mEps ); } // = conversion to Sparse template<int N> cVarEpsNum cEpsNum<N>::ToVEN() const { cVarEpsNum aRes(mNum); for (int aK=0 ; aK<N ; aK++) if (mEps[aK]) aRes.AddVal(mEps[aK],aK); return aRes; } // UNARY template<int N> cEpsNum<N> COS(const cEpsNum<N>& f) { return cEpsNum<N>(cos(f.mNum),-sin(f.mNum)*f.mEps); } /* ************************************** */ /* */ /* :: */ /* */ /* ************************************** */ inline double COS(const double & v) {return cos(v);} /** Compute de difference between a sparse jet and a standard jet, used to check the consistency of the jets */ template<int N> double EpsDifference(const cEpsNum<N> & aEps,const cVarEpsNum & aVarEps) { cVarEpsNum::Init(); // take into account the standard value double aRes= std::abs(aEps.mNum - aVarEps.mNum); cEpsNum<N> aEps2; // will be used to convert aVarEps for (unsigned int aK=0 ; aK<aVarEps.mVEps.size() ; aK++) { int aInd = aVarEps.mVInd[aK]; double aVal = aVarEps.mVEps[aK]; if (aInd>=N) // Is over size, do as if value was 0 aRes += std::abs(aVal); else // else put it in the non sparse representation aEps2.mEps[aInd] += aVal; } // now add the difference of value under N for (int aK=0 ; aK<N ; aK++) aRes += std::abs(aEps2.mEps[aK]-aEps.mEps[aK]); return aRes; } }; #endif // _MMVII_Derivatives_H_
[ "marc.pierrot-deseilligny@ensg.eu" ]
marc.pierrot-deseilligny@ensg.eu
dddef7fd157f261b974036d9415c536ba126229b
dd6b6da760c32ac6830c52aa2f4d5cce17e4d408
/magma-2.5.0/src/zsysv_nopiv_gpu.cpp
0dcf2b7bcc035dc4615bf8f16824a4a0b4e3ba12
[]
no_license
uumami/hit_and_run
81584b4f68cf25a2a1140baa3ee88f9e1844b672
dfda812a52bbd65e02753b9abcb9f54aeb4e8184
refs/heads/master
2023-03-13T16:48:37.975390
2023-02-28T05:04:58
2023-02-28T05:04:58
139,909,134
1
0
null
null
null
null
UTF-8
C++
false
false
3,186
cpp
/* -- MAGMA (version 2.5.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date January 2019 @author Adrien REMY @precisions normal z -> c */ #include "magma_internal.h" /***************************************************************************//** Purpose ------- ZSYSV solves a system of linear equations A * X = B where A is an n-by-n symmetric matrix and X and B are n-by-nrhs matrices. The LU decomposition with no pivoting is used to factor A as The factorization has the form A = U^T * D * U, if UPLO = MagmaUpper, or A = L * D * L^T, if UPLO = MagmaLower, where U is an upper triangular matrix, L is lower triangular, and D is a diagonal matrix. The factored form of A is then used to solve the system of equations A * X = B. Arguments --------- @param[in] uplo magma_uplo_t - = MagmaUpper: Upper triangle of A is stored; - = MagmaLower: Lower triangle of A is stored. @param[in] n INTEGER The order of the matrix A. n >= 0. @param[in] nrhs INTEGER The number of right hand sides, i.e., the number of columns of the matrix B. nrhs >= 0. @param[in,out] dA COMPLEX_16 array, dimension (ldda,n). On entry, the n-by-n matrix to be factored. On exit, the factors L and U from the factorization A = L*U; the unit diagonal elements of L are not stored. @param[in] ldda INTEGER The leading dimension of the array A. ldda >= max(1,n). @param[in,out] dB COMPLEX_16 array, dimension (lddb,nrhs) On entry, the right hand side matrix B. On exit, the solution matrix X. @param[in] lddb INTEGER The leading dimension of the array B. lddb >= max(1,n). @param[out] info INTEGER - = 0: successful exit - < 0: if INFO = -i, the i-th argument had an illegal value @ingroup magma_sysv_nopiv *******************************************************************************/ extern "C" magma_int_t magma_zsysv_nopiv_gpu( magma_uplo_t uplo, magma_int_t n, magma_int_t nrhs, magmaDoubleComplex_ptr dA, magma_int_t ldda, magmaDoubleComplex_ptr dB, magma_int_t lddb, magma_int_t *info) { /* Local variables */ bool upper = (uplo == MagmaUpper); /* Check input arguments */ *info = 0; if (! upper && uplo != MagmaLower) { *info = -1; } else if (n < 0) { *info = -2; } else if (nrhs < 0) { *info = -3; } else if (ldda < max(1,n)) { *info = -5; } else if (lddb < max(1,n)) { *info = -7; } if (*info != 0) { magma_xerbla( __func__, -(*info) ); return *info; } /* Quick return if possible */ if (n == 0 || nrhs == 0) { return *info; } magma_zsytrf_nopiv_gpu(uplo, n, dA, ldda, info); if (*info == 0) { magma_zsytrs_nopiv_gpu( uplo, n, nrhs, dA, ldda, dB, lddb, info ); } return *info; }
[ "vazcorm@gmail.com" ]
vazcorm@gmail.com
f9892c8d62de34648a791d1105a3b0521ececbc7
cb9775d90b3e7caa5771107e692d668567716eaf
/Collections/src/Photon.cc
6e409320757a16a2ceafb4c27466777426b23a9f
[]
no_license
lantone/OSUT3Analysis
f97907a863ffafd2ffd35d0c9a35e6db71c29bda
0c2c18c771108e8af0e4edd510744f175fea8aa3
refs/heads/LS1_Upgrade
2021-01-16T20:49:01.023363
2016-02-25T17:05:28
2016-02-25T17:05:28
50,532,292
0
0
null
2016-01-27T19:31:40
2016-01-27T19:31:40
null
UTF-8
C++
false
false
556
cc
#include "OSUT3Analysis/Collections/interface/Photon.h" #if IS_VALID(photons) osu::Photon::Photon () { } osu::Photon::Photon (const TYPE(photons) &photon) : GenMatchable (photon) { } osu::Photon::Photon (const TYPE(photons) &photon, const edm::Handle<vector<osu::Mcparticle> > &particles) : GenMatchable (photon, particles) { } osu::Photon::Photon (const TYPE(photons) &photon, const edm::Handle<vector<osu::Mcparticle> > &particles, const edm::ParameterSet &cfg) : GenMatchable (photon, particles, cfg) { } osu::Photon::~Photon () { } #endif
[ "ahart@cern.ch" ]
ahart@cern.ch
17c814d78f04ef3ef4ad8d77a3e036ed40330049
473fc28d466ddbe9758ca49c7d4fb42e7d82586e
/app/src/main/java/com/syd/source/aosp/system/nvram/hal/memory_storage.cpp
a9568755f8abeb7e2a6e9dbef062d3bbd59f7e5d
[]
no_license
lz-purple/Source
a7788070623f2965a8caa3264778f48d17372bab
e2745b756317aac3c7a27a4c10bdfe0921a82a1c
refs/heads/master
2020-12-23T17:03:12.412572
2020-01-31T01:54:37
2020-01-31T01:54:37
237,205,127
4
2
null
null
null
null
UTF-8
C++
false
false
2,743
cpp
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <nvram/core/storage.h> namespace nvram { namespace storage { namespace { // Maximum number of space blobs supported. const int kMaxSpaces = 32; class StorageSlot { public: bool present() const { return blob_.size() != 0; } Status Load(Blob* blob) const { if (blob_.size() == 0) { return Status::kNotFound; } if (!blob->Assign(blob_.data(), blob_.size())) { return Status::kStorageError; } return Status::kSuccess; } Status Store(const Blob& blob) { if (!blob_.Assign(blob.data(), blob.size())) { return Status::kStorageError; } return Status::kSuccess; } Status Delete() { return blob_.Resize(0) ? Status::kSuccess : Status::kStorageError; } private: Blob blob_; }; // Stores the header blob. StorageSlot g_header; // Stores the space blobs. struct { uint32_t index; StorageSlot slot; } g_spaces[kMaxSpaces]; // Find the storage slot in |g_spaces| that corresponds to |index|. Returns // |nullptr| if no matching slot exists. StorageSlot* FindSpaceSlot(uint32_t index) { for (size_t i = 0; i < kMaxSpaces; ++i) { if (g_spaces[i].slot.present() && g_spaces[i].index == index) { return &g_spaces[i].slot; } } return nullptr; } } // namespace Status LoadHeader(Blob* blob) { return g_header.Load(blob); } Status StoreHeader(const Blob& blob) { return g_header.Store(blob); } Status LoadSpace(uint32_t index, Blob* blob) { StorageSlot* slot = FindSpaceSlot(index); return slot ? slot->Load(blob) : Status::kNotFound; } Status StoreSpace(uint32_t index, const Blob& blob) { StorageSlot* slot = FindSpaceSlot(index); if (slot) { return slot->Store(blob); } // Allocate a new slot. for (size_t i = 0; i < kMaxSpaces; ++i) { if (!g_spaces[i].slot.present()) { g_spaces[i].index = index; return g_spaces[i].slot.Store(blob); } } return Status::kStorageError; } Status DeleteSpace(uint32_t index) { StorageSlot* slot = FindSpaceSlot(index); if (slot) { slot->Delete(); } return Status::kSuccess; } } // namespace storage } // namespace nvram
[ "997530783@qq.com" ]
997530783@qq.com
4cd2d1fa3826781ca987afafc89c0577ed523ff4
bd72991991f999ffc721e7ff51099312e10bbab3
/XPFace/Include/modulver.h
f63ffc9221c0be1bd6b6a21578c33babe60cc0ec
[]
no_license
alexfordc/my-st-king
1c36ddc7830817ea007f81f565579a01045b4b8e
8ffd0df93fb067013abcd808c24c23a068523ab7
refs/heads/master
2021-05-31T21:01:12.028462
2011-10-03T15:08:12
2011-10-03T15:08:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,003
h
//////////////////////////////////////////////////////////////// // 1998 Microsoft Systems Journal // // If this code works, it was written by Paul DiLascia. // If not, I don't know who wrote it. // #if !defined(MODULVER_H_INCLUDED) #define MODULVER_H_INCLUDED #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // tell linker to link with version.lib for VerQueryValue, etc. #pragma comment(linker, "/defaultlib:version.lib") #ifndef DLLVERSIONINFO // following is from shlwapi.h, in November 1997 release of the Windows SDK /* typedef struct _DllVersionInfo { DWORD cbSize; DWORD dwMajorVersion; // Major version DWORD dwMinorVersion; // Minor version DWORD dwBuildNumber; // Build number DWORD dwPlatformID; // DLLVER_PLATFORM_* } DLLVERSIONINFO; // Platform IDs for DLLVERSIONINFO #define DLLVER_PLATFORM_WINDOWS 0x00000001 // Windows 95 #define DLLVER_PLATFORM_NT 0x00000002 // Windows NT */ #endif // DLLVERSIONINFO ////////////////// // CModuleVersion version info about a module. // To use: // // CModuleVersion ver // if (ver.GetFileVersionInfo("_T("mymodule))) { // // info is in ver, you can call GetValue to get variable info like // CString s = ver.GetValue(_T("CompanyName")); // } // // You can also call the static fn DllGetVersion to get DLLVERSIONINFO. // class CLASS_EXPORT CModuleVersion : public VS_FIXEDFILEINFO { protected: BYTE* m_pVersionInfo; // all version info struct TRANSLATION { WORD langID; // language ID WORD charset; // character set (code page) } m_translation; public: CModuleVersion(); virtual ~CModuleVersion(); BOOL GetFileVersionInfo(LPCTSTR modulename); CString GetValue(LPCTSTR lpKeyName); static BOOL DllGetVersion(LPCTSTR modulename, DLLVERSIONINFO& dvi); static int GetModuleVer(CString cs); }; #endif
[ "lchao5424@gmail.com" ]
lchao5424@gmail.com
06f9ed92e397744452fa0b4a5c4e2532f4679ee9
5deed79671d43661010a0f3a68fd8e887b4a3eda
/Combinatronics/ChocolateFiesta.cpp
7107da81322677b40b13144d08fb711d89d029bf
[]
no_license
cpt-r3tr0/mathematics
ca449a493a8dc34c78ef5b7ede9646879a5597ad
969e10ca2d4a2ab9b309b19294e481dae4c96994
refs/heads/master
2020-04-08T22:08:36.636989
2019-01-31T11:25:45
2019-01-31T11:25:45
159,773,870
0
0
null
null
null
null
UTF-8
C++
false
false
675
cpp
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #define M 1000000007 using namespace std; int n; int a[100005]; long long dp[100005][2]; long long f(int idx, int flag) { if ( idx == n ) { if ( !flag ) return 1; return 0; } long long &ans = dp[idx][flag]; if ( ans != -1 ) return ans; ans = 0; ans += f(idx+1,flag)%M; ans %= M; ans += f(idx+1, (flag+a[idx])%2)%M; ans %= M; return ans; } int main() { cin >> n; for ( int i = 0; i < n; i++ ) cin >> a[i]; memset(dp, -1, sizeof(dp)); long long ans = f(0,0); ans = (ans-1)%M; cout << ans << endl; return 0; }
[ "rbordiya22@hotmail.com" ]
rbordiya22@hotmail.com
fd2efb92f6aa59afbde81c6a5927ca32c2232aa3
e21ec0dd8153cb67d4832c5a938f48c35d4ab3ae
/chrome/browser/chromeos/app_mode/kiosk_external_updater.cc
aac2d075dc477ee73d3c77dbf128815e17fbb6aa
[ "BSD-3-Clause" ]
permissive
xiaowei0828/chromium
e65c8c2fbf2060c46334fc33f98a0ad98706f97c
5167a68813ef5edb1445e205e5489059285e3885
refs/heads/master
2023-02-21T13:03:51.224567
2017-06-27T23:19:35
2017-06-27T23:19:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,360
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/app_mode/kiosk_external_updater.h" #include "base/bind.h" #include "base/files/file_enumerator.h" #include "base/files/file_util.h" #include "base/json/json_file_value_serializer.h" #include "base/location.h" #include "base/logging.h" #include "base/strings/utf_string_conversions.h" #include "base/version.h" #include "chrome/browser/chromeos/app_mode/kiosk_app_manager.h" #include "chrome/browser/chromeos/ui/kiosk_external_update_notification.h" #include "chrome/grit/generated_resources.h" #include "components/version_info/version_info.h" #include "content/public/browser/browser_thread.h" #include "extensions/browser/sandboxed_unpacker.h" #include "extensions/common/extension.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" namespace chromeos { namespace { const char kExternalUpdateManifest[] = "external_update.json"; const char kExternalCrx[] = "external_crx"; const char kExternalVersion[] = "external_version"; void ParseExternalUpdateManifest( const base::FilePath& external_update_dir, base::DictionaryValue* parsed_manifest, KioskExternalUpdater::ExternalUpdateErrorCode* error_code) { base::FilePath manifest = external_update_dir.AppendASCII(kExternalUpdateManifest); if (!base::PathExists(manifest)) { *error_code = KioskExternalUpdater::ERROR_NO_MANIFEST; return; } JSONFileValueDeserializer deserializer(manifest); std::string error_msg; base::Value* extensions = deserializer.Deserialize(NULL, &error_msg).release(); // TODO(Olli Raula) possible memory leak http://crbug.com/543015 if (!extensions) { *error_code = KioskExternalUpdater::ERROR_INVALID_MANIFEST; return; } base::DictionaryValue* dict_value = NULL; if (!extensions->GetAsDictionary(&dict_value)) { *error_code = KioskExternalUpdater::ERROR_INVALID_MANIFEST; return; } parsed_manifest->Swap(dict_value); *error_code = KioskExternalUpdater::ERROR_NONE; } // Copies |external_crx_file| to |temp_crx_file|, and removes |temp_dir| // created for unpacking |external_crx_file|. void CopyExternalCrxAndDeleteTempDir(const base::FilePath& external_crx_file, const base::FilePath& temp_crx_file, const base::FilePath& temp_dir, bool* success) { base::DeleteFile(temp_dir, true); *success = base::CopyFile(external_crx_file, temp_crx_file); } // Returns true if |version_1| < |version_2|, and // if |update_for_same_version| is true and |version_1| = |version_2|. bool ShouldUpdateForHigherVersion(const std::string& version_1, const std::string& version_2, bool update_for_same_version) { const base::Version v1(version_1); const base::Version v2(version_2); if (!v1.IsValid() || !v2.IsValid()) return false; int compare_result = v1.CompareTo(v2); if (compare_result < 0) return true; else if (update_for_same_version && compare_result == 0) return true; else return false; } } // namespace KioskExternalUpdater::ExternalUpdate::ExternalUpdate() { } KioskExternalUpdater::ExternalUpdate::ExternalUpdate( const ExternalUpdate& other) = default; KioskExternalUpdater::ExternalUpdate::~ExternalUpdate() { } KioskExternalUpdater::KioskExternalUpdater( const scoped_refptr<base::SequencedTaskRunner>& backend_task_runner, const base::FilePath& crx_cache_dir, const base::FilePath& crx_unpack_dir) : backend_task_runner_(backend_task_runner), crx_cache_dir_(crx_cache_dir), crx_unpack_dir_(crx_unpack_dir), weak_factory_(this) { // Subscribe to DiskMountManager. DCHECK(disks::DiskMountManager::GetInstance()); disks::DiskMountManager::GetInstance()->AddObserver(this); } KioskExternalUpdater::~KioskExternalUpdater() { if (disks::DiskMountManager::GetInstance()) disks::DiskMountManager::GetInstance()->RemoveObserver(this); } void KioskExternalUpdater::OnDiskEvent( disks::DiskMountManager::DiskEvent event, const disks::DiskMountManager::Disk* disk) { } void KioskExternalUpdater::OnDeviceEvent( disks::DiskMountManager::DeviceEvent event, const std::string& device_path) { } void KioskExternalUpdater::OnMountEvent( disks::DiskMountManager::MountEvent event, MountError error_code, const disks::DiskMountManager::MountPointInfo& mount_info) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (mount_info.mount_type != MOUNT_TYPE_DEVICE || error_code != MOUNT_ERROR_NONE) { return; } if (event == disks::DiskMountManager::MOUNTING) { // If multiple disks have been mounted, skip the rest of them if kiosk // update has already been found. if (!external_update_path_.empty()) { LOG(WARNING) << "External update path already found, skip " << mount_info.mount_path; return; } base::DictionaryValue* parsed_manifest = new base::DictionaryValue(); ExternalUpdateErrorCode* parsing_error = new ExternalUpdateErrorCode; backend_task_runner_->PostTaskAndReply( FROM_HERE, base::Bind(&ParseExternalUpdateManifest, base::FilePath(mount_info.mount_path), parsed_manifest, parsing_error), base::Bind(&KioskExternalUpdater::ProcessParsedManifest, weak_factory_.GetWeakPtr(), base::Owned(parsing_error), base::FilePath(mount_info.mount_path), base::Owned(parsed_manifest))); } else { // unmounting a removable device. if (external_update_path_.value().empty()) { // Clear any previously displayed message. DismissKioskUpdateNotification(); } else if (external_update_path_.value() == mount_info.mount_path) { DismissKioskUpdateNotification(); if (IsExternalUpdatePending()) { LOG(ERROR) << "External kiosk update is not completed when the usb " "stick is unmoutned."; } external_updates_.clear(); external_update_path_.clear(); } } } void KioskExternalUpdater::OnFormatEvent( disks::DiskMountManager::FormatEvent event, FormatError error_code, const std::string& device_path) { } void KioskExternalUpdater::OnExtenalUpdateUnpackSuccess( const std::string& app_id, const std::string& version, const std::string& min_browser_version, const base::FilePath& temp_dir) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // User might pull out the usb stick before updating is completed. if (CheckExternalUpdateInterrupted()) return; if (!ShouldDoExternalUpdate(app_id, version, min_browser_version)) { external_updates_[app_id].update_status = FAILED; MaybeValidateNextExternalUpdate(); return; } // User might pull out the usb stick before updating is completed. if (CheckExternalUpdateInterrupted()) return; base::FilePath external_crx_path = external_updates_[app_id].external_crx.path; base::FilePath temp_crx_path = crx_unpack_dir_.Append(external_crx_path.BaseName()); bool* success = new bool; backend_task_runner_->PostTaskAndReply( FROM_HERE, base::Bind(&CopyExternalCrxAndDeleteTempDir, external_crx_path, temp_crx_path, temp_dir, success), base::Bind(&KioskExternalUpdater::PutValidatedExtension, weak_factory_.GetWeakPtr(), base::Owned(success), app_id, temp_crx_path, version)); } void KioskExternalUpdater::OnExternalUpdateUnpackFailure( const std::string& app_id) { // User might pull out the usb stick before updating is completed. if (CheckExternalUpdateInterrupted()) return; external_updates_[app_id].update_status = FAILED; external_updates_[app_id].error = ui::ResourceBundle::GetSharedInstance().GetLocalizedString( IDS_KIOSK_EXTERNAL_UPDATE_BAD_CRX); MaybeValidateNextExternalUpdate(); } void KioskExternalUpdater::ProcessParsedManifest( ExternalUpdateErrorCode* parsing_error, const base::FilePath& external_update_dir, base::DictionaryValue* parsed_manifest) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (*parsing_error == ERROR_NO_MANIFEST) { KioskAppManager::Get()->OnKioskAppExternalUpdateComplete(false); return; } else if (*parsing_error == ERROR_INVALID_MANIFEST) { NotifyKioskUpdateProgress( ui::ResourceBundle::GetSharedInstance().GetLocalizedString( IDS_KIOSK_EXTERNAL_UPDATE_INVALID_MANIFEST)); KioskAppManager::Get()->OnKioskAppExternalUpdateComplete(false); return; } NotifyKioskUpdateProgress( ui::ResourceBundle::GetSharedInstance().GetLocalizedString( IDS_KIOSK_EXTERNAL_UPDATE_IN_PROGRESS)); external_update_path_ = external_update_dir; for (base::DictionaryValue::Iterator it(*parsed_manifest); !it.IsAtEnd(); it.Advance()) { std::string app_id = it.key(); std::string cached_version_str; base::FilePath cached_crx; if (!KioskAppManager::Get()->GetCachedCrx( app_id, &cached_crx, &cached_version_str)) { LOG(WARNING) << "Can't find app in existing cache " << app_id; continue; } const base::DictionaryValue* extension = NULL; if (!it.value().GetAsDictionary(&extension)) { LOG(ERROR) << "Found bad entry in manifest type " << it.value().GetType(); continue; } std::string external_crx_str; if (!extension->GetString(kExternalCrx, &external_crx_str)) { LOG(ERROR) << "Can't find external crx in manifest " << app_id; continue; } std::string external_version_str; if (extension->GetString(kExternalVersion, &external_version_str)) { if (!ShouldUpdateForHigherVersion( cached_version_str, external_version_str, false)) { LOG(WARNING) << "External app " << app_id << " is at the same or lower version comparing to " << " the existing one."; continue; } } ExternalUpdate update; KioskAppManager::App app; if (KioskAppManager::Get()->GetApp(app_id, &app)) { update.app_name = app.name; } else { NOTREACHED(); } update.external_crx = extensions::CRXFileInfo( app_id, external_update_path_.AppendASCII(external_crx_str)); update.update_status = PENDING; external_updates_[app_id] = update; } if (external_updates_.empty()) { NotifyKioskUpdateProgress( ui::ResourceBundle::GetSharedInstance().GetLocalizedString( IDS_KIOSK_EXTERNAL_UPDATE_NO_UPDATES)); KioskAppManager::Get()->OnKioskAppExternalUpdateComplete(false); return; } ValidateExternalUpdates(); } bool KioskExternalUpdater::CheckExternalUpdateInterrupted() { if (external_updates_.empty()) { // This could happen if user pulls out the usb stick before the updating // operation is completed. LOG(ERROR) << "external_updates_ has been cleared before external " << "updating completes."; return true; } return false; } void KioskExternalUpdater::ValidateExternalUpdates() { for (ExternalUpdateMap::iterator it = external_updates_.begin(); it != external_updates_.end(); ++it) { if (it->second.update_status == PENDING) { scoped_refptr<KioskExternalUpdateValidator> crx_validator = new KioskExternalUpdateValidator(backend_task_runner_, it->second.external_crx, crx_unpack_dir_, weak_factory_.GetWeakPtr()); crx_validator->Start(); break; } } } bool KioskExternalUpdater::IsExternalUpdatePending() { for (ExternalUpdateMap::iterator it = external_updates_.begin(); it != external_updates_.end(); ++it) { if (it->second.update_status == PENDING) { return true; } } return false; } bool KioskExternalUpdater::IsAllExternalUpdatesSucceeded() { for (ExternalUpdateMap::iterator it = external_updates_.begin(); it != external_updates_.end(); ++it) { if (it->second.update_status != SUCCESS) { return false; } } return true; } bool KioskExternalUpdater::ShouldDoExternalUpdate( const std::string& app_id, const std::string& version, const std::string& min_browser_version) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); std::string existing_version_str; base::FilePath existing_path; bool cached = KioskAppManager::Get()->GetCachedCrx( app_id, &existing_path, &existing_version_str); DCHECK(cached); // Compare app version. ui::ResourceBundle* rb = &ui::ResourceBundle::GetSharedInstance(); if (!ShouldUpdateForHigherVersion(existing_version_str, version, false)) { external_updates_[app_id].error = rb->GetLocalizedString( IDS_KIOSK_EXTERNAL_UPDATE_SAME_OR_LOWER_APP_VERSION); return false; } // Check minimum browser version. if (!min_browser_version.empty()) { if (!ShouldUpdateForHigherVersion(min_browser_version, version_info::GetVersionNumber(), true)) { external_updates_[app_id].error = l10n_util::GetStringFUTF16( IDS_KIOSK_EXTERNAL_UPDATE_REQUIRE_HIGHER_BROWSER_VERSION, base::UTF8ToUTF16(min_browser_version)); return false; } } return true; } void KioskExternalUpdater::PutValidatedExtension(bool* crx_copied, const std::string& app_id, const base::FilePath& crx_file, const std::string& version) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (CheckExternalUpdateInterrupted()) return; if (!*crx_copied) { LOG(ERROR) << "Cannot copy external crx file to " << crx_file.value(); external_updates_[app_id].update_status = FAILED; external_updates_[app_id].error = l10n_util::GetStringFUTF16( IDS_KIOSK_EXTERNAL_UPDATE_FAILED_COPY_CRX_TO_TEMP, base::UTF8ToUTF16(crx_file.value())); MaybeValidateNextExternalUpdate(); return; } chromeos::KioskAppManager::Get()->PutValidatedExternalExtension( app_id, crx_file, version, base::Bind(&KioskExternalUpdater::OnPutValidatedExtension, weak_factory_.GetWeakPtr())); } void KioskExternalUpdater::OnPutValidatedExtension(const std::string& app_id, bool success) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (CheckExternalUpdateInterrupted()) return; if (!success) { external_updates_[app_id].update_status = FAILED; external_updates_[app_id].error = l10n_util::GetStringFUTF16( IDS_KIOSK_EXTERNAL_UPDATE_CANNOT_INSTALL_IN_LOCAL_CACHE, base::UTF8ToUTF16(external_updates_[app_id].external_crx.path.value())); } else { external_updates_[app_id].update_status = SUCCESS; } // Validate the next pending external update. MaybeValidateNextExternalUpdate(); } void KioskExternalUpdater::MaybeValidateNextExternalUpdate() { if (IsExternalUpdatePending()) ValidateExternalUpdates(); else MayBeNotifyKioskAppUpdate(); } void KioskExternalUpdater::MayBeNotifyKioskAppUpdate() { if (IsExternalUpdatePending()) return; NotifyKioskUpdateProgress(GetUpdateReportMessage()); NotifyKioskAppUpdateAvailable(); KioskAppManager::Get()->OnKioskAppExternalUpdateComplete( IsAllExternalUpdatesSucceeded()); } void KioskExternalUpdater::NotifyKioskAppUpdateAvailable() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); for (ExternalUpdateMap::iterator it = external_updates_.begin(); it != external_updates_.end(); ++it) { if (it->second.update_status == SUCCESS) { KioskAppManager::Get()->OnKioskAppCacheUpdated(it->first); } } } void KioskExternalUpdater::NotifyKioskUpdateProgress( const base::string16& message) { if (!notification_) notification_.reset(new KioskExternalUpdateNotification(message)); else notification_->ShowMessage(message); } void KioskExternalUpdater::DismissKioskUpdateNotification() { if (notification_.get()) { notification_.reset(); } } base::string16 KioskExternalUpdater::GetUpdateReportMessage() { DCHECK(!IsExternalUpdatePending()); int updated = 0; int failed = 0; base::string16 updated_apps; base::string16 failed_apps; for (ExternalUpdateMap::iterator it = external_updates_.begin(); it != external_updates_.end(); ++it) { base::string16 app_name = base::UTF8ToUTF16(it->second.app_name); if (it->second.update_status == SUCCESS) { ++updated; if (updated_apps.empty()) updated_apps = app_name; else updated_apps = updated_apps + base::ASCIIToUTF16(", ") + app_name; } else { // FAILED ++failed; if (failed_apps.empty()) { failed_apps = app_name + base::ASCIIToUTF16(": ") + it->second.error; } else { failed_apps = failed_apps + base::ASCIIToUTF16("\n") + app_name + base::ASCIIToUTF16(": ") + it->second.error; } } } base::string16 message; message = ui::ResourceBundle::GetSharedInstance().GetLocalizedString( IDS_KIOSK_EXTERNAL_UPDATE_COMPLETE); base::string16 success_app_msg; if (updated) { success_app_msg = l10n_util::GetStringFUTF16( IDS_KIOSK_EXTERNAL_UPDATE_SUCCESSFUL_UPDATED_APPS, updated_apps); message = message + base::ASCIIToUTF16("\n") + success_app_msg; } base::string16 failed_app_msg; if (failed) { failed_app_msg = ui::ResourceBundle::GetSharedInstance().GetLocalizedString( IDS_KIOSK_EXTERNAL_UPDATE_FAILED_UPDATED_APPS) + base::ASCIIToUTF16("\n") + failed_apps; message = message + base::ASCIIToUTF16("\n") + failed_app_msg; } return message; } } // namespace chromeos
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
fd7290656d2e6b1ca1974cefaa1eef275f6d122f
e5f1e6f2d822a83863e5a8893abb96dda6435697
/src/main.cpp
fe32661b13e21183b64f0bc07dc5ffa8ebefbdd4
[]
no_license
maxlund/minion-massacre
39187bd44c7ae43b6e9382717c1d0f48a78e3388
30f2c4356927cb2787bacdd8410fadfa35d24ae8
refs/heads/master
2021-09-07T03:22:48.736182
2018-02-16T14:30:17
2018-02-16T14:30:17
103,815,197
0
1
null
2018-01-29T13:31:18
2017-09-17T08:48:02
C++
UTF-8
C++
false
false
1,128
cpp
#include <SFML/Window.hpp> #include <SFML/Graphics.hpp> #include <iostream> #include "Level.h" #include "ResourceManager.h" #include "Game.h" using namespace std; std::map<std::string, sf::Texture*> ResourceManager::textures{}; std::map<std::string, sf::Font*> ResourceManager::fonts{}; std::map<std::string, sf::Shader*> ResourceManager::shaders{}; sf::Vector2f mouseTileCoordinates(sf::RenderWindow&, const Level&); Level Game::level{"../res/level.tmx"}; int main() { // sf::RenderWindow window{/*sf::VideoMode::getFullscreenModes().at(0) */ sf::VideoMode(840, 640), "Tower Defense" /* sf::Style::Fullscreen */}; sf::RenderWindow window{sf::VideoMode::getDesktopMode(), "Tower Defense"/*, sf::Style::Fullscreen*/}; Game game{window}; sf::Vector2f levelSize{static_cast<float>(Game::getLevel().getWidth()), static_cast<float>(Game::getLevel().getHeight())}; float viewWidth = window.getSize().x * (levelSize.y / window.getSize().y); sf::FloatRect viewRect = sf::FloatRect(-(viewWidth - levelSize.x) / 2, 0, viewWidth, levelSize.y); game.setViewRect(viewRect); game.run(); return 0; }
[ "maxlu701@student.liu.se" ]
maxlu701@student.liu.se
99c1402f79b7b77f4ae8c8ce96aa2a2d4b5e892e
4476dd05f9be3b80d95037d49f6b52c1569ab27b
/104/104.cc
765232e101aad15a953f220e939f1a786eea9b8d
[]
no_license
haampie/project-euler
481e55815c42a0252cac5fddb18da78757a45665
000dc0a4b58a001b9538b7782fcf5098d509d76e
refs/heads/master
2021-01-04T02:31:55.545112
2018-11-09T18:57:15
2018-11-09T18:57:15
71,645,124
0
0
null
null
null
null
UTF-8
C++
false
false
2,190
cc
#include <vector> #include <iostream> #include <iterator> // base 10 class UnsignedBigNum { std::vector<uint8_t> _digits; friend std::ostream &operator<<(std::ostream &, UnsignedBigNum const&); public: explicit UnsignedBigNum(uint8_t v) : _digits{v} {} UnsignedBigNum &operator+=(UnsignedBigNum const &rhs) { if (_digits.size() < rhs._digits.size()) _digits.resize(rhs._digits.size(), 0); for (size_t idx = 0; idx < rhs._digits.size(); ++idx) _digits[idx] += rhs._digits[idx]; overflow(); return *this; } std::vector<uint8_t> const &digits() const { return _digits; } private: void overflow() { for (size_t idx = 0; idx < _digits.size(); ++idx) { if (_digits[idx] >= 10) { auto d = _digits[idx] / 10; _digits[idx] %= 10; if (idx + 1 == _digits.size()) _digits.push_back(d); else _digits[idx + 1] += d; } } } }; std::ostream &operator<<(std::ostream &os, UnsignedBigNum const &bn) { std::copy(bn._digits.rbegin(), bn._digits.rend(), std::ostream_iterator<size_t>(os, "")); return os; } template<class T> bool is_pandigit(T begin, T end) { if (end - begin < 9) return false; std::vector<bool> table(10, false); for (T p = begin; p != begin + 9; ++p) { if (*p == 0 || table[*p]) return false; table[*p] = true; } return true; } int main() { UnsignedBigNum prev(0); UnsignedBigNum curr(1); // found 329468 after running it for a while for (size_t n = 2; n <= 329'468; ++n) { auto tmp = curr; curr += prev; prev = tmp; std::vector<uint8_t> const &digits = curr.digits(); auto front = is_pandigit(digits.begin(), digits.end()); auto back = is_pandigit(digits.rbegin(), digits.rend()); if (front && back) { std::cout << n << '(' << digits.size() << " digits):\n" << curr << '\n'; break; } } }
[ "harmenstoppels@gmail.com" ]
harmenstoppels@gmail.com
382506234d915cc84b5222f402dcb3384b9c71de
3bc8ac57b6244288bfdeadc37b7ec7cb7225ae76
/ZUpdater/ZUpdater.h
7496d9e5758571182f7c4ee94890698fc00dc9d0
[]
no_license
Helical-Games/ZPatcher
713c9634ae32691316f6e5f511ff4a44dea3562a
53ddaa4234e505aa97d084533b4071e42775aaec
refs/heads/master
2021-01-20T17:54:17.714674
2016-06-01T09:13:33
2016-06-01T09:13:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,236
h
////////////////////////////////////////////////////////////////////////// // // ZPatcher - Patcher system - Part of the ZUpdater suite // Felipe "Zoc" Silveira - (c) 2016 // ////////////////////////////////////////////////////////////////////////// // // DownloadFileWriter.h // Class to download a file from an URL and save to disk // ////////////////////////////////////////////////////////////////////////// #ifndef _ZUPDATER_H_ #define _ZUPDATER_H_ #include <vector> #include <string> #ifdef _WIN32 #include <windows.h> #endif // !_WIN32 // Lets avoid adding an unnecessary header here. typedef unsigned long DWORD; namespace ZUpdater { struct Patch { uint64_t sourceBuildNumber; uint64_t targetBuildNumber; std::string fileURL; DWORD fileLength; std::string fileMD5; }; /** * Download the Update XML from the server and process it. The output is stored in g_Patches. * Returns if file was downloaded and processed successfully */ bool CheckForUpdates(const std::string& updateURL, const uint64_t& currentBuildNumber); /** * Returns g_LatestVersion. */ uint64_t GetLatestVersion(); /** * With all the patches stored in g_Patches, find the best path to download updates, using the file download size as the value that should be minimized. * Returns true if there is a path from the source version to the target version (i.e. if the update is possible) */ bool GetSmallestUpdatePath(const uint64_t& sourceBuildNumber, const uint64_t& targetBuildNumber, std::vector<unsigned int>& path, uint64_t& pathFileSize); /** * */ bool DownloadAndApplyPatch(std::string targetDirectory, std::string targetVersionFile, uint64_t targetCurrentVersion); /** * Returns true if it was able to determine the current version stored in configFile. * The found version is returned in the "version" variable. * NOTE: If no file is found, it returns true and version gets the value 0 (i.e. No previous version found, perform full instalation) */ bool GetTargetCurrentVersion(const std::string& configFile, uint64_t& version); /** * Updates given configFile to store the supplied version */ bool SaveTargetNewVersion(const std::string& configFile, const uint64_t& version); /** * Calculate the MD5 hash of a file */ std::string MD5File(std::string fileName); /** * Download file, from given URL, without renaming, to given targetPath. * Note: The filename to be saved is the last part (i.e. after last slash) of given URL. Complex URLs might be a problem for this function. */ bool SimpleDownloadFile(const std::string& URL, const std::string& targetPath = "./"); ////////////////////////////////////////////////////////////////////////// // Windows specific stuff /** * If the updater finds a file with it's own name with an appended 'a' character (e.g. For Zupdater.exe, searches for ZUpdatera.exe), * it will replace itself with the updated found version and restart the application. * it will return true if no write error happened. * Please note, YOU (yes, you!) need to explicitly finish the application after calling this function and it returns updateFound == true */ bool SelfUpdate(bool &updateFound); } #endif
[ "TheZoc@users.noreply.github.com" ]
TheZoc@users.noreply.github.com
ec3cf673e2643b3e6f8c364aff863685b5878f6d
9f2a50ca987db8ac1cedd14bbd78636b9dfe74ed
/functor.h
fb86aea909f0968c347865514c1b1c734cb40b5f
[]
no_license
ponasenko-rs/metaprogramming-seminars
e5b1f8319f758798ce7493d1ff0e80b317542aef
99d880cb30274c06bccc4471d19ccd31d63431c6
refs/heads/main
2023-02-03T20:00:19.468356
2020-12-24T12:03:06
2020-12-24T12:03:06
320,255,606
0
0
null
null
null
null
UTF-8
C++
false
false
2,066
h
#pragma once #include <memory> #include "typelist.h" #include "tuple.h" namespace functor { template <int args_left, typename Result, typename Tuple, typename Invoker, typename... CollectedArgs> traits::EnableIfT<args_left != 0, Result> InvokeTupleArgs(Invoker invoker, Tuple tuple, CollectedArgs... args) { return InvokeTupleArgs<args_left - 1, Result>(invoker, tuple, tuple::TupleGet<args_left - 1>(tuple), args...); } template <int args_left, typename Result, typename Tuple, typename Invoker, typename... CollectedArgs> traits::EnableIfT<args_left == 0, Result> InvokeTupleArgs(Invoker invoker, Tuple tuple, CollectedArgs... args) { return invoker->invoke(args...); } template <typename Result, typename FunctionType> struct FreeFunctionHolder { template <typename... CallArgs> Result operator()(CallArgs... args) { return function(args...); } FreeFunctionHolder(FunctionType function) : function(function) { } template <typename... CallArgs> Result invoke(CallArgs... args) { return operator()(args...); } FunctionType function; }; template <typename FunctionType, typename... Args> class Functor { using Tuple = tuple::Tuple<Args...>; using Result = traits::GetFunctionResultTypeT<FunctionType>; using Invoker = std::shared_ptr<FreeFunctionHolder<Result, FunctionType>>; public: Functor(FunctionType func, Args... args) : invoker(new FreeFunctionHolder<Result, FunctionType>(func)) { tuple::TupleAssign<0>(tuple, args...); } template <typename... CallArgs> Result operator()(CallArgs... args) { return InvokeTupleArgs<accepted_args_length, Result>(invoker, tuple, args...); } private: Tuple tuple; static constexpr int accepted_args_length = typelist::LengthV<typelist::TypeList<Args...>>; Invoker invoker; }; } // namespace functor
[ "rs.ponasenko@gmail.com" ]
rs.ponasenko@gmail.com
e2a292235f3d42bb9c5fc399cf88e8d3c5cbd255
a382d4cda847abc976a7525fbb8399ab7a5de3bd
/include/Renderers/Ogre/EventHandler.h
a18c6d100815be8ce34144e2c8aadf4fe78904e1
[ "MIT" ]
permissive
vkalpias/Karazeh
6d29a7444225fcadb6abe5cfdd911f3ef999d9b6
e7f80849c855545934b5e595847b3d13f77eb1da
refs/heads/master
2021-01-24T01:04:58.269802
2011-09-08T08:53:53
2011-09-08T08:53:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,848
h
/* * Copyright (c) 2011 Ahmad Amireh <ahmad@amireh.net> * * 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 H_EventHandler_H #define H_EventHandler_H #include <iostream> #include <utility> #include "Handler.h" namespace Pixy { class Event; /*! \class EventHandler * * \brief * Functionoid encapsulating event handling methods * * \note * You should never need to create, call, or register an EventHandler * directly. Use EventListener for binding instead. */ template < class T, class EventType > class EventHandler : public Handler { public: typedef bool (T::*methodPtr)(EventType*); //! ctor inline EventHandler(T* inInstance, methodPtr inMethod) : mClassInstance(inInstance), mMethod(inMethod) { }; //! dtor inline virtual ~EventHandler() { mClassInstance = NULL; mMethod = NULL; }; /*! * \brief * Responsible of calling the appropriate handler method of the subscriber. * * \remarks * Depending on the EventType, call() will be able to determine on runtime * the proper registered method to call. * * \note * This method is called internally by Pixy::EventHandler * and should not be called directly. */ inline virtual bool call(Event* inEvt) { return ((*mClassInstance).*mMethod)(static_cast<EventType*>(inEvt)); }; protected: T* mClassInstance; methodPtr mMethod; }; } #endif // H_EventHandler_H
[ "ahmad.amireh@gmail.com" ]
ahmad.amireh@gmail.com
a43f89b91392cfcb716b4b2afb514d691aa0dc62
16b1f5629d580586273b7b88491289beb37eb6cd
/src/version.cpp
dfa70f9aa61551b0df9219151b4ff396a98f1566
[ "MIT" ]
permissive
degarashi/sprinkler
b88095629ca493f168253ae6c5e4b57b6f1e52b6
afc6301ae2c7185f514148100da63dcef94d7f00
refs/heads/master
2020-03-30T01:36:10.479283
2019-03-13T09:37:32
2019-03-13T09:37:32
150,584,179
0
0
null
null
null
null
UTF-8
C++
false
false
1,688
cpp
#include "version.hpp" #include "table_desc.hpp" #include "sql/query.hpp" #include "sql/getvalue.hpp" #include <QSettings> namespace dg { std::string Version::asString() const { return std::to_string(major) + "." + std::to_string(minor) + "." + std::to_string(release) ; } namespace { const QString ver_major("major"), ver_minor("minor"), ver_release("release"), ver_db("version"); } VersionOpt Version::Read(const QSettings& s) { bool ok[3]; const Version ret{ s.value(ver_major).toUInt(ok), s.value(ver_minor).toUInt(ok +1), s.value(ver_release).toUInt(ok +2) }; if(!(ok[0] & ok[1] & ok[2])) return std::nullopt; return ret; } void Version::write(QSettings& s) const { s.setValue(ver_major, major); s.setValue(ver_minor, minor); s.setValue(ver_release, release); } Version::Num Version::ReadFromDB() { if(const auto num = sql::GetValue<Num>( sql::Query( "SELECT " Stg_value " FROM " Setting_Table " WHERE " Stg_key "=?", ver_db ) )) return *num; // 何も記録されてない時は0を返す return 0; } void Version::WriteToDB() { sql::Query( "REPLACE INTO " Setting_Table " VALUES(?,?)", ver_db, DBVersion() ); } Version Version::ThisVersion() noexcept { Version ret; ret.major = 0; ret.minor = 1; ret.release = 6; return ret; } Version::Num Version::DBVersion() noexcept { return 2; } bool Version::operator < (const Version& v) const noexcept { return std::lexicographical_compare( array.begin(), array.end(), v.array.begin(), v.array.end() ); } bool Version::operator == (const Version& v) const noexcept { return array == v.array; } }
[ "slice013@gmail.com" ]
slice013@gmail.com
b200bb4bdcb5866d6473f9954518a49c7126e7e4
a772c6fcd17f431607a58df7a6cd34873a7e5815
/code - 20210906/TypeModbusDlg.h
172c8ae3b8186b97fdb8342ff987acdea4ba51fb
[]
no_license
wanglvhh/VisionProject
43624c8728b6ab3812a536d2a3927be5cd62393f
ce9a3d4b5342fa9b578073e69b28881d88a6da2f
refs/heads/master
2023-07-19T08:09:42.545448
2021-09-10T01:30:05
2021-09-10T01:30:05
404,651,996
3
1
null
null
null
null
GB18030
C++
false
false
698
h
#pragma once // CTypeModbusDlg 对话框 class CTypeModbusDlg : public CDialogEx { DECLARE_DYNAMIC(CTypeModbusDlg) public: CWinXPButtonST m_btnOk; CWinXPButtonST m_btnCancel; int m_nModbusType; CString m_strModbusName; private: void InitAllControl() ; void InitBtnControl() ; public: CTypeModbusDlg(CWnd* pParent = NULL); // 标准构造函数 virtual ~CTypeModbusDlg(); // 对话框数据 enum { IDD = IDD_TYPE_MODBUS_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: virtual BOOL OnInitDialog(); afx_msg void OnRadioClicked(UINT uRadioId) ; afx_msg void OnEnChangeEditModbusname(); };
[ "wanglvhh@outlook.com" ]
wanglvhh@outlook.com
fb5ba36fecb26d2c94c02af5100e3f05bed43332
65b18dbe3f46e5620e9c9f2014b37cd55a814b5d
/firmware/libraries/ros_lib/swarm_driver/Command.h
eacaa9dda9f051bd5ae2f826eac1e5b7cc6785f8
[]
no_license
remintz/hero_common
2575a32f643394c74619d29f288ee8055ea4e576
b19bef6feeb98a6a61592f32cdecab2f5e81401e
refs/heads/master
2020-06-12T10:46:26.111770
2017-04-12T19:13:32
2017-04-12T19:13:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,154
h
#ifndef _ROS_swarm_driver_Command_h #define _ROS_swarm_driver_Command_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" namespace swarm_driver { class Command : public ros::Msg { public: typedef uint8_t _robot_id_type; _robot_id_type robot_id; typedef int8_t _wheel_right_type; _wheel_right_type wheel_right; typedef int8_t _wheel_left_type; _wheel_left_type wheel_left; Command(): robot_id(0), wheel_right(0), wheel_left(0) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; *(outbuffer + offset + 0) = (this->robot_id >> (8 * 0)) & 0xFF; offset += sizeof(this->robot_id); union { int8_t real; uint8_t base; } u_wheel_right; u_wheel_right.real = this->wheel_right; *(outbuffer + offset + 0) = (u_wheel_right.base >> (8 * 0)) & 0xFF; offset += sizeof(this->wheel_right); union { int8_t real; uint8_t base; } u_wheel_left; u_wheel_left.real = this->wheel_left; *(outbuffer + offset + 0) = (u_wheel_left.base >> (8 * 0)) & 0xFF; offset += sizeof(this->wheel_left); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; this->robot_id = ((uint8_t) (*(inbuffer + offset))); offset += sizeof(this->robot_id); union { int8_t real; uint8_t base; } u_wheel_right; u_wheel_right.base = 0; u_wheel_right.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0); this->wheel_right = u_wheel_right.real; offset += sizeof(this->wheel_right); union { int8_t real; uint8_t base; } u_wheel_left; u_wheel_left.base = 0; u_wheel_left.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0); this->wheel_left = u_wheel_left.real; offset += sizeof(this->wheel_left); return offset; } const char * getType(){ return "swarm_driver/Command"; }; const char * getMD5(){ return "d76b8052249a64fe0c4d7bda68ee48ae"; }; }; } #endif
[ "rezeck@dcc.ufmg.br" ]
rezeck@dcc.ufmg.br
39a2ace08a2725269bfd6c36dd207890c1f0b783
16b715a942a05cc950327e4e464c76b1f9df20fb
/F103_timer/user/user_lib/inc/tim.h
bc3c06053639667e3eb87d1a33e77e140e1ea3ab
[]
no_license
KANAIHIROYUKI/STM32
88cbefd0dcfd208b2dd7c8f291f9f53f2a54077d
bd758d6740e235682445f512a312af022b20cc9e
refs/heads/master
2020-12-02T02:12:39.571320
2018-10-24T08:14:24
2018-10-24T08:14:24
60,416,906
0
0
null
null
null
null
ISO-8859-1
C++
false
false
4,151
h
#ifndef TIM_H_ #define TIM_H_ #include "stm32f10x.h" #include <stdio.h> #include "systime.h" #include "base.h" #include "gpio.h" #define PWM_PERIOD_DEFALUT 1024 #define TIM_OCMode_DEFAULT TIM_OCMode_PWM1 #define TIM_PWM 1 #define TIM_ENC 2 #define TIM_TIM 3 #define TIM1_ENC_Setup TIM1,PA8,PA9 #define TIM2_ENC_Setup TIM2,PA0,PA1 #define TIM3_ENC_Setup TIM3,PA6,PA7 #define TIM4_ENC_Setup TIM4,PB6,PB7 #define TIM2_ENC_RM_Setup TIM2,PA15,PB3 #define TIM3_ENC_RM_Setup TIM3,PB4,PB5 #define TIM1_PWM1_Setup TIM1,1,PA8 #define TIM1_PWM2_Setup TIM1,2,PA9 #define TIM1_PWM3_Setup TIM1,3,PA10 #define TIM1_PWM4_Setup TIM1,4,PA11 #define TIM2_PWM1_Setup TIM2,1,PA0 #define TIM2_PWM2_Setup TIM2,2,PA1 #define TIM2_PWM3_Setup TIM2,3,PA2 #define TIM2_PWM4_Setup TIM2,4,PA3 #define TIM3_PWM1_Setup TIM3,1,PA6 #define TIM3_PWM2_Setup TIM3,2,PA7 #define TIM3_PWM3_Setup TIM3,3,PB0 #define TIM3_PWM4_Setup TIM3,4,PB1 #define TIM4_PWM1_Setup TIM4,1,PB6 #define TIM4_PWM2_Setup TIM4,2,PB7 #define TIM4_PWM3_Setup TIM4,3,PB8 #define TIM4_PWM4_Setup TIM4,4,PB9 #define TIM2_PWM1_RM_Setup TIM2,1,PA15 #define TIM2_PWM2_RM_Setup TIM2,2,PB3 #define TIM2_PWM3_RM_Setup TIM2,3,PB10 #define TIM2_PWM4_RM_Setup TIM2,4,PB11 #define TIM3_PWM1_RM_Setup TIM3,1,PB4 #define TIM3_PWM2_RM_Setup TIM3,2,PB5 class TIM:public CountIn{ public: void encoderSetup(TIM_TypeDef* tim,GPIO_TypeDef* gpio1,uint16_t pin1,GPIO_TypeDef* gpio2,uint16_t pin2); int32_t read(); void reset(); void reverse(int8_t dir = -1); int8_t encoder_dir; static int32_t tim1Cnt; static int32_t tim2Cnt; static int32_t tim3Cnt; static int32_t tim4Cnt; void pwmSetup(TIM_TypeDef* tim,uint16_t channel,GPIO_TypeDef* gpio,uint16_t pin,uint16_t period = PWM_PERIOD_DEFALUT,uint16_t prescaler = 0,uint16_t mode = TIM_OCMode_DEFAULT); void pwmReset(uint16_t period = PWM_PERIOD_DEFALUT,uint16_t prescaler = 0,uint16_t mode = TIM_OCMode_DEFAULT); uint16_t duty(uint16_t duty); uint16_t dutyF(float duty); void itSetup(); void timerSetup(TIM_TypeDef* tim); uint64_t millis(); uint64_t micros(); uint16_t pwm_duty; uint16_t pwm_period; uint16_t pwm_prescaler; static uint32_t tim1_mode; static uint32_t tim2_mode; static uint32_t tim3_mode; static uint32_t tim4_mode; void ioSetupEnc(GPIO_TypeDef* gpio1,uint16_t pin1,GPIO_TypeDef* gpio2,uint16_t pin2); void ioSetupPwm(GPIO_TypeDef* gpio,uint16_t pin); TIM_TypeDef* tim_tim; uint16_t pwm_channel; uint16_t pwm_mode; }; void TIM1Setup(uint16_t period = PWM_PERIOD_DEFALUT,uint16_t prescaler = 0); void TIM2Setup(uint16_t period = PWM_PERIOD_DEFALUT,uint16_t prescaler = 0); void TIM3Setup(uint16_t period = PWM_PERIOD_DEFALUT,uint16_t prescaler = 0); void TIM4Setup(uint16_t period = PWM_PERIOD_DEFALUT,uint16_t prescaler = 0); void TIM1ITSetup(uint16_t tim_it = TIM_IT_Update); void TIM2ITSetup(uint16_t tim_it = TIM_IT_Update); void TIM3ITSetup(uint16_t tim_it = TIM_IT_Update); void TIM4ITSetup(uint16_t tim_it = TIM_IT_Update); void TIM_OCStructInit_PWM(TIM_OCInitTypeDef *str); void OC1PWMSetup(TIM_TypeDef*tim,uint16_t mode); void OC2PWMSetup(TIM_TypeDef*tim,uint16_t mode); void OC3PWMSetup(TIM_TypeDef*tim,uint16_t mode); void OC4PWMSetup(TIM_TypeDef*tim,uint16_t mode); void OC1DutySet(TIM_TypeDef*TIMx,uint16_t duty); void OC2DutySet(TIM_TypeDef*TIMx,uint16_t duty); void OC3DutySet(TIM_TypeDef*TIMx,uint16_t duty); void OC4DutySet(TIM_TypeDef*TIMx,uint16_t duty); /********************************«ENCODER ªPWM***********************************************/ void TIM1EncoderSetup(); void TIM2EncoderSetup(); void TIM3EncoderSetup(); void TIM4EncoderSetup(); int32_t TIM1Read(); int32_t TIM2Read(); int32_t TIM3Read(); int32_t TIM4Read(); void TIM1_ENCODER_IRQ(); void TIM2_ENCODER_IRQ(); void TIM3_ENCODER_IRQ(); void TIM4_ENCODER_IRQ(); void TIM1_PWM_Update_IRQ(); void TIM2_PWM_Update_IRQ(); void TIM3_PWM_Update_IRQ(); void TIM4_PWM_Update_IRQ(); void TIM4_PWM_CC1_IRQ(); void TIM4_PWM_CC2_IRQ(); void TIM4_PWM_CC3_IRQ(); void TIM4_PWM_CC4_IRQ(); void TIM1_TIM_Update_IRQ(); void TIM2_TIM_Update_IRQ(); void TIM3_TIM_Update_IRQ(); void TIM4_TIM_Update_IRQ(); #endif
[ "b1503146@planet.kanazawa-it.ac.jp" ]
b1503146@planet.kanazawa-it.ac.jp
81dbc0af0fdf9dfa2738348441358a1f4666d279
d4e96aa48ddff651558a3fe2212ebb3a3afe5ac3
/Modules/ThirdParty/VNL/src/vxl/core/vnl/vnl_int_matrix.h
9463d6142590844c3a8207b575cd632eb99a375a
[ "SMLNJ", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-mit-old-style", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer", "NTP", "IJG", "GPL-1.0-or-later", "libtiff", "BSD-4.3TAHOE", "...
permissive
nalinimsingh/ITK_4D
18e8929672df64df58a6446f047e6ec04d3c2616
95a2eacaeaffe572889832ef0894239f89e3f303
refs/heads/master
2020-03-17T18:58:50.953317
2018-10-01T20:46:43
2018-10-01T21:21:01
133,841,430
0
0
Apache-2.0
2018-05-17T16:34:54
2018-05-17T16:34:53
null
UTF-8
C++
false
false
1,181
h
// This is core/vnl/vnl_int_matrix.h #ifndef vnl_int_matrix_h_ #define vnl_int_matrix_h_ #ifdef VCL_NEEDS_PRAGMA_INTERFACE #pragma interface #endif //: // \file // \brief Specializes vnl_matrix for integers // \author Andrew W. Fitzgibbon, Oxford RRG // \date 27 Dec 96 // // \verbatim // Modifications // LSB (Manchester) 23/3/01 Tidied documentation // \endverbatim // //----------------------------------------------------------------------------- #include <vnl/vnl_matrix.h> #include <vnl/vnl_error.h> #include "vnl/vnl_export.h" //: Specializes vnl_matrix for integers, adding a vnl_matrix<double> ctor. class VNL_EXPORT vnl_int_matrix : public vnl_matrix<int> { typedef vnl_matrix<int> Base; public: vnl_int_matrix() {} vnl_int_matrix(char const* filename); vnl_int_matrix(unsigned r, unsigned c): Base(r, c) {} vnl_int_matrix(unsigned r, unsigned c, int fillvalue): Base(r, c, fillvalue) {} vnl_int_matrix(const vnl_matrix<double>& d); vnl_int_matrix(const vnl_matrix<int>& d):Base(d) {} vnl_int_matrix& operator=(const vnl_matrix<int>& d) { Base::operator=(d); return *this; } }; #endif // vnl_int_matrix_h_
[ "ruizhi@csail.mit.edu" ]
ruizhi@csail.mit.edu
d52711ed7445b25c0acc0bda124ada190b6b7d76
8126291334a4288f51b1116ea31e953debf07039
/SRC/engine/property/permittivity/permittivity.h
4cccfc2c729f826b6f7a93c4fdbd14165e3ae977
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
jumpingyu/OOF2
846a7dd506f029535153834607b698ce32dc155d
31a25398b046c1963859dd96785329d2a9af8681
refs/heads/master
2020-05-21T09:12:07.013560
2019-04-02T21:05:49
2019-04-02T21:05:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,402
h
// -*- C++ -*- /* This software was produced by NIST, an agency of the U.S. government, * and by statute is not subject to copyright in the United States. * Recipients of this software assume all responsibilities associated * with its operation, modification and maintenance. However, to * facilitate maintenance we ask that before distributing modified * versions of this software, you first contact the authors at * oof_manager@nist.gov. */ // dielectric permittivity property #ifndef PERMITTIVITY_H #define PERMITTIVITY_H #include "engine/property.h" #include "engine/symmmatrix.h" #include "common/pythonexportable.h" #include "engine/smallsystem.h" #include <string> class CSubProblem; class Element; class Equation; class ElementNodeIterator; class Material; class OrientationPropBase; class OutputVal; class PropertyOutput; class ScalarField; class VectorFlux; class DielectricPermittivity : public FluxProperty { public: DielectricPermittivity(PyObject *registry, const std::string &name); virtual void flux_matrix(const FEMesh*, const Element*, const ElementFuncNodeIterator&, const Flux*, const MasterPosition&, double time, SmallSystem*) const; virtual void cross_reference(Material*) = 0; virtual void output(const FEMesh*, const Element*, const PropertyOutput*, const MasterPosition&, OutputVal*) const; virtual const SymmMatrix3 permittivityTensor(const FEMesh *mesh, const Element *element, const MasterPosition&x) const = 0; virtual int integration_order(const CSubProblem*, const Element*) const; virtual bool constant_in_space() const { return true; } protected: SymmMatrix3 permittivitytensor_; ScalarField *voltage; VectorFlux *total_polarization; }; class IsoDielectricPermittivity : public DielectricPermittivity { public: IsoDielectricPermittivity(PyObject *registry, const std::string &name, double epsilon); virtual void cross_reference(Material*) {} virtual void precompute(FEMesh*); virtual const SymmMatrix3 permittivityTensor(const FEMesh *mesh, const Element *element, const MasterPosition&x) const { return permittivitytensor_; } private: double epsilon_; }; class AnisoDielectricPermittivity : public DielectricPermittivity { public: AnisoDielectricPermittivity(PyObject *registry, const std::string &name, SymmMatrix3 *epsilon); virtual void cross_reference(Material*); // finds Orientation virtual void precompute(FEMesh*); virtual const SymmMatrix3 permittivityTensor(const FEMesh *mesh, const Element *element, const MasterPosition &x) const; private: SymmMatrix3 epsilon_; OrientationPropBase *orientation; }; //=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=// // distributed charge density class ChargeDensity : public EqnProperty { private: double qdot_; // external heat dumped in per unit area per unit time. VectorFlux *total_polarization; public: ChargeDensity(PyObject *registry, const std::string &name, double qd); double rho() { return qdot_; } virtual int integration_order(const CSubProblem*, const Element*) const; virtual void force_value(const FEMesh*, const Element*, const Equation*, const MasterPosition&, double time, SmallSystem *) const; virtual bool constant_in_space() const { return true; } }; #endif
[ "lnz5@rosie.nist.gov" ]
lnz5@rosie.nist.gov
63dfddfdcb3ddde990144224bcc0837483db3da5
5466d26c70df149bda6cbf823841cd48df370080
/User.cpp
877609800e774c87941e605c856ff1336f45b4d6
[]
no_license
Reksagon/Testing_system
335d67e715f20a0cd0fba8cbcf66e83747b78684
ef3123a081894ac4602e766dd796ff0f657c46fa
refs/heads/main
2023-01-05T06:56:13.363396
2020-10-22T19:27:48
2020-10-22T19:27:48
306,438,456
0
0
null
null
null
null
UTF-8
C++
false
false
5,068
cpp
#include "User.h" string path_user = "user.txt"; string User::login_user; string User::password_user; list<string> login; list<string> password; vector<string> listfile; int pu = 3; void User::Load_User() { ifstream file(path_user); if (!file.is_open()) { cout << "Не удалось открыть файл " << path_user << endl; } else { string lgn, psswrd, s; int col; file >> col; int i = 0; while (i < col) { file >> lgn; file >> psswrd; login.push_back(DeShifr(lgn)); password.push_back(DeShifr(psswrd)); i++; } file.close(); } } int User::Check(string lgn, string psswrd) { while (pu > 0) { for (auto i = login.cbegin(), j = password.cbegin(); i != login.cend(); ++i, j++) { if (*i == lgn && *j == psswrd) { User::login_user = lgn; User::password_user = psswrd; return 1; } } system("cls"); pu--; cout << "Неправильынй логин или пароль. Осталось попыток: " << pu << endl; return 2; } } void User::Register() { list<string> tmplogin; list<string> tmppass; string lgn, psswrd, fio, adress, phone; cout << "\t\t Регистраци:" << endl; cout << "Введите логин:" << endl; cin >> lgn; cout << "Введите пароль:" << endl; cin >> psswrd; cout << "Введите ФИО:" << endl; cin.ignore(); getline(cin, fio); cout << "Введите домашний адрес:" << endl; getline(cin, adress); cout << "Введите телефон:" << endl; getline(cin, phone); ifstream file; file.open(path_user); if (!file.is_open()) { cout << "Не удалось открыть файл " << path_user << endl; } else { string lgn2, psswrd2; int col; file >> Count_User; int i = 0; if (Count_User == 0) { } else { while (i < Count_User) { file >> lgn2; file >> psswrd2; tmplogin.push_back(lgn2); tmppass.push_back(psswrd2); i++; } } tmplogin.push_back(Shifr(lgn)); tmppass.push_back(Shifr(psswrd)); file.close(); } ofstream fout(path_user); if (Count_User == 0) { Count_User++; fout << Count_User << endl; fout << Shifr(lgn) << endl; fout << Shifr(psswrd) << endl; fout.close(); } else { Count_User++; fout << Count_User << endl; for (auto i = tmplogin.cbegin(), j = tmppass.cbegin(); i != tmplogin.cend(); ++i, ++j) { fout << *i << endl; fout << *j << endl; } fout.close(); } ofstream ffout; string path2 = lgn + ".txt"; ffout.open(path2); if (!ffout.is_open()) { cout << "Не удалось открыть файл " << path2 << endl; } else { ffout << fio << endl; ffout << adress << endl; ffout << phone << endl; } ffout.close(); system("cls"); cout << "Вы успешно зарегистрировались в системе!" << endl; } string User::GetLogin() { return login_user; } void User::LoadDataUser() { string path = login_user + ".txt"; ifstream file(path); if (!file.is_open()) { cout << "Не удалось открыть файл " << path << endl; } else { string s; while (getline(file, s)) { FIO = s; getline(file,HomeAdress); getline(file,Phone); } file.close(); } } //************************************************************************************************************************************ void Answer::Save() { string path = login_user + "-passed.txt"; ifstream fin(path); //fout.open(path, fstream::app); if (!fin.is_open()) { fin.open(path); ofstream fout(path); fout << category << endl; fout << NameTest << endl; fout << ball << endl; fout << correct << endl; fout << incorrect << endl; fout.close(); } else { ofstream fout(path, fstream::app); fout << category << endl; fout << NameTest << endl; fout << ball << endl; fout << correct << endl; fout << incorrect << endl; fout.close(); } //listfile.push_back(path); fin.close(); } void Answer::LoadPassedTest() { string path = login_user + "-passed.txt"; vector<string> category, nametest, ball, correct, incorrect; ifstream file(path); //fout.open(path, fstream::app); if (!file.is_open()) { cout << "error" << endl; } else { string cat, name, b, cor, incor; while (getline(file, cat)) { getline(file, name); getline(file, b); getline(file, cor); getline(file, incor); category.push_back(cat); nametest.push_back(name); ball.push_back(b); correct.push_back(cor); incorrect.push_back(incor); } } file.close(); for (int i = 0; i < category.size(); i++) { float a1 = stof(correct[i]); float b1 = stof(incorrect[i]); float ab = a1 + b1; float c1 = (a1 / ab) * 100; cout << "Категория: " << category[i] << endl; cout << "Тест: " << nametest[i] << endl; cout << "Оценка: " << ball[i] << endl; cout << "Правильных ответов: " << correct[i] << endl; cout << "Неправильных ответов: " << incorrect[i] << endl; cout << "Процент ответов: " << c1 << "%" << endl << endl; } }
[ "noreply@github.com" ]
noreply@github.com
a71ef9d6c20b4e7af4c5349c97f364c7095f120c
ab08dcb1f06ab70edd174d6b72e38f90180e22ac
/018_Cascaded Shadow Maps/ScreenQuadPass.h
f64f3f1ad0ed88c3d998a4df44e3461d6e5f123d
[ "MIT" ]
permissive
AngelMonica126/GraphicAlgorithm
f208bbbe0212151a2659b425816380d9f9dbdd8a
58877e6a8dba75ab171b0d89260defaffa22d047
refs/heads/master
2022-06-02T18:46:36.061487
2022-03-06T14:30:44
2022-03-06T14:30:44
271,798,397
1,240
203
MIT
2021-08-19T07:32:05
2020-06-12T12:55:47
C++
UTF-8
C++
false
false
311
h
#pragma once #include "RenderPass.h" class CScreenQuadPass : public IRenderPass { public: CScreenQuadPass(const std::string& vPassName, int vExecutionOrder); virtual ~CScreenQuadPass(); virtual void initV() override; virtual void updateV() override; int m_OldKeyDebug = -1; int m_OldKeyNormal = -1; };
[ "1071209504@qq.com" ]
1071209504@qq.com
d2bdf269a40b14e8e2c81945b2abde5f80193d24
9da43703f185346cc8c7b1627553ebfc96af18b9
/Ultrasonic_1.ino
81849b3f0a95e7ace52da21c3ce7577039c4ed6a
[]
no_license
otavio17/robo_usp
0033db9865d94b24dcebeed80834bb78ff949e84
7c800e6e1d30eeaa6c8eda2425dcbc225d6cf40d
refs/heads/master
2020-06-01T13:22:30.861346
2019-06-07T18:47:00
2019-06-07T18:47:00
190,793,155
0
0
null
null
null
null
UTF-8
C++
false
false
614
ino
#include <Ultrasonic.h> const int pino_trigger = 3; const int pino_echo = 5; Ultrasonic ultrasonic_sensor(pino_trigger, pino_echo); void setup() { Serial.begin(9600); Serial.println("Teste sensor ultrassom"); } void loop() { float cmMsec, inMsec; long microsec = ultrasonic_sensor.timing(); cmMsec = ultrasonic_sensor.convert(microsec, Ultrasonic::CM); inMsec = ultrasonic_sensor.convert(microsec, Ultrasonic::IN); Serial.println("Distância em centímetro:"); Serial.println(cmMsec); Serial.println("Distância em polegadas:"); Serial.println(inMsec); delay(10000); }
[ "noreply@github.com" ]
noreply@github.com