text
stringlengths
5
1.04M
#include <sys/socket.h> #include <arpa/inet.h> #include <fcntl.h> #include <cstring> #include <ctime> #include <unistd.h> #include "kingpin/AsyncLogger.h" #include "kingpin/Buffer.h" #include "kingpin/Utils.h" #include "kingpin/Exception.h" using namespace std; using namespace kingpin; class Client { public: static const int _port; static const int _step; static const char *const _ip; void start() { int sock = connectIp(_ip, _port, 15); const char *str; str = "/tmp/file.test"; ::write(sock, str, strlen(str)); sleep(1); str = "\n"; ::write(sock, str, strlen(str)); int fd = ::open("/tmp/file.test.copy", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); if (fd < 0) { fatalError("syscall open failed"); } Buffer buffer; bool end = false; while(!end) { try { buffer.readNioToBuffer(sock, _step); } catch(const EOFException &e) { INFO << e << END; end = true; } buffer.writeNioFromBufferTillEnd(fd); } ::close(fd); } }; const int Client::_port = 8890; const int Client::_step = 1024 * 10; const char *const Client::_ip = "127.0.0.1"; int main() { Client client; client.start(); return 0; }
/*! * Copyright (c) 2016 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for * license information. */ #ifndef LIGHTGBM_IO_SPARSE_BIN_HPP_ #define LIGHTGBM_IO_SPARSE_BIN_HPP_ #include <LightGBM/bin.h> #include <LightGBM/utils/log.h> #include <LightGBM/utils/openmp_wrapper.h> #include <algorithm> #include <cstdint> #include <cstring> #include <limits> #include <utility> #include <vector> #include <mimalloc.h> namespace LightGBM { template <typename VAL_T> class SparseBin; const size_t kNumFastIndex = 64; template <typename VAL_T> class SparseBinIterator : public BinIterator { public: SparseBinIterator(const SparseBin<VAL_T> *bin_data, uint32_t min_bin, uint32_t max_bin, uint32_t most_freq_bin) : bin_data_(bin_data), min_bin_(static_cast<VAL_T>(min_bin)), max_bin_(static_cast<VAL_T>(max_bin)), most_freq_bin_(static_cast<VAL_T>(most_freq_bin)) { if (most_freq_bin_ == 0) { offset_ = 1; } else { offset_ = 0; } Reset(0); } SparseBinIterator(const SparseBin<VAL_T> *bin_data, data_size_t start_idx) : bin_data_(bin_data) { Reset(start_idx); } inline uint32_t RawGet(data_size_t idx) override; inline VAL_T InnerRawGet(data_size_t idx); inline uint32_t Get(data_size_t idx) override { VAL_T ret = InnerRawGet(idx); if (ret >= min_bin_ && ret <= max_bin_) { return ret - min_bin_ + offset_; } else { return most_freq_bin_; } } inline void Reset(data_size_t idx) override; private: const SparseBin<VAL_T> *bin_data_; data_size_t cur_pos_; data_size_t i_delta_; VAL_T min_bin_; VAL_T max_bin_; VAL_T most_freq_bin_; uint8_t offset_; }; template <typename VAL_T> class SparseBin : public Bin { public: friend class SparseBinIterator<VAL_T>; explicit SparseBin(data_size_t num_data) : num_data_(num_data) { int num_threads = OMP_NUM_THREADS(); push_buffers_.resize(num_threads); } ~SparseBin() {} void ReSize(data_size_t num_data) override { num_data_ = num_data; } void Push(int tid, data_size_t idx, uint32_t value) override { auto cur_bin = static_cast<VAL_T>(value); if (cur_bin != 0) { push_buffers_[tid].emplace_back(idx, cur_bin); } } BinIterator *GetIterator(uint32_t min_bin, uint32_t max_bin, uint32_t most_freq_bin) const override; #define ACC_GH(hist, i, g, h) \ const auto ti = static_cast<int>(i) << 1; \ hist[ti] += g; \ hist[ti + 1] += h; void ConstructHistogram(const data_size_t *data_indices, data_size_t start, data_size_t end, const score_t *ordered_gradients, const score_t *ordered_hessians, hist_t *out) const override { data_size_t i_delta, cur_pos; InitIndex(data_indices[start], &i_delta, &cur_pos); data_size_t i = start; for (;;) { if (cur_pos < data_indices[i]) { cur_pos += deltas_[++i_delta]; if (i_delta >= num_vals_) { break; } } else if (cur_pos > data_indices[i]) { if (++i >= end) { break; } } else { const VAL_T bin = vals_[i_delta]; ACC_GH(out, bin, ordered_gradients[i], ordered_hessians[i]); if (++i >= end) { break; } cur_pos += deltas_[++i_delta]; if (i_delta >= num_vals_) { break; } } } } void ConstructHistogram(data_size_t start, data_size_t end, const score_t *ordered_gradients, const score_t *ordered_hessians, hist_t *out) const override { data_size_t i_delta, cur_pos; InitIndex(start, &i_delta, &cur_pos); while (cur_pos < start && i_delta < num_vals_) { cur_pos += deltas_[++i_delta]; } while (cur_pos < end && i_delta < num_vals_) { const VAL_T bin = vals_[i_delta]; ACC_GH(out, bin, ordered_gradients[cur_pos], ordered_hessians[cur_pos]); cur_pos += deltas_[++i_delta]; } } void ConstructHistogram(const data_size_t *data_indices, data_size_t start, data_size_t end, const score_t *ordered_gradients, hist_t *out) const override { data_size_t i_delta, cur_pos; InitIndex(data_indices[start], &i_delta, &cur_pos); data_size_t i = start; hist_t *grad = out; hist_cnt_t *cnt = reinterpret_cast<hist_cnt_t *>(out + 1); for (;;) { if (cur_pos < data_indices[i]) { cur_pos += deltas_[++i_delta]; if (i_delta >= num_vals_) { break; } } else if (cur_pos > data_indices[i]) { if (++i >= end) { break; } } else { const uint32_t ti = static_cast<uint32_t>(vals_[i_delta]) << 1; grad[ti] += ordered_gradients[i]; ++cnt[ti]; if (++i >= end) { break; } cur_pos += deltas_[++i_delta]; if (i_delta >= num_vals_) { break; } } } } void ConstructHistogram(data_size_t start, data_size_t end, const score_t *ordered_gradients, hist_t *out) const override { data_size_t i_delta, cur_pos; InitIndex(start, &i_delta, &cur_pos); hist_t *grad = out; hist_cnt_t *cnt = reinterpret_cast<hist_cnt_t *>(out + 1); while (cur_pos < start && i_delta < num_vals_) { cur_pos += deltas_[++i_delta]; } while (cur_pos < end && i_delta < num_vals_) { const uint32_t ti = static_cast<uint32_t>(vals_[i_delta]) << 1; grad[ti] += ordered_gradients[cur_pos]; ++cnt[ti]; cur_pos += deltas_[++i_delta]; } } #undef ACC_GH inline void NextNonzeroFast(data_size_t *i_delta, data_size_t *cur_pos) const { *cur_pos += deltas_[++(*i_delta)]; if (*i_delta >= num_vals_) { *cur_pos = num_data_; } } inline bool NextNonzero(data_size_t *i_delta, data_size_t *cur_pos) const { *cur_pos += deltas_[++(*i_delta)]; if (*i_delta < num_vals_) { return true; } else { *cur_pos = num_data_; return false; } } template <bool MISS_IS_ZERO, bool MISS_IS_NA, bool MFB_IS_ZERO, bool MFB_IS_NA, bool USE_MIN_BIN> data_size_t SplitInner(uint32_t min_bin, uint32_t max_bin, uint32_t default_bin, uint32_t most_freq_bin, bool default_left, uint32_t threshold, const data_size_t *data_indices, data_size_t cnt, data_size_t *lte_indices, data_size_t *gt_indices) const { auto th = static_cast<VAL_T>(threshold + min_bin); auto t_zero_bin = static_cast<VAL_T>(min_bin + default_bin); if (most_freq_bin == 0) { --th; --t_zero_bin; } const auto minb = static_cast<VAL_T>(min_bin); const auto maxb = static_cast<VAL_T>(max_bin); data_size_t lte_count = 0; data_size_t gt_count = 0; data_size_t *default_indices = gt_indices; data_size_t *default_count = &gt_count; data_size_t *missing_default_indices = gt_indices; data_size_t *missing_default_count = &gt_count; if (most_freq_bin <= threshold) { default_indices = lte_indices; default_count = &lte_count; } if (MISS_IS_ZERO || MISS_IS_NA) { if (default_left) { missing_default_indices = lte_indices; missing_default_count = &lte_count; } } SparseBinIterator<VAL_T> iterator(this, data_indices[0]); if (min_bin < max_bin) { for (data_size_t i = 0; i < cnt; ++i) { const data_size_t idx = data_indices[i]; const auto bin = iterator.InnerRawGet(idx); if ((MISS_IS_ZERO && !MFB_IS_ZERO && bin == t_zero_bin) || (MISS_IS_NA && !MFB_IS_NA && bin == maxb)) { missing_default_indices[(*missing_default_count)++] = idx; } else if ((USE_MIN_BIN && (bin < minb || bin > maxb)) || (!USE_MIN_BIN && bin == 0)) { if ((MISS_IS_NA && MFB_IS_NA) || (MISS_IS_ZERO && MFB_IS_ZERO)) { missing_default_indices[(*missing_default_count)++] = idx; } else { default_indices[(*default_count)++] = idx; } } else if (bin > th) { gt_indices[gt_count++] = idx; } else { lte_indices[lte_count++] = idx; } } } else { data_size_t *max_bin_indices = gt_indices; data_size_t *max_bin_count = &gt_count; if (maxb <= th) { max_bin_indices = lte_indices; max_bin_count = &lte_count; } for (data_size_t i = 0; i < cnt; ++i) { const data_size_t idx = data_indices[i]; const auto bin = iterator.InnerRawGet(idx); if (MISS_IS_ZERO && !MFB_IS_ZERO && bin == t_zero_bin) { missing_default_indices[(*missing_default_count)++] = idx; } else if (bin != maxb) { if ((MISS_IS_NA && MFB_IS_NA) || (MISS_IS_ZERO && MFB_IS_ZERO)) { missing_default_indices[(*missing_default_count)++] = idx; } else { default_indices[(*default_count)++] = idx; } } else { if (MISS_IS_NA && !MFB_IS_NA) { missing_default_indices[(*missing_default_count)++] = idx; } else { max_bin_indices[(*max_bin_count)++] = idx; } } } } return lte_count; } data_size_t Split(uint32_t min_bin, uint32_t max_bin, uint32_t default_bin, uint32_t most_freq_bin, MissingType missing_type, bool default_left, uint32_t threshold, const data_size_t *data_indices, data_size_t cnt, data_size_t *lte_indices, data_size_t *gt_indices) const override { #define ARGUMENTS \ min_bin, max_bin, default_bin, most_freq_bin, default_left, threshold, \ data_indices, cnt, lte_indices, gt_indices if (missing_type == MissingType::None) { return SplitInner<false, false, false, false, true>(ARGUMENTS); } else if (missing_type == MissingType::Zero) { if (default_bin == most_freq_bin) { return SplitInner<true, false, true, false, true>(ARGUMENTS); } else { return SplitInner<true, false, false, false, true>(ARGUMENTS); } } else { if (max_bin == most_freq_bin + min_bin && most_freq_bin > 0) { return SplitInner<false, true, false, true, true>(ARGUMENTS); } else { return SplitInner<false, true, false, false, true>(ARGUMENTS); } } #undef ARGUMENTS } data_size_t Split(uint32_t max_bin, uint32_t default_bin, uint32_t most_freq_bin, MissingType missing_type, bool default_left, uint32_t threshold, const data_size_t *data_indices, data_size_t cnt, data_size_t *lte_indices, data_size_t *gt_indices) const override { #define ARGUMENTS \ 1, max_bin, default_bin, most_freq_bin, default_left, threshold, \ data_indices, cnt, lte_indices, gt_indices if (missing_type == MissingType::None) { return SplitInner<false, false, false, false, false>(ARGUMENTS); } else if (missing_type == MissingType::Zero) { if (default_bin == most_freq_bin) { return SplitInner<true, false, true, false, false>(ARGUMENTS); } else { return SplitInner<true, false, false, false, false>(ARGUMENTS); } } else { if (max_bin == most_freq_bin + 1 && most_freq_bin > 0) { return SplitInner<false, true, false, true, false>(ARGUMENTS); } else { return SplitInner<false, true, false, false, false>(ARGUMENTS); } } #undef ARGUMENTS } template <bool USE_MIN_BIN> data_size_t SplitCategoricalInner(uint32_t min_bin, uint32_t max_bin, uint32_t most_freq_bin, const uint32_t *threshold, int num_threahold, const data_size_t *data_indices, data_size_t cnt, data_size_t *lte_indices, data_size_t *gt_indices) const { data_size_t lte_count = 0; data_size_t gt_count = 0; data_size_t *default_indices = gt_indices; data_size_t *default_count = &gt_count; SparseBinIterator<VAL_T> iterator(this, data_indices[0]); if (Common::FindInBitset(threshold, num_threahold, most_freq_bin)) { default_indices = lte_indices; default_count = &lte_count; } for (data_size_t i = 0; i < cnt; ++i) { const data_size_t idx = data_indices[i]; const uint32_t bin = iterator.RawGet(idx); if (USE_MIN_BIN && (bin < min_bin || bin > max_bin)) { default_indices[(*default_count)++] = idx; } else if (!USE_MIN_BIN && bin == 0) { default_indices[(*default_count)++] = idx; } else if (Common::FindInBitset(threshold, num_threahold, bin - min_bin)) { lte_indices[lte_count++] = idx; } else { gt_indices[gt_count++] = idx; } } return lte_count; } data_size_t SplitCategorical(uint32_t min_bin, uint32_t max_bin, uint32_t most_freq_bin, const uint32_t *threshold, int num_threahold, const data_size_t *data_indices, data_size_t cnt, data_size_t *lte_indices, data_size_t *gt_indices) const override { return SplitCategoricalInner<true>(min_bin, max_bin, most_freq_bin, threshold, num_threahold, data_indices, cnt, lte_indices, gt_indices); } data_size_t SplitCategorical(uint32_t max_bin, uint32_t most_freq_bin, const uint32_t *threshold, int num_threahold, const data_size_t *data_indices, data_size_t cnt, data_size_t *lte_indices, data_size_t *gt_indices) const override { return SplitCategoricalInner<false>(1, max_bin, most_freq_bin, threshold, num_threahold, data_indices, cnt, lte_indices, gt_indices); } data_size_t num_data() const override { return num_data_; } void FinishLoad() override { // get total non zero size size_t pair_cnt = 0; for (size_t i = 0; i < push_buffers_.size(); ++i) { pair_cnt += push_buffers_[i].size(); } std::vector<std::pair<data_size_t, VAL_T>> &idx_val_pairs = push_buffers_[0]; idx_val_pairs.reserve(pair_cnt); for (size_t i = 1; i < push_buffers_.size(); ++i) { idx_val_pairs.insert(idx_val_pairs.end(), push_buffers_[i].begin(), push_buffers_[i].end()); push_buffers_[i].clear(); push_buffers_[i].shrink_to_fit(); } // sort by data index std::sort(idx_val_pairs.begin(), idx_val_pairs.end(), [](const std::pair<data_size_t, VAL_T> &a, const std::pair<data_size_t, VAL_T> &b) { return a.first < b.first; }); // load delta array LoadFromPair(idx_val_pairs); } void LoadFromPair( const std::vector<std::pair<data_size_t, VAL_T>> &idx_val_pairs) { deltas_.clear(); vals_.clear(); deltas_.reserve(idx_val_pairs.size()); vals_.reserve(idx_val_pairs.size()); // transform to delta array data_size_t last_idx = 0; for (size_t i = 0; i < idx_val_pairs.size(); ++i) { const data_size_t cur_idx = idx_val_pairs[i].first; const VAL_T bin = idx_val_pairs[i].second; data_size_t cur_delta = cur_idx - last_idx; // disallow the multi-val in one row if (i > 0 && cur_delta == 0) { continue; } while (cur_delta >= 256) { deltas_.push_back(255); vals_.push_back(0); cur_delta -= 255; } deltas_.push_back(static_cast<uint8_t>(cur_delta)); vals_.push_back(bin); last_idx = cur_idx; } // avoid out of range deltas_.push_back(0); num_vals_ = static_cast<data_size_t>(vals_.size()); // reduce memory cost deltas_.shrink_to_fit(); vals_.shrink_to_fit(); // generate fast index GetFastIndex(); } void GetFastIndex() { fast_index_.clear(); // get shift cnt data_size_t mod_size = (num_data_ + kNumFastIndex - 1) / kNumFastIndex; data_size_t pow2_mod_size = 1; fast_index_shift_ = 0; while (pow2_mod_size < mod_size) { pow2_mod_size <<= 1; ++fast_index_shift_; } // build fast index data_size_t i_delta = -1; data_size_t cur_pos = 0; data_size_t next_threshold = 0; while (NextNonzero(&i_delta, &cur_pos)) { while (next_threshold <= cur_pos) { fast_index_.emplace_back(i_delta, cur_pos); next_threshold += pow2_mod_size; } } // avoid out of range while (next_threshold < num_data_) { fast_index_.emplace_back(num_vals_ - 1, cur_pos); next_threshold += pow2_mod_size; } fast_index_.shrink_to_fit(); } void SaveBinaryToFile(const VirtualFileWriter *writer) const override { writer->Write(&num_vals_, sizeof(num_vals_)); writer->Write(deltas_.data(), sizeof(uint8_t) * (num_vals_ + 1)); writer->Write(vals_.data(), sizeof(VAL_T) * num_vals_); } size_t SizesInByte() const override { return sizeof(num_vals_) + sizeof(uint8_t) * (num_vals_ + 1) + sizeof(VAL_T) * num_vals_; } void LoadFromMemory( const void *memory, const std::vector<data_size_t, mi_stl_allocator<data_size_t>> &local_used_indices) override { const char *mem_ptr = reinterpret_cast<const char *>(memory); data_size_t tmp_num_vals = *(reinterpret_cast<const data_size_t *>(mem_ptr)); mem_ptr += sizeof(tmp_num_vals); const uint8_t *tmp_delta = reinterpret_cast<const uint8_t *>(mem_ptr); mem_ptr += sizeof(uint8_t) * (tmp_num_vals + 1); const VAL_T *tmp_vals = reinterpret_cast<const VAL_T *>(mem_ptr); deltas_.clear(); vals_.clear(); num_vals_ = tmp_num_vals; for (data_size_t i = 0; i < num_vals_; ++i) { deltas_.push_back(tmp_delta[i]); vals_.push_back(tmp_vals[i]); } deltas_.push_back(0); // reduce memory cost deltas_.shrink_to_fit(); vals_.shrink_to_fit(); if (local_used_indices.empty()) { // generate fast index GetFastIndex(); } else { std::vector<std::pair<data_size_t, VAL_T>> tmp_pair; data_size_t cur_pos = 0; data_size_t j = -1; for (data_size_t i = 0; i < static_cast<data_size_t>(local_used_indices.size()); ++i) { const data_size_t idx = local_used_indices[i]; while (cur_pos < idx && j < num_vals_) { NextNonzero(&j, &cur_pos); } if (cur_pos == idx && j < num_vals_ && vals_[j] > 0) { // new row index is i tmp_pair.emplace_back(i, vals_[j]); } } LoadFromPair(tmp_pair); } } void CopySubrow(const Bin *full_bin, const data_size_t *used_indices, data_size_t num_used_indices) override { auto other_bin = dynamic_cast<const SparseBin<VAL_T> *>(full_bin); deltas_.clear(); vals_.clear(); data_size_t start = 0; if (num_used_indices > 0) { start = used_indices[0]; } SparseBinIterator<VAL_T> iterator(other_bin, start); // transform to delta array data_size_t last_idx = 0; for (data_size_t i = 0; i < num_used_indices; ++i) { auto bin = iterator.InnerRawGet(used_indices[i]); if (bin > 0) { data_size_t cur_delta = i - last_idx; while (cur_delta >= 256) { deltas_.push_back(255); vals_.push_back(0); cur_delta -= 255; } deltas_.push_back(static_cast<uint8_t>(cur_delta)); vals_.push_back(bin); last_idx = i; } } // avoid out of range deltas_.push_back(0); num_vals_ = static_cast<data_size_t>(vals_.size()); // reduce memory cost deltas_.shrink_to_fit(); vals_.shrink_to_fit(); // generate fast index GetFastIndex(); } SparseBin<VAL_T> *Clone() override; SparseBin<VAL_T>(const SparseBin<VAL_T> &other) : num_data_(other.num_data_), deltas_(other.deltas_), vals_(other.vals_), num_vals_(other.num_vals_), push_buffers_(other.push_buffers_), fast_index_(other.fast_index_), fast_index_shift_(other.fast_index_shift_) {} void InitIndex(data_size_t start_idx, data_size_t *i_delta, data_size_t *cur_pos) const { auto idx = start_idx >> fast_index_shift_; if (static_cast<size_t>(idx) < fast_index_.size()) { const auto fast_pair = fast_index_[start_idx >> fast_index_shift_]; *i_delta = fast_pair.first; *cur_pos = fast_pair.second; } else { *i_delta = -1; *cur_pos = 0; } } private: data_size_t num_data_; std::vector<uint8_t, Common::AlignmentAllocator<uint8_t, kAlignedSize>> deltas_; std::vector<VAL_T, Common::AlignmentAllocator<VAL_T, kAlignedSize>> vals_; data_size_t num_vals_; std::vector<std::vector<std::pair<data_size_t, VAL_T>>> push_buffers_; std::vector<std::pair<data_size_t, data_size_t>> fast_index_; data_size_t fast_index_shift_; }; template <typename VAL_T> SparseBin<VAL_T> *SparseBin<VAL_T>::Clone() { return new SparseBin(*this); } template <typename VAL_T> inline uint32_t SparseBinIterator<VAL_T>::RawGet(data_size_t idx) { return InnerRawGet(idx); } template <typename VAL_T> inline VAL_T SparseBinIterator<VAL_T>::InnerRawGet(data_size_t idx) { while (cur_pos_ < idx) { bin_data_->NextNonzeroFast(&i_delta_, &cur_pos_); } if (cur_pos_ == idx) { return bin_data_->vals_[i_delta_]; } else { return 0; } } template <typename VAL_T> inline void SparseBinIterator<VAL_T>::Reset(data_size_t start_idx) { bin_data_->InitIndex(start_idx, &i_delta_, &cur_pos_); } template <typename VAL_T> BinIterator *SparseBin<VAL_T>::GetIterator(uint32_t min_bin, uint32_t max_bin, uint32_t most_freq_bin) const { return new SparseBinIterator<VAL_T>(this, min_bin, max_bin, most_freq_bin); } } // namespace LightGBM #endif // LightGBM_IO_SPARSE_BIN_HPP_
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/debug/debug_grpc_testlib.h" #include "tensorflow/core/debug/debug_graph_utils.h" #include "tensorflow/core/debug/debugger_event_metadata.pb.h" #include "tensorflow/core/framework/summary.pb.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/protobuf.h" #include "tensorflow/core/platform/tracing.h" namespace tensorflow { namespace test { ::grpc::Status TestEventListenerImpl::SendEvents( ::grpc::ServerContext* context, ::grpc::ServerReaderWriter<::tensorflow::EventReply, ::tensorflow::Event>* stream) { Event event; while (stream->Read(&event)) { if (event.has_log_message()) { debug_metadata_strings.push_back(event.log_message().message()); stream->Write(EventReply()); } else if (!event.graph_def().empty()) { encoded_graph_defs.push_back(event.graph_def()); stream->Write(EventReply()); } else if (event.has_summary()) { const Summary::Value& val = event.summary().value(0); std::vector<string> name_items = tensorflow::str_util::Split(val.node_name(), ':'); const string node_name = name_items[0]; const string debug_op = name_items[2]; const TensorProto& tensor_proto = val.tensor(); Tensor tensor(tensor_proto.dtype()); if (!tensor.FromProto(tensor_proto)) { return ::grpc::Status::CANCELLED; } // Obtain the device name, which is encoded in JSON. third_party::tensorflow::core::debug::DebuggerEventMetadata metadata; if (val.metadata().plugin_data().plugin_name() != "debugger") { // This plugin data was meant for another plugin. continue; } auto status = tensorflow::protobuf::util::JsonStringToMessage( val.metadata().plugin_data().content(), &metadata); if (!status.ok()) { // The device name could not be determined. continue; } device_names.push_back(metadata.device()); node_names.push_back(node_name); output_slots.push_back(metadata.output_slot()); debug_ops.push_back(debug_op); debug_tensors.push_back(tensor); // If the debug node is currently in the READ_WRITE mode, send an // EventReply to 1) unblock the execution and 2) optionally modify the // value. const DebugNodeKey debug_node_key(metadata.device(), node_name, metadata.output_slot(), debug_op); if (write_enabled_debug_node_keys_.find(debug_node_key) != write_enabled_debug_node_keys_.end()) { stream->Write(EventReply()); } } } { mutex_lock l(states_mu_); for (size_t i = 0; i < new_states_.size(); ++i) { EventReply event_reply; EventReply::DebugOpStateChange* change = event_reply.add_debug_op_state_changes(); // State changes will take effect in the next stream, i.e., next debugged // Session.run() call. change->set_state(new_states_[i]); const DebugNodeKey& debug_node_key = debug_node_keys_[i]; change->set_node_name(debug_node_key.node_name); change->set_output_slot(debug_node_key.output_slot); change->set_debug_op(debug_node_key.debug_op); stream->Write(event_reply); if (new_states_[i] == EventReply::DebugOpStateChange::READ_WRITE) { write_enabled_debug_node_keys_.insert(debug_node_key); } else { write_enabled_debug_node_keys_.erase(debug_node_key); } } debug_node_keys_.clear(); new_states_.clear(); } return ::grpc::Status::OK; } void TestEventListenerImpl::ClearReceivedDebugData() { debug_metadata_strings.clear(); encoded_graph_defs.clear(); device_names.clear(); node_names.clear(); output_slots.clear(); debug_ops.clear(); debug_tensors.clear(); } void TestEventListenerImpl::RequestDebugOpStateChangeAtNextStream( const EventReply::DebugOpStateChange::State new_state, const DebugNodeKey& debug_node_key) { mutex_lock l(states_mu_); debug_node_keys_.push_back(debug_node_key); new_states_.push_back(new_state); } void TestEventListenerImpl::RunServer(const int server_port) { ::grpc::ServerBuilder builder; builder.AddListeningPort(strings::StrCat("localhost:", server_port), ::grpc::InsecureServerCredentials()); builder.RegisterService(this); std::unique_ptr<::grpc::Server> server = builder.BuildAndStart(); while (!stop_requested_.load()) { Env::Default()->SleepForMicroseconds(200 * 1000); } server->Shutdown(); stopped_.store(true); } void TestEventListenerImpl::StopServer() { stop_requested_.store(true); while (!stopped_.load()) { } } bool PollTillFirstRequestSucceeds(const string& server_url, const size_t max_attempts) { const int kSleepDurationMicros = 100 * 1000; size_t n_attempts = 0; bool success = false; // Try a number of times to send the Event proto to the server, as it may // take the server a few seconds to start up and become responsive. Tensor prep_tensor(DT_FLOAT, TensorShape({1, 1})); prep_tensor.flat<float>()(0) = 42.0f; while (n_attempts++ < max_attempts) { const uint64 wall_time = Env::Default()->NowMicros(); Status publish_s = DebugIO::PublishDebugTensor( DebugNodeKey("/job:localhost/replica:0/task:0/cpu:0", "prep_node", 0, "DebugIdentity"), prep_tensor, wall_time, {server_url}); Status close_s = DebugIO::CloseDebugURL(server_url); if (publish_s.ok() && close_s.ok()) { success = true; break; } else { Env::Default()->SleepForMicroseconds(kSleepDurationMicros); } } return success; } } // namespace test } // namespace tensorflow
/********************************************************************* * 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 the Willow Garage 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: Martin Pecka */ #include <moveit/robot_model/aabb.h> #include <moveit/robot_model/robot_model.h> #include <moveit/robot_state/robot_state.h> #include <moveit_resources/config.h> #include <urdf_parser/urdf_parser.h> #include <fstream> #include <boost/filesystem.hpp> #include <gtest/gtest.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <tf2/LinearMath/Vector3.h> #include <moveit/utils/robot_model_test_utils.h> // To visualize bbox of the PR2, set this to 1. #ifndef VISUALIZE_PR2_RVIZ #define VISUALIZE_PR2_RVIZ 0 #endif #if VISUALIZE_PR2_RVIZ #include "rclcpp/rclcpp.hpp" #include <visualization_msgs/Marker.h> #include <geometric_shapes/shape_operations.h> #endif class TestAABB : public testing::Test { protected: void SetUp() override{}; robot_state::RobotState loadModel(const std::string robot_name) { robot_model::RobotModelPtr model = moveit::core::loadTestingRobotModel(robot_name); return loadModel(model); } robot_state::RobotState loadModel(robot_model::RobotModelPtr model) { robot_state::RobotState robot_state = robot_state::RobotState(model); robot_state.setToDefaultValues(); robot_state.update(true); return robot_state; } void TearDown() override { } }; TEST_F(TestAABB, TestPR2) { // Contains a link with mesh geometry that is not centered robot_state::RobotState pr2_state = this->loadModel("pr2_description"); const Eigen::Vector3d& extentsBaseFootprint = pr2_state.getLinkModel("base_footprint")->getShapeExtentsAtOrigin(); // values taken from moveit_resources/pr2_description/urdf/robot.xml EXPECT_NEAR(extentsBaseFootprint[0], 0.001, 1e-4); EXPECT_NEAR(extentsBaseFootprint[1], 0.001, 1e-4); EXPECT_NEAR(extentsBaseFootprint[2], 0.001, 1e-4); const Eigen::Vector3d& offsetBaseFootprint = pr2_state.getLinkModel("base_footprint")->getCenteredBoundingBoxOffset(); EXPECT_NEAR(offsetBaseFootprint[0], 0.0, 1e-4); EXPECT_NEAR(offsetBaseFootprint[1], 0.0, 1e-4); EXPECT_NEAR(offsetBaseFootprint[2], 0.071, 1e-4); const Eigen::Vector3d& extentsBaseLink = pr2_state.getLinkModel("base_link")->getShapeExtentsAtOrigin(); // values computed from moveit_resources/pr2_description/urdf/meshes/base_v0/base_L.stl in e.g. Meshlab EXPECT_NEAR(extentsBaseLink[0], 0.668242, 1e-4); EXPECT_NEAR(extentsBaseLink[1], 0.668242, 1e-4); EXPECT_NEAR(extentsBaseLink[2], 0.656175, 1e-4); const Eigen::Vector3d& offsetBaseLink = pr2_state.getLinkModel("base_link")->getCenteredBoundingBoxOffset(); EXPECT_NEAR(offsetBaseLink[0], 0.0, 1e-4); EXPECT_NEAR(offsetBaseLink[1], 0.0, 1e-4); EXPECT_NEAR(offsetBaseLink[2], 0.656175 / 2, 1e-4); // The 3D mesh isn't centered, but is whole above z axis std::vector<double> pr2_aabb; pr2_state.computeAABB(pr2_aabb); ASSERT_EQ(pr2_aabb.size(), 6u); EXPECT_NEAR(pr2_aabb[0], -0.3376, 1e-4); EXPECT_NEAR(pr2_aabb[1], 0.6499, 1e-4); EXPECT_NEAR(pr2_aabb[2], -0.6682 / 2, 1e-4); EXPECT_NEAR(pr2_aabb[3], 0.6682 / 2, 1e-4); EXPECT_NEAR(pr2_aabb[4], 0.0044, 1e-4); EXPECT_NEAR(pr2_aabb[5], 1.6328, 1e-4); // Test a specific link known to have some global rotation in the default pose const moveit::core::LinkModel* link = pr2_state.getLinkModel("l_forearm_link"); Eigen::Isometry3d transform = pr2_state.getGlobalLinkTransform(link); // intentional copy, we will translate const Eigen::Vector3d& extents = link->getShapeExtentsAtOrigin(); transform.translate(link->getCenteredBoundingBoxOffset()); moveit::core::AABB aabb; aabb.extendWithTransformedBox(transform, extents); EXPECT_NEAR(aabb.center()[0], 0.5394, 1e-4); EXPECT_NEAR(aabb.center()[1], 0.1880, 1e-4); EXPECT_NEAR(aabb.center()[2], 1.1665, 1e-4); EXPECT_NEAR(aabb.sizes()[0], 0.2209, 1e-4); EXPECT_NEAR(aabb.sizes()[1], 0.1201, 1e-4); EXPECT_NEAR(aabb.sizes()[2], 0.2901, 1e-4); #if VISUALIZE_PR2_RVIZ std::cout << "Overall bounding box of PR2:" << std::endl; std::string dims[] = { "x", "y", "z" }; for (std::size_t i = 0; i < 3; ++i) { double dim = pr2_aabb[2 * i + 1] - pr2_aabb[2 * i]; double center = dim / 2; std::cout << dims[i] << ": size=" << dim << ", offset=" << (pr2_aabb[2 * i + 1] - center) << std::endl; } // Initialize a ROS publisher char* argv[0]; int argc = 0; rclcpp::init(argc, argv); auto node = rclcpp::Node::make_shared("visualize_pr2"); auto pub_aabb = node->create_publisher<visualization_msgs::Marker>("/visualization_aabb", rmw_qos_profile_default); auto pub_obb = node->create_publisher<visualization_msgs::Marker>("/visualization_obb", rmw_qos_profile_default); rclcpp::Rate loop_rate(10); // Wait for the publishers to establish connections sleep(5); // Prepare the ROS message we will reuse throughout the rest of the function. auto msg = std::make_shared<visualization_msgs::Marker>(); msg->header.frame_id = pr2_state.getRobotModel()->getRootLinkName(); msg->type = visualization_msgs::Marker::CUBE; msg->color.a = 0.5; msg->lifetime.sec = 3000; // Publish the AABB of the whole model msg->ns = "pr2"; msg->pose.position.x = (pr2_aabb[0] + pr2_aabb[1]) / 2; msg->pose.position.y = (pr2_aabb[2] + pr2_aabb[3]) / 2; msg->pose.position.z = (pr2_aabb[4] + pr2_aabb[5]) / 2; msg->pose.orientation.x = msg->pose.orientation.y = msg->pose.orientation.z = 0; msg->pose.orientation.w = 1; msg->scale.x = pr2_aabb[1] - pr2_aabb[0]; msg->scale.y = pr2_aabb[3] - pr2_aabb[2]; msg->scale.z = pr2_aabb[5] - pr2_aabb[4]; pub_aabb->publish(msg); // Publish BBs for all links std::vector<const moveit::core::LinkModel*> links = pr2_state.getRobotModel()->getLinkModelsWithCollisionGeometry(); for (std::size_t i = 0; i < links.size(); ++i) { Eigen::Isometry3d transform = pr2_state.getGlobalLinkTransform(links[i]); // intentional copy, we will translate const Eigen::Vector3d& extents = links[i]->getShapeExtentsAtOrigin(); transform.translate(links[i]->getCenteredBoundingBoxOffset()); moveit::core::AABB aabb; aabb.extendWithTransformedBox(transform, extents); // Publish AABB msg->ns = links[i]->getName(); msg->pose.position.x = transform.translation()[0]; msg->pose.position.y = transform.translation()[1]; msg->pose.position.z = transform.translation()[2]; msg->pose.orientation.x = msg->pose.orientation.y = msg->pose.orientation.z = 0; msg->pose.orientation.w = 1; msg->color.r = 1; msg->color.b = 0; msg->scale.x = aabb.sizes()[0]; msg->scale.y = aabb.sizes()[1]; msg->scale.z = aabb.sizes()[2]; pub_aabb->publish(msg); // Publish OBB (oriented BB) msg->ns += "-obb"; msg->pose.position.x = transform.translation()[0]; msg->pose.position.y = transform.translation()[1]; msg->pose.position.z = transform.translation()[2]; msg->scale.x = extents[0]; msg->scale.y = extents[1]; msg->scale.z = extents[2]; msg->color.r = 0; msg->color.b = 1; Eigen::Quaterniond q(transform.rotation()); msg->pose.orientation.x = q.x(); msg->pose.orientation.y = q.y(); msg->pose.orientation.z = q.z(); msg->pose.orientation.w = q.w(); pub_obb->publish(msg); } // Publish BBs for all attached bodies std::vector<const moveit::core::AttachedBody*> attached_bodies; pr2_state.getAttachedBodies(attached_bodies); for (std::vector<const moveit::core::AttachedBody*>::const_iterator it = attached_bodies.begin(); it != attached_bodies.end(); ++it) { const EigenSTL::vector_Isometry3d& transforms = (*it)->getGlobalCollisionBodyTransforms(); const std::vector<shapes::ShapeConstPtr>& shapes = (*it)->getShapes(); for (std::size_t i = 0; i < transforms.size(); ++i) { Eigen::Vector3d extents = shapes::computeShapeExtents(shapes[i].get()); moveit::core::AABB aabb; aabb.extendWithTransformedBox(transforms[i], extents); // Publish AABB msg->ns = (*it)->getName() + boost::lexical_cast<std::string>(i); msg->pose.position.x = transforms[i].translation()[0]; msg->pose.position.y = transforms[i].translation()[1]; msg->pose.position.z = transforms[i].translation()[2]; msg->pose.orientation.x = msg->pose.orientation.y = msg->pose.orientation.z = 0; msg->pose.orientation.w = 1; msg->color.r = 1; msg->color.b = 0; msg->scale.x = aabb.sizes()[0]; msg->scale.y = aabb.sizes()[1]; msg->scale.z = aabb.sizes()[2]; pub_aabb->publish(msg); // Publish OBB (oriented BB) msg->ns += "-obb"; msg->pose.position.x = transforms[i].translation()[0]; msg->pose.position.y = transforms[i].translation()[1]; msg->pose.position.z = transforms[i].translation()[2]; msg->scale.x = extents[0]; msg->scale.y = extents[1]; msg->scale.z = extents[2]; msg->color.r = 0; msg->color.b = 1; Eigen::Quaterniond q(transforms[i].rotation()); msg->pose.orientation.x = q.x(); msg->pose.orientation.y = q.y(); msg->pose.orientation.z = q.z(); msg->pose.orientation.w = q.w(); pub_obb->publish(msg); } } #endif } TEST_F(TestAABB, TestSimple) { // Contains a link with simple geometry and an offset in the collision link moveit::core::RobotModelBuilder builder("simple", "base_footprint"); geometry_msgs::Pose origin; tf2::toMsg(tf2::Vector3(0, 0, 0.051), origin.position); origin.orientation.w = 1.0; builder.addChain("base_footprint->base_link", "fixed", { origin }); tf2::toMsg(tf2::Vector3(0, 0, 0), origin.position); builder.addCollisionMesh("base_link", "package://moveit_resources/pr2_description/urdf/meshes/base_v0/base_L.stl", origin); tf2::toMsg(tf2::Vector3(0, 0, 0.071), origin.position); builder.addCollisionBox("base_footprint", { 0.001, 0.001, 0.001 }, origin); builder.addVirtualJoint("odom_combined", "base_footprint", "planar", "world_joint"); builder.addGroup({}, { "world_joint" }, "base"); ASSERT_TRUE(builder.isValid()); robot_state::RobotState simple_state = loadModel(builder.build()); std::vector<double> simple_aabb; simple_state.computeAABB(simple_aabb); ASSERT_EQ(simple_aabb.size(), 6u); EXPECT_NEAR(simple_aabb[0], -0.6682 / 2, 1e-4); EXPECT_NEAR(simple_aabb[1], 0.6682 / 2, 1e-4); EXPECT_NEAR(simple_aabb[2], -0.6682 / 2, 1e-4); EXPECT_NEAR(simple_aabb[3], 0.6682 / 2, 1e-4); EXPECT_NEAR(simple_aabb[4], 0.0510, 1e-4); EXPECT_NEAR(simple_aabb[5], 0.7071, 1e-4); } TEST_F(TestAABB, TestComplex) { // Contains a link with simple geometry and an offset and rotation in the collision link moveit::core::RobotModelBuilder builder("complex", "base_footprint"); geometry_msgs::Pose origin; tf2::toMsg(tf2::Vector3(0, 0, 1.0), origin.position); tf2::Quaternion q; q.setRPY(0, 0, 1.5708); origin.orientation = tf2::toMsg(q); builder.addChain("base_footprint->base_link", "fixed", { origin }); tf2::toMsg(tf2::Vector3(5.0, 0, 1.0), origin.position); builder.addCollisionBox("base_link", { 1.0, 0.1, 0.1 }, origin); tf2::toMsg(tf2::Vector3(4.0, 0, 1.0), origin.position); builder.addCollisionBox("base_link", { 1.0, 0.1, 0.1 }, origin); tf2::toMsg(tf2::Vector3(-5.0, 0.0, -1.0), origin.position); q.setRPY(0, 1.5708, 0); origin.orientation = tf2::toMsg(q); builder.addCollisionBox("base_footprint", { 0.1, 1.0, 0.1 }, origin); builder.addVirtualJoint("odom_combined", "base_footprint", "planar", "world_joint"); builder.addGroup({}, { "world_joint" }, "base"); ASSERT_TRUE(builder.isValid()); robot_state::RobotState complex_state = this->loadModel(builder.build()); EXPECT_NEAR(complex_state.getLinkModel("base_footprint")->getShapeExtentsAtOrigin()[0], 0.1, 1e-4); EXPECT_NEAR(complex_state.getLinkModel("base_footprint")->getShapeExtentsAtOrigin()[1], 1.0, 1e-4); EXPECT_NEAR(complex_state.getLinkModel("base_footprint")->getShapeExtentsAtOrigin()[2], 0.1, 1e-4); EXPECT_NEAR(complex_state.getLinkModel("base_footprint")->getCenteredBoundingBoxOffset()[0], -5.0, 1e-4); EXPECT_NEAR(complex_state.getLinkModel("base_footprint")->getCenteredBoundingBoxOffset()[1], 0.0, 1e-4); EXPECT_NEAR(complex_state.getLinkModel("base_footprint")->getCenteredBoundingBoxOffset()[2], -1.0, 1e-4); EXPECT_NEAR(complex_state.getLinkModel("base_link")->getShapeExtentsAtOrigin()[0], 1.1, 1e-4); EXPECT_NEAR(complex_state.getLinkModel("base_link")->getShapeExtentsAtOrigin()[1], 1.0, 1e-4); EXPECT_NEAR(complex_state.getLinkModel("base_link")->getShapeExtentsAtOrigin()[2], 0.1, 1e-4); EXPECT_NEAR(complex_state.getLinkModel("base_link")->getCenteredBoundingBoxOffset()[0], 4.5, 1e-4); EXPECT_NEAR(complex_state.getLinkModel("base_link")->getCenteredBoundingBoxOffset()[1], 0.0, 1e-4); EXPECT_NEAR(complex_state.getLinkModel("base_link")->getCenteredBoundingBoxOffset()[2], 1.0, 1e-4); std::vector<double> complex_aabb; complex_state.computeAABB(complex_aabb); ASSERT_EQ(complex_aabb.size(), 6u); EXPECT_NEAR(complex_aabb[0], -5.05, 1e-4); EXPECT_NEAR(complex_aabb[1], 0.5, 1e-4); EXPECT_NEAR(complex_aabb[2], -0.5, 1e-4); EXPECT_NEAR(complex_aabb[3], 5.05, 1e-4); EXPECT_NEAR(complex_aabb[4], -1.05, 1e-4); EXPECT_NEAR(complex_aabb[5], 2.05, 1e-4); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
// // Created by Administrator on 2019/12/20. // #include "FriendFunc.h" FriendFunc::FriendFunc() { this->name = "Dream"; } char* FriendFunc::getName() { return this->name; }
//+--------------------------------------------------------------------------- // // Microsoft Forms // Copyright (C) Microsoft Corporation, 1994-1996 // // File: rulestyl.hxx // // Contents: Support for Cascading Style Sheets Object Model. // // CRuleStyle // //---------------------------------------------------------------------------- #ifndef I_RULESTYL_HXX_ #define I_RULESTYL_HXX_ #pragma INCMSG("--- Beg 'rulestyl.hxx'") #ifndef X_STYLE_HXX_ #define X_STYLE_HXX_ #include "style.hxx" #endif class CStyleSheetRule; MtExtern(CRuleStyle) //+--------------------------------------------------------------------------- // // Class: CRuleStyle // //---------------------------------------------------------------------------- class CRuleStyle : public CStyle { DECLARE_CLASS_TYPES(CRuleStyle, CStyle) public: DECLARE_MEMCLEAR_NEW_DELETE(Mt(CRuleStyle)) CRuleStyle( CStyleSheetRule *pRule ); ~CRuleStyle(); inline void ClearRule() { _pRule = NULL; _pAA = NULL; }; //Data access HRESULT PrivatizeProperties(CVoid **ppv) {return S_OK;} //Parsing methods HRESULT OnPropertyChange(DISPID dispid, DWORD dwFlags); //CBase methods STDMETHOD(PrivateQueryInterface)(REFIID iid, void ** ppv); HRESULT QueryInterface(REFIID iid, void **ppv){return PrivateQueryInterface(iid, ppv);} STDMETHODIMP_(ULONG) PrivateAddRef(); STDMETHODIMP_(ULONG) PrivateRelease(); virtual CAtomTable * GetAtomTable ( BOOL *pfExpando = NULL ); void Passivate(); struct CLASSDESC { CBase::CLASSDESC _classdescBase; void*_apfnTearOff; }; // Helper for HDL file virtual CAttrArray **GetAttrArray ( void ) const; NV_DECLARE_TEAROFF_METHOD(GetDispID, getdispid, (BSTR bstrName, DWORD grfdex, DISPID *pid)); NV_DECLARE_TEAROFF_METHOD(InvokeEx, invokeex, (DISPID id, LCID lcid, WORD wFlags, DISPPARAMS *pdp, VARIANT *pvarRes, EXCEPINFO *pei, IServiceProvider *pSrvProvider)); // Override all property gets/puts so that the invtablepropdesc points to // our local functions to give us a chance to pass the pAA of CStyleRule and // not CRuleStyle. NV_DECLARE_TEAROFF_METHOD(put_StyleComponent, PUT_StyleComponent, (BSTR v)); NV_DECLARE_TEAROFF_METHOD(put_Url, PUT_Url, (BSTR v)); NV_DECLARE_TEAROFF_METHOD(put_String, PUT_String, (BSTR v)); NV_DECLARE_TEAROFF_METHOD(put_Short, PUT_Short, (short v)); NV_DECLARE_TEAROFF_METHOD(put_Long, PUT_Long, (long v)); NV_DECLARE_TEAROFF_METHOD(put_Bool, PUT_Bool, (VARIANT_BOOL v)); NV_DECLARE_TEAROFF_METHOD(put_Variant, PUT_Variant, (VARIANT v)); NV_DECLARE_TEAROFF_METHOD(put_DataEvent, PUT_DataEvent, (VARIANT v)); NV_DECLARE_TEAROFF_METHOD(get_Url, GET_Url, (BSTR *p)); NV_DECLARE_TEAROFF_METHOD(get_StyleComponent, GET_StyleComponent, (BSTR *p)); NV_DECLARE_TEAROFF_METHOD(get_Property, GET_Property, (void *p)); #ifndef NO_EDIT virtual IOleUndoManager * UndoManager(void); virtual BOOL QueryCreateUndo(BOOL fRequiresParent, BOOL fDirtyChange = TRUE); #endif // NO_EDIT #define _CRuleStyle_ #include "style.hdl" protected: DECLARE_CLASSDESC_MEMBERS; CStyleSheetRule *_pRule; // May be NULL if disconnected. }; #pragma INCMSG("--- End 'rulestyl.hxx'") #else #pragma INCMSG("*** Dup 'rulestyl.hxx'") #endif
// Copyright (c) 2018 The Dash Core developers // Copyright (c) 2019 The BitGreen Core developers // Copyright (c) 2019 The PineCoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <special/specialdb.h> std::unique_ptr<CSpecialDB> pspecialdb; CSpecialDB::CSpecialDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(fMemory ? "" : (GetDataDir() / "specialdb"), nCacheSize, fMemory, fWipe), rootBatch(db), rootDBTransaction(db, rootBatch), curDBTransaction(rootDBTransaction, rootDBTransaction) { } bool CSpecialDB::CommitRootTransaction() { assert(curDBTransaction.IsClean()); rootDBTransaction.Commit(); bool ret = db.WriteBatch(rootBatch); rootBatch.Clear(); return ret; } bool CSpecialDB::VerifyBestBlock(const uint256& hash) { // Make sure specialdb is consistent. // If we already have best block hash saved, the previous block should match it. uint256 hashBestBlock; bool fHasBestBlock = Read("b_b", hashBestBlock); uint256 hashBlockIndex = fHasBestBlock ? hash : uint256(); assert(hashBestBlock == hashBlockIndex); return fHasBestBlock; } void CSpecialDB::WriteBestBlock(const uint256& hash) { Write("b_b", hash); }
#pragma once #include <string> #include <sstream> #include <stdio.h> #include <sys/stat.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include <stdarg.h> #include <cassert> #include <stdexcept> #include <system_error> enum LogLevel { NONE = 0, CRITICAL, // An invariant is breached, or program state is jeopardized so that exit is required. ERROR, // An invariant is breached, the current user operation/intent will fail, but the program can recover or resume. WARNING, // An invariant may be breached, but program state is OK and the user operation will succeed. PRINT, // Status messages that record nominal execution but that is neither large nor proportional to input complexity. FUSS, // Unexpected condition that is part of proper execution but may indicate improper usage by the user. INFO, // Status messages that are not large in proportion to input complexity. DETAIL, // Status messages that can be large in proportion to input complexity. DBG, // Messages that are intended to show specific information with the intent of detecting preconditions to failure. DBG2 // The firehose. }; template<int Level, const char* Name, typename...Sinks> struct Log { inline static int level = Level; static void write (const char* szstr, int size) { (Sinks::write(szstr,size), ...); } template<typename...Ps> static void fmtprint (int lvl, const char* fmt, Ps...ps); public: static void initialize () { } static void finalize () {} template<int Lvl, typename...Ps> static void log_at_level (const char* fmt, Ps...ps); template<typename...Ps> static void debug2 (const char* fmt, Ps...ps) { log_at_level<LogLevel::DBG2,Ps...> (fmt,ps...); } template<typename...Ps> static void debug (const char* fmt, Ps...ps) { log_at_level<LogLevel::DBG, Ps...> (fmt,ps...); } template<typename...Ps> static void detail (const char* fmt, Ps...ps) { log_at_level<LogLevel::DETAIL,Ps...> (fmt,ps...); } template<typename...Ps> static void info (const char* fmt, Ps...ps) { log_at_level<LogLevel::INFO,Ps...> (fmt,ps...); } template<typename...Ps> static void print (const char* fmt, Ps...ps) { log_at_level<LogLevel::PRINT,Ps...> (fmt,ps...); } template<typename...Ps> static void fuss (const char* fmt, Ps...ps) { log_at_level<LogLevel::FUSS,Ps...> (fmt,ps...); } template<typename...Ps> static void warning (const char* fmt, Ps...ps) { log_at_level<LogLevel::WARNING,Ps...> (fmt,ps...); } template<typename...Ps> static void error (const char* fmt, Ps...ps) { log_at_level<LogLevel::ERROR,Ps...> (fmt,ps...); } template<typename...Ps> static void critical (const char* fmt, Ps...ps) { log_at_level<LogLevel::CRITICAL,Ps...> (fmt,ps...); } }; template<int Level, const char* Name> struct Log<Level,Name,FILE> { inline static int level = Level; inline static FILE* file; static void initialize_with_filename(const std::string& filename); static void initialize_with_handle(FILE* fh) { file = fh; } static void finalize(); static void write (const char* szstr, int size); }; template<int Level, const char* Name> void Log<Level, Name, FILE>::initialize_with_filename (const std::string& filename) { using namespace std; file = fopen(filename.c_str(), "w+"); if (!file) { throw std::system_error(errno, std::system_category()); } } template<int Level, const char* Name> void Log<Level, Name, FILE>::finalize () { assert(file != nullptr); if (fclose(file)) { throw std::system_error(errno, std::system_category()); } } template<int Level, const char* Name> inline void Log<Level, Name, FILE>::write (const char* szstr, int size) { if (!fwrite(szstr, size, 1, file)) { throw std::system_error(errno, std::system_category()); } if (!fputc('\n',file)) { throw std::system_error(errno, std::system_category()); } if (fflush(file)) { throw std::system_error(errno, std::system_category()); } } template<int Level, const char* Name, typename...Sinks> template<typename...Ps> inline void Log<Level, Name, Sinks...>::fmtprint (int lvl, const char* fmt, Ps...ps) { char entry[1024]; char msg[960]; int chrs = snprintf(msg,960,fmt,ps...); struct timespec ts; clock_gettime(CLOCK_MONOTONIC_COARSE, &ts); chrs = snprintf(entry, 1024,"%ld.%06ld [%s-%d] %s", ts.tv_sec, ts.tv_nsec/1000, Name, lvl, msg); write(entry,chrs); } #pragma GCC diagnostic ignored "-Wunused-but-set-parameter" template<int Level, const char* Name, typename...Sinks> template<int Lvl, typename...Ps> inline void Log<Level,Name,Sinks...>::log_at_level (const char* fmt, Ps...ps) { if constexpr (Level >= Lvl) { fmtprint(Lvl, fmt, ps...); } }
/* * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #include <AK/Singleton.h> #include <Kernel/Devices/NullDevice.h> #include <Kernel/Sections.h> namespace Kernel { static Singleton<NullDevice> s_the; UNMAP_AFTER_INIT void NullDevice::initialize() { s_the.ensure_instance(); } NullDevice& NullDevice::the() { return *s_the; } UNMAP_AFTER_INIT NullDevice::NullDevice() : CharacterDevice(1, 3) { } UNMAP_AFTER_INIT NullDevice::~NullDevice() { } bool NullDevice::can_read(const FileDescription&, size_t) const { return true; } KResultOr<size_t> NullDevice::read(FileDescription&, u64, UserOrKernelBuffer&, size_t) { return 0; } KResultOr<size_t> NullDevice::write(FileDescription&, u64, const UserOrKernelBuffer&, size_t buffer_size) { return buffer_size; } }
# include <Siv3D.hpp> # include <HamFramework.hpp> # include "GameInfo.hpp" # include "Typing.hpp" # include "CheckBox.hpp" # include "WordFactory.hpp" # include "KeyboardInput.hpp" /////////////////////////////////////////////////////////////////////// // // 間違えた時のエフェクト // struct TypoEffect : IEffect { Vec2 pos; TypoEffect(const double x, const double y) : pos(Vec2(x, y)) {} bool update(double timeSec) { const double e = EaseOut(Easing::Quad, timeSec); FontAsset(U"SmallText")(U"Miss!").drawAt(pos.x, pos.y - 20 * e, ColorF(Palette::Red, 1 - timeSec)); return timeSec < 1.0; } }; /////////////////////////////////////////////////////////////////////// // // キーボードを描画 // const Array<Array<char32>> qwerty = { { U'1', U'2', U'3', U'4', U'5', U'6', U'7', U'8', U'9', U'0', U'-', U'^', U'¥' }, { U'Q', U'W', U'E', U'R', U'T', U'Y', U'U', U'I', U'O', U'P', U'@', U'[' }, { U'A', U'S', U'D', U'F', U'G', U'H', U'J', U'K', U'L', U';', U':', U']' }, { U'Z', U'X', U'C', U'V', U'B', U'N', U'M', U',', U'.', U'/', U'_' } }; void drawKeyboard(const double x, const double y, const Array<char32> &highlight) { qwerty.each_index([&] (const int32 i, const auto& line) { line.each_index([&] (const int32 j, const char32 c) { const auto pressed = highlight.includes(c); const auto& color = pressed ? Palette::Lightpink : Palette::White; RoundRect(x + j * 80 + i * 40, y + i * 80, 70, 70, 5).draw(color); FontAsset(U"Text")(c).drawAt(x + j * 80 + i * 40 + 35, y + i * 80 + 35, GameInfo::BackgroundColor); }); }); } void drawFingers(const char32 c) { const static std::array<String, 10> keysCorrespondingToEachFngers = { U"", U"5TGB4RFV", U"3EDC", U"2WSX", U"1QAZ", U"", U"6YHN7UJM", U"8IK,", U"9OL.", U"0P;/-@:_^[]¥", }; constexpr static std::array<int32, 5> fingerLength = {30, 80, 100, 80, 50}; const int32 offsetX = Scene::Center().x; for (const int32 i : step(5)) { RoundRect(offsetX - 100 - i * 50, 720 - fingerLength[i], 40, fingerLength[i] + 20, 20) .draw(keysCorrespondingToEachFngers[i].includes(c) ? Palette::Lightpink : Palette::White); RoundRect(offsetX + 100 + i * 50, 720 - fingerLength[i], 40, fingerLength[i] + 20, 20) .draw(keysCorrespondingToEachFngers[i + 5].includes(c) ? Palette::Lightpink : Palette::White); } } /////////////////////////////////////////////////////////////////////// // // セーブ用スコアデータ // struct ScoreData { int32 timeMillisec = 0; int32 wordCount = 0; int32 correctTypeCount = 0; int32 typoCount = 0; Date date = Date(1970, 1, 1); bool isRandom = false; bool isTimeAttack = false; double speed() const { return timeMillisec == 0 ? -1 : correctTypeCount * 1000.0 / timeMillisec; } int32 score() const { return (timeMillisec == 0 || typoCount + correctTypeCount == 0) ? -1 : speed() * 126 * pow((double) correctTypeCount / (typoCount + correctTypeCount), 2); } template <class Archive> void SIV3D_SERIALIZE(Archive& archive) { archive(timeMillisec, wordCount, correctTypeCount, typoCount, date, isRandom, isTimeAttack); } }; /////////////////////////////////////////////////////////////////////// // // セーブ用設定データ // struct ConfigData { std::array<bool, 4> activeLines = {true, true, true, true}; bool showRomaji = true; bool showKeyboard = true; bool showFingers = true; template <class Archive> void SIV3D_SERIALIZE(Archive& archive) { archive(activeLines, showRomaji, showKeyboard, showFingers); } }; /////////////////////////////////////////////////////////////////////// // // デフォルトのハイスコア // const std::array<std::array<ScoreData, 5>, 5> defaultHighScores; /////////////////////////////////////////////////////////////////////// // // 全てのシーンからアクセスできるデータ // struct GameData { WordType type = WordType::None; Array<char32> allowedChars; bool isTimeAttack = false; ScoreData lastScore; ConfigData config; }; using MyApp = SceneManager<String, GameData>; /////////////////////////////////////////////////////////////////////// // // タイトル画面 // class Title : public MyApp::Scene { Stopwatch m_effectBackgroundStopwatch{ StartImmediately::Yes }; Stopwatch m_effectMenuItemStopwatch{ StartImmediately::Yes }; const Array<RoundRect> m_menuRects = { RoundRect(Arg::center = Vec2(Scene::Center().x - 220, 300), 360, 100, 50), RoundRect(Arg::center = Vec2(Scene::Center().x - 220, 440), 360, 100, 50), RoundRect(Arg::center = Vec2(Scene::Center().x + 220, 300), 360, 100, 50), RoundRect(Arg::center = Vec2(Scene::Center().x + 220, 440), 360, 100, 50), }; const Array<Circle> m_menuCircles = { Circle(486, 610, 60), Circle(640, 630, 60), Circle(794, 610, 60), }; const Array<String> m_menuTexts = { U"スコア", U"終了", U"設定", }; public: Title(const InitData& init) : IScene(init) { if (FileSystem::Exists(GameInfo::ConfigFilePath)) { try { Deserializer<BinaryReader>{GameInfo::ConfigFilePath}(getData().config); } catch (cereal::Exception e) { Serializer<BinaryWriter>{GameInfo::ConfigFilePath}(getData().config); } } else { Serializer<BinaryWriter>{GameInfo::ConfigFilePath}(getData().config); } } void update() override { bool handCursor = false; m_menuRects.each_index([&] (int i, const auto& shape) { handCursor |= shape.mouseOver(); if (shape.leftClicked()) { if (i == 0) { getData().type = WordType::Random; getData().isTimeAttack = true; changeScene(U"Select"); } else if (i == 1) { getData().type = WordType::Text; getData().isTimeAttack = true; changeScene(U"Game"); } else if (i == 2) { getData().type = WordType::Random; getData().isTimeAttack = false; changeScene(U"Select"); } else if (i == 3) { getData().type = WordType::Text; getData().isTimeAttack = false; changeScene(U"Game"); } return; } }); m_menuCircles.each_index([&] (int i, const auto& shape) { handCursor |= shape.mouseOver(); if (shape.leftClicked()) { if (i == 0) { changeScene(U"Score"); } else if (i == 1) { System::Exit(); } else if (i == 2) { changeScene(U"Config"); } return; } }); Cursor::RequestStyle(handCursor ? CursorStyle::Hand : CursorStyle::Default); } void draw() const override { FontAsset(U"Title")(GameInfo::Title).drawAt(Scene::Center().x, 80); FontAsset(U"MenuLarge")(U"20単語").drawAt(Scene::Center().x - 220, 200); FontAsset(U"MenuLarge")(U"2分間").drawAt(Scene::Center().x + 220, 200); m_menuRects.each_index([&] (const int32 i, const auto& shape) { shape.draw(); FontAsset(U"MenuLarge")(i % 2 == 0 ? U"ポジション練習" : U"文章・単語練習").drawAt(shape.center(), Palette::Black); }); m_menuCircles.each_index([&] (const int32 i, const auto& shape) { shape.draw(); FontAsset(U"MenuSmall")(m_menuTexts[i]).drawAt(shape.center, Palette::Black); }); const Size versionSize = FontAsset(U"Version")(GameInfo::Version).region().size.asPoint(); FontAsset(U"Version")(GameInfo::Version).drawAt(Scene::Size().moveBy(-versionSize)); } }; /////////////////////////////////////////////////////////////////////// // // 設定画面 // class Config : public MyApp::Scene { const Circle m_back = Circle(Scene::Center().x, 630, 60); CheckBox m_romaji = CheckBox(100, 150, true, U"ローマ字を表示する", FontAsset(U"MenuSmall")); CheckBox m_keyboard = CheckBox(100, 250, true, U"キーボードを表示する", FontAsset(U"MenuSmall")); CheckBox m_fingers = CheckBox(150, 350, true, U"指を表示する", FontAsset(U"MenuSmall")); void saveConfig() { getData().config.showRomaji = m_romaji; getData().config.showKeyboard = m_keyboard; getData().config.showFingers = m_fingers; Serializer<BinaryWriter>{GameInfo::ConfigFilePath}(getData().config); } void drawGameScreen() const { Transformer2D t2(Mat3x2::Translate(600, 100)); Transformer2D t1(Mat3x2::Scale(0.5)); Rect(0, 0, 1280, 720).drawFrame(); if (m_keyboard) { drawKeyboard(115, m_fingers ? 280 : 340, { U'B' }); if (m_fingers) { drawFingers(U'B'); Rect(0, 720, 1280, 740).draw(GameInfo::BackgroundColor); } } const int32 strY = m_fingers ? 140 : 180; FontAsset(U"Text")(U"ぶんしょう").draw(115, strY); if (m_romaji) FontAsset(U"SmallText")(U" BU N SHO U").draw(115, strY + 60); FontAsset(U"GameScore")(U"単語数: 0 / 0").draw(115, 40); FontAsset(U"GameScore")(U"時間: 00'00").draw(500, 40); if (!m_keyboard) TextureAsset(U"Tori").draw(850, 400); } public: Config(const InitData& init) : IScene(init) { m_romaji.setChecked(getData().config.showRomaji); m_keyboard.setChecked(getData().config.showKeyboard); const auto&& updateCheck = [&] (const bool checked) { m_fingers.setChecked(checked); m_fingers.setEnabled(checked); }; m_keyboard.setOnChangeHandler(updateCheck); updateCheck(m_keyboard); m_fingers.setChecked(getData().config.showFingers); } void update() { m_romaji.update(); m_keyboard.update(); m_fingers.update(); if (m_back.leftClicked()) { saveConfig(); changeScene(U"Title"); } if (m_back.mouseOver()) Cursor::RequestStyle(CursorStyle::Hand); } void draw() const { drawGameScreen(); m_romaji.draw(); m_keyboard.draw(); m_fingers.draw(); m_back.draw(); FontAsset(U"MenuSmall")(U"戻る").drawAt(m_back.center, Palette::Black); } }; /////////////////////////////////////////////////////////////////////// // // 選択画面 // class Select : public MyApp::Scene { bool m_advanced = false; Array<char32> m_allowedChars; Array<CheckBox> m_lineCheckboxes = { CheckBox(80, 195, true), CheckBox(80, 275, true), CheckBox(80, 355, true), CheckBox(80, 435, true), }; Circle m_start = Circle(Scene::Center().x + 70, 630, 60); Circle m_back = Circle(Scene::Center().x - 70, 630, 60); void saveLineSelection() { m_lineCheckboxes.each_index([&] (const int32 i, const auto& checkbox) { getData().config.activeLines[i] = checkbox; }); Serializer<BinaryWriter>{GameInfo::ConfigFilePath}(getData().config); } public: Select(const InitData& init) : IScene(init) { const auto onChange = [&] (const bool _) { m_allowedChars.clear(); m_lineCheckboxes.each_index([&] (const int32 i, const auto& _checkbox) { if (_checkbox) m_allowedChars.append(qwerty[i]); }); }; m_lineCheckboxes.each_index([&] (const int32 i, auto& checkbox) { checkbox.setChecked(getData().config.activeLines[i]); checkbox.setOnChangeHandler(onChange); }); onChange(true); } void update() { m_lineCheckboxes.each([&] (auto& checkbox) { checkbox.update(); }); if (m_start.leftClicked()) { getData().allowedChars = m_allowedChars; saveLineSelection(); changeScene(U"Game", 2000); } if (m_back.leftClicked()) { saveLineSelection(); changeScene(U"Title"); } if (m_start.mouseOver() || m_back.mouseOver()) Cursor::RequestStyle(CursorStyle::Hand); } void draw() const { FontAsset(U"Menu")(U"チェックが入っている列を練習します").drawAt(Scene::Center().x, 80); m_lineCheckboxes.each([&] (const auto& checkbox) { checkbox.draw(); }); drawKeyboard(160, 190, m_allowedChars); m_start.draw(Palette::White); FontAsset(U"MenuSmall")(U"始める").drawAt(m_start.center, Palette::Black); m_back.draw(Palette::White); FontAsset(U"MenuSmall")(U"戻る").drawAt(m_back.center, Palette::Black); } }; /////////////////////////////////////////////////////////////////////// // // ゲーム // class Game : public MyApp::Scene { Typing m_typing; WordFactory m_factory; bool m_timeattack; int32 m_wordCount = 0, m_correctTypeCount = 0, m_typoCount = 0; Stopwatch m_countDownTimer; Stopwatch m_gameTimer; Effect m_effect; bool onCountDown() const { return m_countDownTimer.isRunning() && m_countDownTimer < 4000ms; } bool onGame() const { return m_gameTimer.isRunning(); } public: Game(const InitData& init) : IScene(init), m_factory(getData().type, U"words.txt", getData().allowedChars), m_timeattack(getData().isTimeAttack) { getData().lastScore = ScoreData(); m_typing.setCorrectWordHandler([&] { m_wordCount++; }); m_typing.setNextWordHandler([&] { return m_timeattack ? (m_wordCount < GameInfo::GameNumberOfWords ? m_factory.nextWord() : U" ") : m_factory.nextWord(); }); m_factory.loadWords(); } void update() override { if (KeyEscape.down()) { changeScene(U"Title", 2000); } if (!onGame() && !m_countDownTimer.isRunning()) { m_countDownTimer.start(); } if (!onGame() && m_countDownTimer >= 3000ms) { m_gameTimer.start(); } if (!onGame()) { return; } if ((m_timeattack && m_wordCount >= GameInfo::GameNumberOfWords) || (!m_timeattack && m_gameTimer.ms() >= GameInfo::GameTimeMillisec)) { getData().lastScore = ScoreData{ m_gameTimer.ms(), m_wordCount, m_correctTypeCount, m_typoCount, Date::Today(), getData().type == WordType::Random, m_timeattack }; changeScene(U"Result", 2000); } Array<char32> m_typedChars; m_typedChars = KeyboardInput::getInputChars(); m_typing.update(); char32 lastTypo = 0; for (const auto s : m_typedChars) { if (m_typing.onCharInput(s)) { m_correctTypeCount++; } else { lastTypo = s; m_typoCount++; } } qwerty.each_index([&] (const int32 i, const auto& line) { line.each_index([&] (const int32 j, const char32 c) { if (c == lastTypo) { int32 x, y; if (getData().config.showFingers) { x = 115 + 35 + j * 80 + i * 40; y = 280 + 35 + i * 80; } else if (getData().config.showKeyboard) { x = 115 + 35 + j * 80 + i * 40; y = 340 + 35 + i * 80; } else { auto [offsetx, offsety] = m_typing.getNextCharPos(); x = 115 + offsetx; y = 200 + offsety; } m_effect.add<TypoEffect>(x, y); } }); }); lastTypo = 0; } void draw() const override { if (onCountDown()) { const int32 timeMillisec = Max((3999 - m_countDownTimer.ms()), 0); const int32 countDown = timeMillisec / 1000; const double e = EaseIn(Easing::Expo, (timeMillisec % 1000) / 1000.0); if (countDown > 0) { Transformer2D t(Mat3x2::Scale(1.0 + e * 2, Scene::Center())); FontAsset(U"CountDown")(countDown).drawAt(Scene::Center()); } else { Transformer2D t(Mat3x2::Scale(1.0 + (1.0 - e) * 2, Scene::Center())); FontAsset(U"CountDown")(U"スタート").drawAt(Scene::Center(), AlphaF(e)); } } if (!onGame()) { return; } const char32 nextChar = m_typing.getNextChar(); if (getData().config.showKeyboard) { drawKeyboard(115, getData().config.showFingers ? 280 : 340, { nextChar }); if (getData().config.showFingers) drawFingers(nextChar); } const int32 strY = getData().config.showFingers ? 170 : 200; m_typing.draw(115, strY, true, getData().config.showRomaji); if (m_timeattack) { const int32 timeMillisec = m_gameTimer.ms(); FontAsset(U"GameScore")(U"単語数: {} / {}"_fmt(m_wordCount, GameInfo::GameNumberOfWords)).draw(115, 40); FontAsset(U"GameScore")(U"時間: {:0>2}'{:0>2}"_fmt(timeMillisec / 1000, timeMillisec % 1000 / 10)).draw(500, 40); } else { const int32 timeLeftMillisec = Max(GameInfo::GameTimeMillisec - m_gameTimer.ms(), 0); FontAsset(U"GameScore")(U"単語数: {}"_fmt(m_wordCount)).draw(115, 40); FontAsset(U"GameScore")(U"時間: {:0>2}'{:0>2}"_fmt(timeLeftMillisec / 1000, timeLeftMillisec % 1000 / 10)).draw(500, 40); } const Size versionSize = FontAsset(U"Version")(U"escキーでタイトルへ").region().size.asPoint(); FontAsset(U"Version")(U"escキーでタイトルへ").drawAt(Scene::Size().moveBy(-versionSize)); if (!getData().config.showKeyboard) TextureAsset(U"Tori").draw(850, 400); m_effect.update(); } }; /////////////////////////////////////////////////////////////////////// // // 結果画面 // class Result : public MyApp::Scene { private: std::array<std::array<ScoreData, 5>, 5> m_highScores = defaultHighScores; const Circle titleButton = Circle(Scene::Center().x, 630, 60); public: Result(const InitData& init) : IScene(init) { if (FileSystem::Exists(GameInfo::SaveFilePath)) { try { Deserializer<BinaryReader>{GameInfo::SaveFilePath}(m_highScores); } catch (cereal::Exception e) { Serializer<BinaryWriter>{GameInfo::SaveFilePath}(m_highScores); } } else { Serializer<BinaryWriter>{GameInfo::SaveFilePath}(m_highScores); } bool modified = false; const auto updateScores = [&] (std::array<ScoreData, 5>& scores) { if (scores.back().score() <= getData().lastScore.score()) { scores.back() = getData().lastScore; std::sort(scores.begin(), scores.end(), [] (const ScoreData& a, const ScoreData& b) { return a.score() > b.score() ? true : a.score() == b.score() ? a.date > b.date : false; }); modified = true; } }; updateScores(m_highScores[0]); const int32 type_index = getData().type == WordType::Random ? 0 : 1; const int32 timeattack_index = getData().isTimeAttack ? 0 : 2; updateScores(m_highScores[1 + type_index + timeattack_index]); if (modified) Serializer<BinaryWriter>{GameInfo::SaveFilePath}(m_highScores); } void update() override { if (titleButton.leftClicked() || KeyEscape.down()) { changeScene(U"Title"); } if (titleButton.mouseOver()) { Cursor::RequestStyle(CursorStyle::Hand); } } void draw() const override { FontAsset(U"Result")(U"結果").drawAt(Scene::Center().x, 80); const auto& score = getData().lastScore; FontAsset(U"GameScore")(U"単語数:").draw(Arg::topRight = Vec2(Scene::Center().x - 20, 180)); FontAsset(U"GameScore")(score.wordCount, U"語").draw(Scene::Center().x + 20, 180); FontAsset(U"GameScore")(U"時間:").draw(Arg::topRight = Vec2(Scene::Center().x - 20, 240)); FontAsset(U"GameScore")(U"{:0>2}'{:0>2}"_fmt(score.timeMillisec / 1000, score.timeMillisec % 1000 / 10)).draw(Scene::Center().x + 20, 240); FontAsset(U"GameScore")(U"正しいタイプ数:").draw(Arg::topRight = Vec2(Scene::Center().x - 20, 300)); FontAsset(U"GameScore")(score.correctTypeCount,U" type", score.correctTypeCount == 1 ? U"" : U"s").draw(Scene::Center().x + 20, 300); FontAsset(U"GameScore")(U"ミスタイプ数:").draw(Arg::topRight = Vec2(Scene::Center().x - 20, 360)); FontAsset(U"GameScore")(score.typoCount, U" type", score.typoCount == 1 ? U"" : U"s").draw(Scene::Center().x + 20, 360); FontAsset(U"GameScore")(U"タイプの速さ:").draw(Arg::topRight = Vec2(Scene::Center().x - 20, 420)); FontAsset(U"GameScore")(U"{:.3g}"_fmt(score.speed()), U" types/s").draw(Scene::Center().x + 20, 420); FontAsset(U"GameScore")(U"スコア:").draw(Arg::topRight = Vec2(Scene::Center().x - 20, 480)); FontAsset(U"GameScore")(score.score()).draw(Scene::Center().x + 20, 480); titleButton.draw(); FontAsset(U"MenuSmall")(U"戻る").drawAt(titleButton.center, Palette::Black); } }; /////////////////////////////////////////////////////////////////////// // // ハイスコア一覧 // class Score : public MyApp::Scene { const Array<String> tab_texts = { U"総合", U"20問ポジション", U"20問文章・単語", U"2分ポジション", U"2分文章・単語", }; Array<RoundRect> tabs; int32 m_page = 0; std::array<std::array<ScoreData, 5>, 5> m_highScores = defaultHighScores; const Circle titleButton = Circle(Scene::Center().x, 630, 60); static String getOrdinal(const int32 n) { switch (n) { case 1: return U"1st "; case 2: return U"2nd "; case 3: return U"3rd "; default: return U"{}th "_fmt(n); } } static const Color& getOrdinalColor(const int32 n) { switch (n) { case 1: return Palette::Gold; case 2: return Palette::Silver; case 3: return Palette::Brown; default: return Palette::White; } } public: Score(const InitData& init) : IScene(init) { if (FileSystem::Exists(GameInfo::SaveFilePath)) { try { Deserializer<BinaryReader>{GameInfo::SaveFilePath}(m_highScores); } catch (cereal::Exception e) { Serializer<BinaryWriter>{GameInfo::SaveFilePath}(m_highScores); } } else { Serializer<BinaryWriter>{GameInfo::SaveFilePath}(m_highScores); } tabs.resize(5); for (const auto i : step(5)) { tabs[i] = RoundRect(20 + i * 210, 20, 200, 60, 30); } } void update() override { if (KeyEscape.down() || titleButton.leftClicked()) { changeScene(U"Title"); } bool hover = false; tabs.each_index([&] (const int32 i, const auto& shape) { hover |= shape.mouseOver(); if (shape.leftClicked()) { m_page = static_cast<int32>(i); return; } }); if (titleButton.mouseOver()) { hover = true; } if (hover) { Cursor::RequestStyle(CursorStyle::Hand); } } void draw() const override { const int32 h = FontAsset(U"ScoreList").height(); const int32 dh = FontAsset(U"ScoreListDetail").height(); tabs.each_index([&] (const int32 i, const auto& shape) { const bool selected = i == m_page; if (selected) { shape.draw(Palette::White); } else { shape.stretched(2).draw(Palette::White); shape.draw(GameInfo::BackgroundColor); } FontAsset(U"MenuSmall")(tab_texts[i]).drawAt(shape.center(), Palette::Black); }); const auto& scores = m_highScores[m_page]; for (int32 i = 0, n = static_cast<int32>(scores.size()) ; i < n ; i++) { const auto& score = scores[i]; const Rect rect = Rect(1000, 80).setCenter(Scene::Center().x, static_cast<int32>(145 + i * 90)); rect.draw(ColorF(1.0, 0.2)); FontAsset(U"ScoreList")(getOrdinal(static_cast<int32>(i + 1))).draw(rect.pos + Point(20, (rect.h - h) / 2), getOrdinalColor(i + 1)); if (score.score() >= 0) { FontAsset(U"ScoreList")(score.score()).draw(rect.pos + Point(140, (rect.h - h) / 2)); FontAsset(U"ScoreListDetail")(score.isRandom ? U"ポジション" : U"文章・単語") .draw(rect.pos + Point(260, rect.h / 4 - dh / 2)); FontAsset(U"ScoreListDetail")(U"{:.3g}"_fmt(score.speed()), U" types/s") .draw(rect.pos + Point(260, rect.h * 3 / 4 - dh / 2)); FontAsset(U"ScoreListDetail")(U"単語数: ", score.wordCount, U"語") .draw(rect.pos + Point(420, rect.h / 4 - dh / 2)); FontAsset(U"ScoreListDetail")(U"時間: {:0>2}'{:0>2}"_fmt(score.timeMillisec / 1000, score.timeMillisec % 1000 / 10)) .draw(rect.pos + Point(420, rect.h * 3 / 4 - dh / 2)); FontAsset(U"ScoreListDetail")(U"正しいタイプ数: ", score.correctTypeCount, U" type", score.correctTypeCount == 1 ? U"" : U"s") .draw(rect.pos + Point(580, rect.h / 4 - dh / 2)); FontAsset(U"ScoreListDetail")(U"ミスタイプ数: ", score.typoCount, U" type", score.typoCount == 1 ? U"" : U"s") .draw(rect.pos + Point(580, rect.h * 3 / 4 - dh / 2)); const Size& dateSize = FontAsset(U"ScoreListDetail")(scores[i].date).region().size.asPoint(); FontAsset(U"ScoreListDetail")(score.date) .draw(rect.br().x - dateSize.x - 40, rect.center().y - dateSize.y / 2); } else { FontAsset(U"ScoreList")(U"-").draw(rect.pos + Point(140, (rect.h - h) / 2)); } } titleButton.draw(); FontAsset(U"MenuSmall")(U"戻る").drawAt(titleButton.center, Palette::Black); } }; /////////////////////////////////////////////////////////////////////// // // スタッフクレジット // class Credit : public MyApp::Scene { Array<std::tuple<String, double, bool>> m_credits; double m_height = 0.0; Stopwatch m_stopwatch{ StartImmediately::Yes }; double yOffset() const { return Scene::Height() + 60 - m_stopwatch.ms() / 20.0; } public: Credit(const InitData& init) : IScene(init) { double y = 0; for (const auto& credit : GameInfo::Credits) { m_credits.emplace_back(credit.first, y, true); y += 70; for (const auto& name : credit.second) { m_credits.emplace_back(name, y, false); y += 60; } y += 60; } m_height = y; } void update() override { if ((MouseL | KeyEscape).down()) { changeScene(U"Title"); } if ((m_height + yOffset()) < 0) { m_stopwatch.restart(); } } void draw() const override { const double offset = yOffset(); for (const auto& credit : m_credits) { FontAsset(std::get<bool>(credit) ? U"CreditBig" : U"CreditSmall")(std::get<String>(credit)) .drawAt(Scene::Center().x, std::get<double>(credit) + offset); } } }; /////////////////////////////////////////////////////////////////////// // // メイン関数 // void Main() { Window::Resize(1280, 720); Window::SetTitle(GameInfo::Title); Scene::SetBackground(GameInfo::BackgroundColor); ////////////////////////////////////////////////////////////// // // 使用するシーン // MyApp manager; manager.setFadeColor(GameInfo::FadeInColor); manager.add<Title>(U"Title"); manager.add<Select>(U"Select"); manager.add<Config>(U"Config"); manager.add<Game>(U"Game"); manager.add<Result>(U"Result"); manager.add<Score>(U"Score"); manager.add<Credit>(U"Credit"); ////////////////////////////////////////////////////////////// // // 使用するフォント // FontAsset::Register(U"Title", GameInfo::TitleFontSize, Typeface::Heavy); FontAsset::Register(U"Menu", 30, Typeface::Bold); FontAsset::Register(U"MenuLarge", 40, Typeface::Bold); FontAsset::Register(U"MenuSmall", 24, Typeface::Bold); FontAsset::Register(U"Version", 14, Typeface::Regular); FontAsset::Register(U"CountDown", 72, Typeface::Bold); FontAsset::Register(U"Text", 50, Typeface::Heavy); FontAsset::Register(U"SmallText", 20, Typeface::Heavy); FontAsset::Register(U"Result", 80, Typeface::Bold); FontAsset::Register(U"ResultButton", 32, Typeface::Regular); FontAsset::Register(U"GameScore", 40, Typeface::Light); FontAsset::Register(U"ScoreList", 50, Typeface::Heavy); FontAsset::Register(U"ScoreListDetail", 20, Typeface::Regular, FontStyle::Italic); FontAsset::Register(U"CreditBig", 32, Typeface::Bold); FontAsset::Register(U"CreditSmall", 28, Typeface::Regular); ////////////////////////////////////////////////////////////// // // 使用するテクスチャ // TextureAsset::Register(U"Tori", Resource(U"textures/tori.png")); ////////////////////////////////////////////////////////////// // // メインループ // while (System::Update()) { if (!manager.update()) { break; } } }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE369_Divide_by_Zero__int_fgets_modulo_72b.cpp Label Definition File: CWE369_Divide_by_Zero__int.label.xml Template File: sources-sinks-72b.tmpl.cpp */ /* * @description * CWE: 369 Divide by Zero * BadSource: fgets Read data from the console using fgets() * GoodSource: Non-zero * Sinks: modulo * GoodSink: Check for zero before modulo * BadSink : Modulo a constant with data * Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files * * */ #include "std_testcase.h" #include <vector> using namespace std; namespace CWE369_Divide_by_Zero__int_fgets_modulo_72 { #ifndef OMITBAD void badSink(vector<int> dataVector) { /* copy data out of dataVector */ int data = dataVector[2]; /* POTENTIAL FLAW: Possibly divide by zero */ printIntLine(100 % data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(vector<int> dataVector) { int data = dataVector[2]; /* POTENTIAL FLAW: Possibly divide by zero */ printIntLine(100 % data); } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink(vector<int> dataVector) { int data = dataVector[2]; /* FIX: test for a zero denominator */ if( data != 0 ) { printIntLine(100 % data); } else { printLine("This would result in a divide by zero"); } } #endif /* OMITGOOD */ } /* close namespace */
/*============================================================================= Copyright (c) 2001-2007 Joel de Guzman 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) ==============================================================================*/ #if !defined(FUSION_INCLUDE_INSERT_RANGE) #define FUSION_INCLUDE_INSERT_RANGE #include <boost/fusion/algorithm/transformation/insert_range.hpp> #endif
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync_file_system/drive_backend/sync_engine.h" #include <utility> #include <vector> #include "base/bind.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/task_scheduler/post_task.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "base/values.h" #include "chrome/browser/drive/drive_notification_manager_factory.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/sync_file_system/drive_backend/callback_helper.h" #include "chrome/browser/sync_file_system/drive_backend/conflict_resolver.h" #include "chrome/browser/sync_file_system/drive_backend/drive_backend_constants.h" #include "chrome/browser/sync_file_system/drive_backend/drive_service_on_worker.h" #include "chrome/browser/sync_file_system/drive_backend/drive_service_wrapper.h" #include "chrome/browser/sync_file_system/drive_backend/drive_uploader_on_worker.h" #include "chrome/browser/sync_file_system/drive_backend/drive_uploader_wrapper.h" #include "chrome/browser/sync_file_system/drive_backend/list_changes_task.h" #include "chrome/browser/sync_file_system/drive_backend/local_to_remote_syncer.h" #include "chrome/browser/sync_file_system/drive_backend/metadata_database.h" #include "chrome/browser/sync_file_system/drive_backend/register_app_task.h" #include "chrome/browser/sync_file_system/drive_backend/remote_change_processor_on_worker.h" #include "chrome/browser/sync_file_system/drive_backend/remote_change_processor_wrapper.h" #include "chrome/browser/sync_file_system/drive_backend/remote_to_local_syncer.h" #include "chrome/browser/sync_file_system/drive_backend/sync_engine_context.h" #include "chrome/browser/sync_file_system/drive_backend/sync_engine_initializer.h" #include "chrome/browser/sync_file_system/drive_backend/sync_task.h" #include "chrome/browser/sync_file_system/drive_backend/sync_worker.h" #include "chrome/browser/sync_file_system/drive_backend/sync_worker_interface.h" #include "chrome/browser/sync_file_system/drive_backend/uninstall_app_task.h" #include "chrome/browser/sync_file_system/file_status_observer.h" #include "chrome/browser/sync_file_system/logger.h" #include "chrome/browser/sync_file_system/syncable_file_system_util.h" #include "components/drive/drive_notification_manager.h" #include "components/drive/drive_uploader.h" #include "components/drive/service/drive_api_service.h" #include "components/drive/service/drive_service_interface.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" #include "components/signin/core/browser/signin_manager.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/service_manager_connection.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/extension_system_provider.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/common/extension.h" #include "google_apis/drive/drive_api_url_generator.h" #include "mojo/public/cpp/bindings/interface_request.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "net/url_request/url_request_context_getter.h" #include "services/device/public/interfaces/constants.mojom.h" #include "services/device/public/interfaces/wake_lock_provider.mojom.h" #include "services/service_manager/public/cpp/connector.h" #include "storage/browser/blob/scoped_file.h" #include "storage/common/fileapi/file_system_util.h" namespace sync_file_system { class RemoteChangeProcessor; namespace drive_backend { constexpr net::NetworkTrafficAnnotationTag kTrafficAnnotation = net::DefineNetworkTrafficAnnotation("sync_file_system", R"( semantics { sender: "Sync FileSystem Chrome API" description: "Sync FileSystem API provides an isolated FileSystem to Chrome " "Apps. The contents of the FileSystem are automatically synced " "among application instances through a hidden folder on Google " "Drive. This service uploades or downloads these files for " "synchronization." trigger: "When a Chrome App uses Sync FileSystem API, or when a file on " "Google Drive is modified." data: "Files created by Chrome Apps via Sync FileSystem API." destination: GOOGLE_OWNED_SERVICE } policy { cookies_allowed: false setting: "This feature cannot be disabled in settings." policy_exception_justification: "Not implemented." })"); std::unique_ptr<drive::DriveServiceInterface> SyncEngine::DriveServiceFactory::CreateDriveService( OAuth2TokenService* oauth2_token_service, net::URLRequestContextGetter* url_request_context_getter, base::SequencedTaskRunner* blocking_task_runner) { return std::unique_ptr< drive::DriveServiceInterface>(new drive::DriveAPIService( oauth2_token_service, url_request_context_getter, blocking_task_runner, GURL(google_apis::DriveApiUrlGenerator::kBaseUrlForProduction), GURL(google_apis::DriveApiUrlGenerator::kBaseThumbnailUrlForProduction), std::string(), /* custom_user_agent */ kTrafficAnnotation)); } class SyncEngine::WorkerObserver : public SyncWorkerInterface::Observer { public: WorkerObserver(base::SequencedTaskRunner* ui_task_runner, base::WeakPtr<SyncEngine> sync_engine) : ui_task_runner_(ui_task_runner), sync_engine_(sync_engine) { sequence_checker_.DetachFromSequence(); } ~WorkerObserver() override { DCHECK(sequence_checker_.CalledOnValidSequence()); } void OnPendingFileListUpdated(int item_count) override { if (ui_task_runner_->RunsTasksInCurrentSequence()) { if (sync_engine_) sync_engine_->OnPendingFileListUpdated(item_count); return; } DCHECK(sequence_checker_.CalledOnValidSequence()); ui_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngine::OnPendingFileListUpdated, sync_engine_, item_count)); } void OnFileStatusChanged(const storage::FileSystemURL& url, SyncFileType file_type, SyncFileStatus file_status, SyncAction sync_action, SyncDirection direction) override { if (ui_task_runner_->RunsTasksInCurrentSequence()) { if (sync_engine_) sync_engine_->OnFileStatusChanged( url, file_type, file_status, sync_action, direction); return; } DCHECK(sequence_checker_.CalledOnValidSequence()); ui_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngine::OnFileStatusChanged, sync_engine_, url, file_type, file_status, sync_action, direction)); } void UpdateServiceState(RemoteServiceState state, const std::string& description) override { if (ui_task_runner_->RunsTasksInCurrentSequence()) { if (sync_engine_) sync_engine_->UpdateServiceState(state, description); return; } DCHECK(sequence_checker_.CalledOnValidSequence()); ui_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngine::UpdateServiceState, sync_engine_, state, description)); } void DetachFromSequence() { sequence_checker_.DetachFromSequence(); } private: scoped_refptr<base::SequencedTaskRunner> ui_task_runner_; base::WeakPtr<SyncEngine> sync_engine_; base::SequenceChecker sequence_checker_; DISALLOW_COPY_AND_ASSIGN(WorkerObserver); }; namespace { void DidRegisterOrigin(const base::TimeTicks& start_time, const SyncStatusCallback& callback, SyncStatusCode status) { base::TimeDelta delta(base::TimeTicks::Now() - start_time); LOCAL_HISTOGRAM_TIMES("SyncFileSystem.RegisterOriginTime", delta); callback.Run(status); } } // namespace std::unique_ptr<SyncEngine> SyncEngine::CreateForBrowserContext( content::BrowserContext* context, TaskLogger* task_logger) { scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner = base::ThreadTaskRunnerHandle::Get(); scoped_refptr<base::SequencedTaskRunner> worker_task_runner = base::CreateSequencedTaskRunnerWithTraits( {base::MayBlock(), base::TaskPriority::BACKGROUND, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); scoped_refptr<base::SequencedTaskRunner> drive_task_runner = base::CreateSequencedTaskRunnerWithTraits( {base::MayBlock(), base::TaskPriority::BACKGROUND, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); Profile* profile = Profile::FromBrowserContext(context); drive::DriveNotificationManager* notification_manager = drive::DriveNotificationManagerFactory::GetForBrowserContext(context); ExtensionService* extension_service = extensions::ExtensionSystem::Get(context)->extension_service(); SigninManagerBase* signin_manager = SigninManagerFactory::GetForProfile(profile); OAuth2TokenService* token_service = ProfileOAuth2TokenServiceFactory::GetForProfile(profile); scoped_refptr<net::URLRequestContextGetter> request_context = content::BrowserContext::GetDefaultStoragePartition(context)-> GetURLRequestContext(); std::unique_ptr<drive_backend::SyncEngine> sync_engine(new SyncEngine( ui_task_runner.get(), worker_task_runner.get(), drive_task_runner.get(), GetSyncFileSystemDir(context->GetPath()), task_logger, notification_manager, extension_service, signin_manager, token_service, request_context.get(), base::MakeUnique<DriveServiceFactory>(), nullptr /* env_override */)); sync_engine->Initialize(); return sync_engine; } void SyncEngine::AppendDependsOnFactories( std::set<BrowserContextKeyedServiceFactory*>* factories) { DCHECK(factories); factories->insert(drive::DriveNotificationManagerFactory::GetInstance()); factories->insert(SigninManagerFactory::GetInstance()); factories->insert( extensions::ExtensionsBrowserClient::Get()->GetExtensionSystemFactory()); factories->insert(ProfileOAuth2TokenServiceFactory::GetInstance()); } SyncEngine::~SyncEngine() { Reset(); net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this); if (signin_manager_) signin_manager_->RemoveObserver(this); if (notification_manager_) notification_manager_->RemoveObserver(this); } void SyncEngine::Reset() { if (drive_service_) drive_service_->RemoveObserver(this); worker_task_runner_->DeleteSoon(FROM_HERE, sync_worker_.release()); worker_task_runner_->DeleteSoon(FROM_HERE, worker_observer_.release()); worker_task_runner_->DeleteSoon(FROM_HERE, remote_change_processor_on_worker_.release()); drive_service_wrapper_.reset(); drive_service_.reset(); drive_uploader_wrapper_.reset(); drive_uploader_.reset(); remote_change_processor_wrapper_.reset(); callback_tracker_.AbortAll(); } void SyncEngine::Initialize() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); Reset(); if (!signin_manager_ || !signin_manager_->IsAuthenticated()) return; DCHECK(drive_service_factory_); std::unique_ptr<drive::DriveServiceInterface> drive_service = drive_service_factory_->CreateDriveService( token_service_, request_context_.get(), drive_task_runner_.get()); device::mojom::WakeLockProviderPtr wake_lock_provider(nullptr); DCHECK(content::ServiceManagerConnection::GetForProcess()); auto* connector = content::ServiceManagerConnection::GetForProcess()->GetConnector(); connector->BindInterface(device::mojom::kServiceName, mojo::MakeRequest(&wake_lock_provider)); std::unique_ptr<drive::DriveUploaderInterface> drive_uploader( new drive::DriveUploader(drive_service.get(), drive_task_runner_.get(), std::move(wake_lock_provider))); InitializeInternal(std::move(drive_service), std::move(drive_uploader), nullptr); } void SyncEngine::InitializeForTesting( std::unique_ptr<drive::DriveServiceInterface> drive_service, std::unique_ptr<drive::DriveUploaderInterface> drive_uploader, std::unique_ptr<SyncWorkerInterface> sync_worker) { Reset(); InitializeInternal(std::move(drive_service), std::move(drive_uploader), std::move(sync_worker)); } void SyncEngine::InitializeInternal( std::unique_ptr<drive::DriveServiceInterface> drive_service, std::unique_ptr<drive::DriveUploaderInterface> drive_uploader, std::unique_ptr<SyncWorkerInterface> sync_worker) { drive_service_ = std::move(drive_service); drive_service_wrapper_.reset(new DriveServiceWrapper(drive_service_.get())); std::string account_id; if (signin_manager_) account_id = signin_manager_->GetAuthenticatedAccountId(); drive_service_->Initialize(account_id); drive_uploader_ = std::move(drive_uploader); drive_uploader_wrapper_.reset( new DriveUploaderWrapper(drive_uploader_.get())); // DriveServiceWrapper and DriveServiceOnWorker relay communications // between DriveService and syncers in SyncWorker. std::unique_ptr<drive::DriveServiceInterface> drive_service_on_worker( new DriveServiceOnWorker(drive_service_wrapper_->AsWeakPtr(), ui_task_runner_.get(), worker_task_runner_.get())); std::unique_ptr<drive::DriveUploaderInterface> drive_uploader_on_worker( new DriveUploaderOnWorker(drive_uploader_wrapper_->AsWeakPtr(), ui_task_runner_.get(), worker_task_runner_.get())); std::unique_ptr<SyncEngineContext> sync_engine_context(new SyncEngineContext( std::move(drive_service_on_worker), std::move(drive_uploader_on_worker), task_logger_, ui_task_runner_.get(), worker_task_runner_.get())); worker_observer_.reset(new WorkerObserver(ui_task_runner_.get(), weak_ptr_factory_.GetWeakPtr())); base::WeakPtr<ExtensionServiceInterface> extension_service_weak_ptr; if (extension_service_) extension_service_weak_ptr = extension_service_->AsWeakPtr(); if (!sync_worker) { sync_worker.reset(new SyncWorker( sync_file_system_dir_, extension_service_weak_ptr, env_override_)); } sync_worker_ = std::move(sync_worker); sync_worker_->AddObserver(worker_observer_.get()); worker_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncWorkerInterface::Initialize, base::Unretained(sync_worker_.get()), base::Passed(&sync_engine_context))); if (remote_change_processor_) SetRemoteChangeProcessor(remote_change_processor_); drive_service_->AddObserver(this); service_state_ = REMOTE_SERVICE_TEMPORARY_UNAVAILABLE; OnNetworkChanged(net::NetworkChangeNotifier::GetConnectionType()); if (drive_service_->HasRefreshToken()) OnReadyToSendRequests(); else OnRefreshTokenInvalid(); } void SyncEngine::AddServiceObserver(SyncServiceObserver* observer) { service_observers_.AddObserver(observer); } void SyncEngine::AddFileStatusObserver(FileStatusObserver* observer) { file_status_observers_.AddObserver(observer); } void SyncEngine::RegisterOrigin(const GURL& origin, const SyncStatusCallback& callback) { if (!sync_worker_) { // TODO(tzik): Record |origin| and retry the registration after late // sign-in. Then, return SYNC_STATUS_OK. if (!signin_manager_ || !signin_manager_->IsAuthenticated()) callback.Run(SYNC_STATUS_AUTHENTICATION_FAILED); else callback.Run(SYNC_STATUS_ABORT); return; } SyncStatusCallback relayed_callback = RelayCallbackToCurrentThread( FROM_HERE, base::Bind(&DidRegisterOrigin, base::TimeTicks::Now(), TrackCallback(callback))); worker_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncWorkerInterface::RegisterOrigin, base::Unretained(sync_worker_.get()), origin, relayed_callback)); } void SyncEngine::EnableOrigin( const GURL& origin, const SyncStatusCallback& callback) { if (!sync_worker_) { // It's safe to return OK immediately since this is also checked in // SyncWorker initialization. callback.Run(SYNC_STATUS_OK); return; } SyncStatusCallback relayed_callback = RelayCallbackToCurrentThread( FROM_HERE, TrackCallback(callback)); worker_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncWorkerInterface::EnableOrigin, base::Unretained(sync_worker_.get()), origin, relayed_callback)); } void SyncEngine::DisableOrigin( const GURL& origin, const SyncStatusCallback& callback) { if (!sync_worker_) { // It's safe to return OK immediately since this is also checked in // SyncWorker initialization. callback.Run(SYNC_STATUS_OK); return; } SyncStatusCallback relayed_callback = RelayCallbackToCurrentThread( FROM_HERE, TrackCallback(callback)); worker_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncWorkerInterface::DisableOrigin, base::Unretained(sync_worker_.get()), origin, relayed_callback)); } void SyncEngine::UninstallOrigin( const GURL& origin, UninstallFlag flag, const SyncStatusCallback& callback) { if (!sync_worker_) { // It's safe to return OK immediately since this is also checked in // SyncWorker initialization. callback.Run(SYNC_STATUS_OK); return; } SyncStatusCallback relayed_callback = RelayCallbackToCurrentThread( FROM_HERE, TrackCallback(callback)); worker_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncWorkerInterface::UninstallOrigin, base::Unretained(sync_worker_.get()), origin, flag, relayed_callback)); } void SyncEngine::ProcessRemoteChange(const SyncFileCallback& callback) { if (GetCurrentState() == REMOTE_SERVICE_DISABLED) { callback.Run(SYNC_STATUS_SYNC_DISABLED, storage::FileSystemURL()); return; } base::Closure abort_closure = base::Bind(callback, SYNC_STATUS_ABORT, storage::FileSystemURL()); if (!sync_worker_) { abort_closure.Run(); return; } SyncFileCallback tracked_callback = callback_tracker_.Register( abort_closure, callback); SyncFileCallback relayed_callback = RelayCallbackToCurrentThread( FROM_HERE, tracked_callback); worker_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncWorkerInterface::ProcessRemoteChange, base::Unretained(sync_worker_.get()), relayed_callback)); } void SyncEngine::SetRemoteChangeProcessor(RemoteChangeProcessor* processor) { remote_change_processor_ = processor; if (!sync_worker_) return; remote_change_processor_wrapper_.reset( new RemoteChangeProcessorWrapper(processor)); remote_change_processor_on_worker_.reset(new RemoteChangeProcessorOnWorker( remote_change_processor_wrapper_->AsWeakPtr(), ui_task_runner_.get(), worker_task_runner_.get())); worker_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncWorkerInterface::SetRemoteChangeProcessor, base::Unretained(sync_worker_.get()), remote_change_processor_on_worker_.get())); } LocalChangeProcessor* SyncEngine::GetLocalChangeProcessor() { return this; } RemoteServiceState SyncEngine::GetCurrentState() const { if (!sync_enabled_) return REMOTE_SERVICE_DISABLED; if (!has_refresh_token_) return REMOTE_SERVICE_AUTHENTICATION_REQUIRED; return service_state_; } void SyncEngine::GetOriginStatusMap(const StatusMapCallback& callback) { base::Closure abort_closure = base::Bind(callback, base::Passed(std::unique_ptr<OriginStatusMap>())); if (!sync_worker_) { abort_closure.Run(); return; } StatusMapCallback tracked_callback = callback_tracker_.Register(abort_closure, callback); StatusMapCallback relayed_callback = RelayCallbackToCurrentThread(FROM_HERE, tracked_callback); worker_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncWorkerInterface::GetOriginStatusMap, base::Unretained(sync_worker_.get()), relayed_callback)); } void SyncEngine::DumpFiles(const GURL& origin, const ListCallback& callback) { base::Closure abort_closure = base::Bind(callback, base::Passed(std::unique_ptr<base::ListValue>())); if (!sync_worker_) { abort_closure.Run(); return; } ListCallback tracked_callback = callback_tracker_.Register(abort_closure, callback); PostTaskAndReplyWithResult(worker_task_runner_.get(), FROM_HERE, base::Bind(&SyncWorkerInterface::DumpFiles, base::Unretained(sync_worker_.get()), origin), tracked_callback); } void SyncEngine::DumpDatabase(const ListCallback& callback) { base::Closure abort_closure = base::Bind(callback, base::Passed(std::unique_ptr<base::ListValue>())); if (!sync_worker_) { abort_closure.Run(); return; } ListCallback tracked_callback = callback_tracker_.Register(abort_closure, callback); PostTaskAndReplyWithResult(worker_task_runner_.get(), FROM_HERE, base::Bind(&SyncWorkerInterface::DumpDatabase, base::Unretained(sync_worker_.get())), tracked_callback); } void SyncEngine::SetSyncEnabled(bool sync_enabled) { if (sync_enabled_ == sync_enabled) return; sync_enabled_ = sync_enabled; if (sync_enabled_) { if (!sync_worker_) Initialize(); // Have no login credential. if (!sync_worker_) return; worker_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncWorkerInterface::SetSyncEnabled, base::Unretained(sync_worker_.get()), sync_enabled_)); return; } if (!sync_worker_) return; // TODO(tzik): Consider removing SyncWorkerInterface::SetSyncEnabled and // let SyncEngine handle the flag. worker_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncWorkerInterface::SetSyncEnabled, base::Unretained(sync_worker_.get()), sync_enabled_)); Reset(); } void SyncEngine::PromoteDemotedChanges(const base::Closure& callback) { if (!sync_worker_) { callback.Run(); return; } base::Closure relayed_callback = RelayCallbackToCurrentThread( FROM_HERE, callback_tracker_.Register(callback, callback)); worker_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncWorkerInterface::PromoteDemotedChanges, base::Unretained(sync_worker_.get()), relayed_callback)); } void SyncEngine::ApplyLocalChange(const FileChange& local_change, const base::FilePath& local_path, const SyncFileMetadata& local_metadata, const storage::FileSystemURL& url, const SyncStatusCallback& callback) { if (GetCurrentState() == REMOTE_SERVICE_DISABLED) { callback.Run(SYNC_STATUS_SYNC_DISABLED); return; } if (!sync_worker_) { callback.Run(SYNC_STATUS_ABORT); return; } SyncStatusCallback relayed_callback = RelayCallbackToCurrentThread( FROM_HERE, TrackCallback(callback)); worker_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncWorkerInterface::ApplyLocalChange, base::Unretained(sync_worker_.get()), local_change, local_path, local_metadata, url, relayed_callback)); } void SyncEngine::OnNotificationReceived() { if (!sync_worker_) return; worker_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncWorkerInterface::ActivateService, base::Unretained(sync_worker_.get()), REMOTE_SERVICE_OK, "Got push notification for Drive")); } void SyncEngine::OnPushNotificationEnabled(bool /* enabled */) {} void SyncEngine::OnReadyToSendRequests() { has_refresh_token_ = true; if (!sync_worker_) return; worker_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncWorkerInterface::ActivateService, base::Unretained(sync_worker_.get()), REMOTE_SERVICE_OK, "Authenticated")); } void SyncEngine::OnRefreshTokenInvalid() { has_refresh_token_ = false; if (!sync_worker_) return; worker_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncWorkerInterface::DeactivateService, base::Unretained(sync_worker_.get()), "Found invalid refresh token.")); } void SyncEngine::OnNetworkChanged( net::NetworkChangeNotifier::ConnectionType type) { if (!sync_worker_) return; bool network_available_old = network_available_; network_available_ = (type != net::NetworkChangeNotifier::CONNECTION_NONE); if (!network_available_old && network_available_) { worker_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncWorkerInterface::ActivateService, base::Unretained(sync_worker_.get()), REMOTE_SERVICE_OK, "Connected")); } else if (network_available_old && !network_available_) { worker_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncWorkerInterface::DeactivateService, base::Unretained(sync_worker_.get()), "Disconnected")); } } void SyncEngine::GoogleSigninFailed(const GoogleServiceAuthError& error) { Reset(); UpdateServiceState(REMOTE_SERVICE_AUTHENTICATION_REQUIRED, "Failed to sign in."); } void SyncEngine::GoogleSigninSucceeded(const std::string& account_id, const std::string& username) { Initialize(); } void SyncEngine::GoogleSignedOut(const std::string& account_id, const std::string& username) { Reset(); UpdateServiceState(REMOTE_SERVICE_AUTHENTICATION_REQUIRED, "User signed out."); } SyncEngine::SyncEngine( const scoped_refptr<base::SingleThreadTaskRunner>& ui_task_runner, const scoped_refptr<base::SequencedTaskRunner>& worker_task_runner, const scoped_refptr<base::SequencedTaskRunner>& drive_task_runner, const base::FilePath& sync_file_system_dir, TaskLogger* task_logger, drive::DriveNotificationManager* notification_manager, ExtensionServiceInterface* extension_service, SigninManagerBase* signin_manager, OAuth2TokenService* token_service, net::URLRequestContextGetter* request_context, std::unique_ptr<DriveServiceFactory> drive_service_factory, leveldb::Env* env_override) : ui_task_runner_(ui_task_runner), worker_task_runner_(worker_task_runner), drive_task_runner_(drive_task_runner), sync_file_system_dir_(sync_file_system_dir), task_logger_(task_logger), notification_manager_(notification_manager), extension_service_(extension_service), signin_manager_(signin_manager), token_service_(token_service), request_context_(request_context), drive_service_factory_(std::move(drive_service_factory)), remote_change_processor_(nullptr), service_state_(REMOTE_SERVICE_TEMPORARY_UNAVAILABLE), has_refresh_token_(false), network_available_(false), sync_enabled_(false), env_override_(env_override), weak_ptr_factory_(this) { DCHECK(sync_file_system_dir_.IsAbsolute()); if (notification_manager_) notification_manager_->AddObserver(this); if (signin_manager_) signin_manager_->AddObserver(this); net::NetworkChangeNotifier::AddNetworkChangeObserver(this); } void SyncEngine::OnPendingFileListUpdated(int item_count) { for (auto& observer : service_observers_) observer.OnRemoteChangeQueueUpdated(item_count); } void SyncEngine::OnFileStatusChanged(const storage::FileSystemURL& url, SyncFileType file_type, SyncFileStatus file_status, SyncAction sync_action, SyncDirection direction) { for (auto& observer : file_status_observers_) { observer.OnFileStatusChanged(url, file_type, file_status, sync_action, direction); } } void SyncEngine::UpdateServiceState(RemoteServiceState state, const std::string& description) { service_state_ = state; for (auto& observer : service_observers_) observer.OnRemoteServiceStateUpdated(GetCurrentState(), description); } SyncStatusCallback SyncEngine::TrackCallback( const SyncStatusCallback& callback) { return callback_tracker_.Register( base::Bind(callback, SYNC_STATUS_ABORT), callback); } } // namespace drive_backend } // namespace sync_file_system
#include <iostream> using namespace std; int numeroSecreto = 7; void adivinarNumeroSecreto(int miNumero) { if(miNumero == numeroSecreto) { cout<<"Adivinartes!"; } else { cout<<"Intento fallido con: " << miNumero <<endl; int otroNumero; cout<<"Ingrese otro numero: "; cin>>otroNumero; adivinarNumeroSecreto(otroNumero); } } int main(int argc, char** argv) { adivinarNumeroSecreto(5); return 0; }
#include <stdio.h> #include <externalComponent122/lib1.h> #include <externalComponent24/lib1.h> #include <externalComponent25/lib1.h> #include <externalComponent26/lib1.h> #include <externalComponent27/lib1.h> #include <externalComponent28/lib1.h> #include <externalComponent29/lib1.h> #include <externalComponent30/lib1.h> #include <externalComponent31/lib1.h> #include <externalComponent32/lib1.h> #include <externalComponent33/lib1.h> #include <externalComponent34/lib1.h> #include <externalComponent35/lib1.h> #include <externalComponent36/lib1.h> #include <externalComponent37/lib1.h> #include <externalComponent38/lib1.h> #include <externalComponent39/lib1.h> #include <externalComponent40/lib1.h> #include <externalComponent41/lib1.h> #include <externalComponent42/lib1.h> #include <externalComponent43/lib1.h> #include <externalComponent44/lib1.h> #include <externalComponent45/lib1.h> #include <externalComponent46/lib1.h> #include <externalComponent47/lib1.h> #include <externalComponent48/lib1.h> #include <externalComponent49/lib1.h> #include <externalComponent50/lib1.h> #include <externalComponent51/lib1.h> #include <externalComponent9/lib1.h> #include <externalComponent10/lib1.h> #include <externalComponent11/lib1.h> #include <externalComponent12/lib1.h> #include <externalComponent13/lib1.h> #include <externalComponent14/lib1.h> #include <externalComponent15/lib1.h> #include <externalComponent16/lib1.h> #include <externalComponent17/lib1.h> #include <externalComponent18/lib1.h> #include <externalComponent19/lib1.h> #include <externalComponent20/lib1.h> #include <externalComponent21/lib1.h> #include <externalComponent170/lib1.h> #include <externalComponent221/lib1.h> int main() { printf("Hello from Main\n"); }
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/Scripting/Natives/Generated/LibTreeSharedVarReferenceName.hpp> namespace RED4ext { namespace aiscript { struct SharedVarName { static constexpr const char* NAME = "aiscriptSharedVarName"; static constexpr const char* ALIAS = NAME; uint8_t unk00[0x8 - 0x0]; // 0 LibTreeSharedVarReferenceName varName; // 08 }; RED4EXT_ASSERT_SIZE(SharedVarName, 0x10); } // namespace aiscript } // namespace RED4ext
// Copyright (c) 2014-2018, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include "include_base_utils.h" using namespace epee; #include "checkpoints.h" #include "common/dns_utils.h" #include "include_base_utils.h" #include "string_tools.h" #include "storages/portable_storage_template_helper.h" // epee json include #include "serialization/keyvalue_serialization.h" #undef MONERO_DEFAULT_LOG_CATEGORY #define MONERO_DEFAULT_LOG_CATEGORY "checkpoints" namespace cryptonote { /** * @brief struct for loading a checkpoint from json */ struct t_hashline { uint64_t height; //!< the height of the checkpoint std::string hash; //!< the hash for the checkpoint BEGIN_KV_SERIALIZE_MAP() KV_SERIALIZE(height) KV_SERIALIZE(hash) END_KV_SERIALIZE_MAP() }; /** * @brief struct for loading many checkpoints from json */ struct t_hash_json { std::vector<t_hashline> hashlines; //!< the checkpoint lines from the file BEGIN_KV_SERIALIZE_MAP() KV_SERIALIZE(hashlines) END_KV_SERIALIZE_MAP() }; //--------------------------------------------------------------------------- checkpoints::checkpoints() { } //--------------------------------------------------------------------------- bool checkpoints::add_checkpoint(uint64_t height, const std::string& hash_str) { crypto::hash h = crypto::null_hash; bool r = epee::string_tools::parse_tpod_from_hex_string(hash_str, h); CHECK_AND_ASSERT_MES(r, false, "Failed to parse checkpoint hash string into binary representation!"); // return false if adding at a height we already have AND the hash is different if (m_points.count(height)) { CHECK_AND_ASSERT_MES(h == m_points[height], false, "Checkpoint at given height already exists, and hash for new checkpoint was different!"); } m_points[height] = h; return true; } //--------------------------------------------------------------------------- bool checkpoints::is_in_checkpoint_zone(uint64_t height) const { return !m_points.empty() && (height <= (--m_points.end())->first); } //--------------------------------------------------------------------------- bool checkpoints::check_block(uint64_t height, const crypto::hash& h, bool& is_a_checkpoint) const { auto it = m_points.find(height); is_a_checkpoint = it != m_points.end(); if(!is_a_checkpoint) return true; if(it->second == h) { MINFO("CHECKPOINT PASSED FOR HEIGHT " << height << " " << h); return true; }else { MWARNING("CHECKPOINT FAILED FOR HEIGHT " << height << ". EXPECTED HASH: " << it->second << ", FETCHED HASH: " << h); return false; } } //--------------------------------------------------------------------------- bool checkpoints::check_block(uint64_t height, const crypto::hash& h) const { bool ignored; return check_block(height, h, ignored); } //--------------------------------------------------------------------------- //FIXME: is this the desired behavior? bool checkpoints::is_alternative_block_allowed(uint64_t blockchain_height, uint64_t block_height) const { if (0 == block_height) return false; auto it = m_points.upper_bound(blockchain_height); // Is blockchain_height before the first checkpoint? if (it == m_points.begin()) return true; --it; uint64_t checkpoint_height = it->first; return checkpoint_height < block_height; } //--------------------------------------------------------------------------- uint64_t checkpoints::get_max_height() const { std::map< uint64_t, crypto::hash >::const_iterator highest = std::max_element( m_points.begin(), m_points.end(), ( boost::bind(&std::map< uint64_t, crypto::hash >::value_type::first, _1) < boost::bind(&std::map< uint64_t, crypto::hash >::value_type::first, _2 ) ) ); return highest->first; } //--------------------------------------------------------------------------- const std::map<uint64_t, crypto::hash>& checkpoints::get_points() const { return m_points; } bool checkpoints::check_for_conflicts(const checkpoints& other) const { for (auto& pt : other.get_points()) { if (m_points.count(pt.first)) { CHECK_AND_ASSERT_MES(pt.second == m_points.at(pt.first), false, "Checkpoint at given height already exists, and hash for new checkpoint was different!"); } } return true; } bool checkpoints::init_default_checkpoints(network_type nettype) { if (nettype == TESTNET) { ADD_CHECKPOINT(0, "48ca7cd3c8de5b6a4d53d2861fbdaedca141553559f9be9520068053cda8430b"); ADD_CHECKPOINT(1000000, "46b690b710a07ea051bc4a6b6842ac37be691089c0f7758cfeec4d5fc0b4a258"); return true; } if (nettype == STAGENET) { ADD_CHECKPOINT(0, "76ee3cc98646292206cd3e86f74d88b4dcc1d937088645e9b0cbca84b7ce74eb"); ADD_CHECKPOINT(10000, "1f8b0ce313f8b9ba9a46108bfd285c45ad7c2176871fd41c3a690d4830ce2fd5"); return true; } ADD_CHECKPOINT(1, "771fbcd656ec1464d3a02ead5e18644030007a0fc664c0a964d30922821a8148"); ADD_CHECKPOINT(10, "c0e3b387e47042f72d8ccdca88071ff96bff1ac7cde09ae113dbb7ad3fe92381"); ADD_CHECKPOINT(100, "ac3e11ca545e57c49fca2b4e8c48c03c23be047c43e471e1394528b1f9f80b2d"); ADD_CHECKPOINT(1000, "5acfc45acffd2b2e7345caf42fa02308c5793f15ec33946e969e829f40b03876"); ADD_CHECKPOINT(10000, "c758b7c81f928be3295d45e230646de8b852ec96a821eac3fea4daf3fcac0ca2"); ADD_CHECKPOINT(22231, "7cb10e29d67e1c069e6e11b17d30b809724255fee2f6868dc14cfc6ed44dfb25"); ADD_CHECKPOINT(29556, "53c484a8ed91e4da621bb2fa88106dbde426fe90d7ef07b9c1e5127fb6f3a7f6"); ADD_CHECKPOINT(50000, "0fe8758ab06a8b9cb35b7328fd4f757af530a5d37759f9d3e421023231f7b31c"); ADD_CHECKPOINT(80000, "a62dcd7b536f22e003ebae8726e9e7276f63d594e264b6f0cd7aab27b66e75e3"); ADD_CHECKPOINT(202612, "bbd604d2ba11ba27935e006ed39c9bfdd99b76bf4a50654bc1e1e61217962698"); ADD_CHECKPOINT(202613, "e2aa337e78df1f98f462b3b1e560c6b914dec47b610698b7b7d1e3e86b6197c2"); ADD_CHECKPOINT(202614, "c29e3dc37d8da3e72e506e31a213a58771b24450144305bcba9e70fa4d6ea6fb"); ADD_CHECKPOINT(205000, "5d3d7a26e6dc7535e34f03def711daa8c263785f73ec1fadef8a45880fde8063"); ADD_CHECKPOINT(220000, "9613f455933c00e3e33ac315cc6b455ee8aa0c567163836858c2d9caff111553"); ADD_CHECKPOINT(230300, "bae7a80c46859db355556e3a9204a337ae8f24309926a1312323fdecf1920e61"); ADD_CHECKPOINT(230700, "93e631240ceac831da1aebfc5dac8f722c430463024763ebafa888796ceaeedf"); ADD_CHECKPOINT(231350, "b5add137199b820e1ea26640e5c3e121fd85faa86a1e39cf7e6cc097bdeb1131"); ADD_CHECKPOINT(232150, "955de8e6b6508af2c24f7334f97beeea651d78e9ade3ab18fec3763be3201aa8"); ADD_CHECKPOINT(249380, "654fb0a81ce3e5caf7e3264a70f447d4bd07586c08fa50f6638cc54da0a52b2d"); ADD_CHECKPOINT(460000, "75037a7aed3e765db96c75bcf908f59d690a5f3390baebb9edeafd336a1c4831"); ADD_CHECKPOINT(500000, "2428f0dbe49796be05ed81b347f53e1f7f44aed0abf641446ec2b94cae066b02"); ADD_CHECKPOINT(600000, "f5828ebf7d7d1cb61762c4dfe3ccf4ecab2e1aad23e8113668d981713b7a54c5"); ADD_CHECKPOINT(700000, "12be9b3d210b93f574d2526abb9c1ab2a881b479131fd0d4f7dac93875f503cd"); ADD_CHECKPOINT(825000, "56503f9ad766774b575be3aff73245e9d159be88132c93d1754764f28da2ff60"); ADD_CHECKPOINT(900000, "d9958d0e7dcf91a5a7b11de225927bf7efc6eb26240315ce12372be902cc1337"); ADD_CHECKPOINT(913193, "5292d5d56f6ba4de33a58d9a34d263e2cb3c6fee0aed2286fd4ac7f36d53c85f"); ADD_CHECKPOINT(1000000, "a886ef5149902d8342475fee9bb296341b891ac67c4842f47a833f23c00ed721"); ADD_CHECKPOINT(1100000, "3fd720c5c8b3072fc1ccda922dec1ef25f9ed88a1e6ad4103d0fe00b180a5903"); ADD_CHECKPOINT(1150000, "1dd16f626d18e1e988490dfd06de5920e22629c972c58b4d8daddea0038627b2"); ADD_CHECKPOINT(1200000, "fa7d13a90850882060479d100141ff84286599ae39c3277c8ea784393f882d1f"); ADD_CHECKPOINT(1300000, "31b34272343a44a9f4ac7de7a8fcf3b7d8a3124d7d6870affd510d2f37e74cd0"); ADD_CHECKPOINT(1390000, "a8f5649dd4ded60eedab475f2bec8c934681c07e3cf640e9be0617554f13ff6c"); return true; } bool checkpoints::load_checkpoints_from_json(const std::string &json_hashfile_fullpath) { boost::system::error_code errcode; if (! (boost::filesystem::exists(json_hashfile_fullpath, errcode))) { LOG_PRINT_L1("Blockchain checkpoints file not found"); return true; } LOG_PRINT_L1("Adding checkpoints from blockchain hashfile"); uint64_t prev_max_height = get_max_height(); LOG_PRINT_L1("Hard-coded max checkpoint height is " << prev_max_height); t_hash_json hashes; if (!epee::serialization::load_t_from_json_file(hashes, json_hashfile_fullpath)) { MERROR("Error loading checkpoints from " << json_hashfile_fullpath); return false; } for (std::vector<t_hashline>::const_iterator it = hashes.hashlines.begin(); it != hashes.hashlines.end(); ) { uint64_t height; height = it->height; if (height <= prev_max_height) { LOG_PRINT_L1("ignoring checkpoint height " << height); } else { std::string blockhash = it->hash; LOG_PRINT_L1("Adding checkpoint height " << height << ", hash=" << blockhash); ADD_CHECKPOINT(height, blockhash); } ++it; } return true; } bool checkpoints::load_checkpoints_from_dns(network_type nettype) { std::vector<std::string> records; // All four MoneroPulse domains have DNSSEC on and valid static const std::vector<std::string> dns_urls = { "checkpoints.moneropulse.se" , "checkpoints.moneropulse.org" , "checkpoints.moneropulse.net" , "checkpoints.moneropulse.co" }; static const std::vector<std::string> testnet_dns_urls = { "testpoints.moneropulse.se" , "testpoints.moneropulse.org" , "testpoints.moneropulse.net" , "testpoints.moneropulse.co" }; static const std::vector<std::string> stagenet_dns_urls = { "stagenetpoints.moneropulse.se" , "stagenetpoints.moneropulse.org" , "stagenetpoints.moneropulse.net" , "stagenetpoints.moneropulse.co" }; if (!tools::dns_utils::load_txt_records_from_dns(records, nettype == TESTNET ? testnet_dns_urls : nettype == STAGENET ? stagenet_dns_urls : dns_urls)) return true; // why true ? for (const auto& record : records) { auto pos = record.find(":"); if (pos != std::string::npos) { uint64_t height; crypto::hash hash; // parse the first part as uint64_t, // if this fails move on to the next record std::stringstream ss(record.substr(0, pos)); if (!(ss >> height)) { continue; } // parse the second part as crypto::hash, // if this fails move on to the next record std::string hashStr = record.substr(pos + 1); if (!epee::string_tools::parse_tpod_from_hex_string(hashStr, hash)) { continue; } ADD_CHECKPOINT(height, hashStr); } } return true; } bool checkpoints::load_new_checkpoints(const std::string &json_hashfile_fullpath, network_type nettype, bool dns) { bool result; result = load_checkpoints_from_json(json_hashfile_fullpath); if (dns) { result &= load_checkpoints_from_dns(nettype); } return result; } }
// Copyright (c) 2016-2020 The ZCash developers // Copyright (c) 2020 The GlobalSalaryCoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "sapling/sapling_util.h" #include "sync.h" #include <algorithm> #include <librustzcash.h> #include <stdexcept> #include <iostream> std::vector<unsigned char> convertIntToVectorLE(const uint64_t val_int) { std::vector<unsigned char> bytes; for(size_t i = 0; i < 8; i++) { bytes.push_back(val_int >> (i * 8)); } return bytes; } // Convert bytes into boolean vector. (MSB to LSB) std::vector<bool> convertBytesVectorToVector(const std::vector<unsigned char>& bytes) { std::vector<bool> ret; ret.resize(bytes.size() * 8); unsigned char c; for (size_t i = 0; i < bytes.size(); i++) { c = bytes.at(i); for (size_t j = 0; j < 8; j++) { ret.at((i*8)+j) = (c >> (7-j)) & 1; } } return ret; } // Convert boolean vector (big endian) to integer uint64_t convertVectorToInt(const std::vector<bool>& v) { if (v.size() > 64) { throw std::length_error ("boolean vector can't be larger than 64 bits"); } uint64_t result = 0; for (size_t i=0; i<v.size();i++) { if (v.at(i)) { result |= (uint64_t)1 << ((v.size() - 1) - i); } } return result; } uint256 random_uint256() { uint256 ret; randombytes_buf(ret.begin(), 32); return ret; }
/* ========================================================= V:Multiplayer - http://www.vmultiplayer.com -- File: Main.cpp -- Project: Client.Launcher -- Author(s): OrMisicL =============================================================*/ #include "Main.h" // That code belongs to VMultiplayer or LaunchHelper to modify the game when starting // Reformate the settings path /*char szSettingsPath[MAX_PATH]; sprintf(szSettingsPath, "%s/"CLIENT_SETTINGS_FILE, szCurrentPath); // Initialize the configuration file tinyxml2::XMLDocument xmlSettings; if (xmlSettings.LoadFile(szSettingsPath) != tinyxml2::XMLError::XML_SUCCESS) { MessageBox(NULL, "Couldn't locate \""CLIENT_SETTINGS_FILE"\".\nPlease reinstall V:Multiplayer or visit the website at " WEBSITE " for more details.", "V:Multiplayer Error", MB_OK | MB_ICONERROR); return 0; }*/ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPreviousInstance, LPSTR lpCmdLine, int iCmdShow) { // Get the current path char szCurrentPath[MAX_PATH]; if (!CSharedUtility::GetCurrentPath(szCurrentPath)) { MessageBox(NULL, "An internal error has occured.", "V:Multiplayer Error", MB_OK | MB_ICONERROR); return 0; } // Read the resgitery key char szGamePath[MAX_PATH], szLauncherPath[MAX_PATH]; if (!CSharedUtility::ReadRegisteryKey("GTAVPath", szGamePath, MAX_PATH)) { // Ask them to specify the path now int iResponse = MessageBox(NULL, "Couldn't find GTAV directory path.\nWould you like to choose the path now ?", "V:Multiplayer", MB_YESNO | MB_ICONQUESTION); if (iResponse == IDNO) { MessageBox(NULL, "Couldn't locate \""GAME_EXECUTABLE"\".", "V:Multiplayer Error", MB_OK | MB_ICONERROR); return 0; } // Taken from http://vcfaq.mvps.org/sdk/20.htm BROWSEINFO browseInfo = { 0 }; browseInfo.lpszTitle = "Pick a Directory"; ITEMIDLIST * pItemIdList = SHBrowseForFolder(&browseInfo); if (pItemIdList != NULL) { // Get the name of the selected folder if (!SHGetPathFromIDList(pItemIdList, szGamePath)) { MessageBox(NULL, "Couldn't locate \""GAME_EXECUTABLE"\".", "V:Multiplayer Error", MB_OK | MB_ICONERROR); return 0; } // Free any memory used IMalloc * pIMalloc = 0; if (SUCCEEDED(SHGetMalloc(&pIMalloc))) { pIMalloc->Free(pItemIdList); pIMalloc->Release(); } // Make the full launcher path sprintf(szLauncherPath, "%s\\"GAME_EXECUTABLE, szGamePath); // Validate the path if (!CSharedUtility::FileExists(szLauncherPath)) { MessageBox(NULL, "Couldn't locate \""GAME_EXECUTABLE"\".", "V:Multiplayer Error", MB_OK | MB_ICONERROR); return 0; } // Write the new path if (!CSharedUtility::WriteRegisteryKey("GTAVPath", szGamePath, strlen(szGamePath))) { // Try to create it now if (!CSharedUtility::CreateRegisteryKey("GTAVPath", szGamePath, strlen(szGamePath))) { MessageBox(NULL, "Couldn't update the GTAV path.\nPlease reinstall V:Multiplayer or visit the website at " WEBSITE " for more details.", "V:Multiplayer Error", MB_OK | MB_ICONERROR); return 0; } } } } else // Make the full launcher path sprintf(szLauncherPath, "%s\\"GAME_EXECUTABLE, szGamePath); // Check if the game executable file is valid if (!CSharedUtility::FileExists(szLauncherPath)) { MessageBox(NULL, "Couldn't locate \""GAME_EXECUTABLE"\".", "V:Multiplayer Error", MB_OK | MB_ICONERROR); return 0; } // Create the full LaunchHelper path char szLaunchHelperPath[MAX_PATH]; sprintf(szLaunchHelperPath, "%s\\"VMULTIPLAYER_LAUNCH_HELPER_LIBRARY, szCurrentPath); // Check if the V:Multiplayer librarys are valid if (!CSharedUtility::FileExists(szLaunchHelperPath)) { MessageBox(NULL, "Couldn't locate \""VMULTIPLAYER_LAUNCH_HELPER_LIBRARY"\".\nPlease reinstall V:Multiplayer or visit the website at " WEBSITE " for more details.", "V:Multiplayer Error", MB_OK | MB_ICONERROR); return 0; } // Initialize the STARTUPINFO structure STARTUPINFO StartupInfo; memset(&StartupInfo, 0, sizeof(StartupInfo)); // Initialize the PROCESS_INFORMATION structure PROCESS_INFORMATION ProcessInfo; memset(&ProcessInfo, 0, sizeof(ProcessInfo)); // Launch the game if (!CreateProcess(szLauncherPath, "", NULL, NULL, true, CREATE_SUSPENDED, NULL, NULL, &StartupInfo, &ProcessInfo)) { MessageBox(NULL, "Couldn't start \""GAME_EXECUTABLE"\".", "V:Multiplayer Error", MB_OK | MB_ICONERROR); ExitProcess(0); } // Try to inject the library if (!CSharedUtility::InjectLibrary(ProcessInfo.hProcess, szLaunchHelperPath)) { MessageBox(NULL, "Couldn't inject \"" VMULTIPLAYER_LAUNCH_HELPER_LIBRARY "\" into the game.", "V:Multiplayer Error", MB_OK | MB_ICONERROR); ExitProcess(0); } // Resume the launcher ResumeThread(ProcessInfo.hThread); return 1; }
/**************************************************** Date: May 19th link: https://leetcode.com/explore/challenge/card/may-leetcoding-challenge-2021/600/week-3-may-15th-may-21st/3744/ ****************************************************/ #include <iostream> #include <vector> #include <list> #include <algorithm> #include <string> #include <stack> #include <queue> #include <map> #include <unordered_map> #include <unordered_set> #include <cmath> #include <limits.h> using namespace std; /* Q: Minimum Moves to Equal Array Elements II Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. In one move, you can increment or decrement an element of the array by 1. Example 1: Input: nums = [1,2,3] Output: 2 Explanation: Only two moves are needed (remember each move increments or decrements one element): [1,2,3] => [2,2,3] => [2,2,2] Example 2: Input: nums = [1,10,2,9] Output: 16 Constraints: n == nums.length 1 <= nums.length <= 105 -109 <= nums[i] <= 109 */ class Solution1_t { public: int minMoves2(vector<int>& nums) { sort(nums.begin(), nums.end()); int median = nums[nums.size()/2]; int ans = 0; for(int n : nums) { ans += abs(median-n); } return ans; } };
/*========================================================================= Program: ParaView Module: pqSpherePropertyWidget.cxx Copyright (c) 2005,2006 Sandia Corporation, Kitware Inc. All rights reserved. ParaView is a free software; you can redistribute it and/or modify it under the terms of the ParaView license version 1.2. See License_v1.2.txt for the full ParaView license. A copy of this license can be obtained by contacting Kitware Inc. 28 Corporate Drive Clifton Park, NY 12065 USA 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ========================================================================*/ #include "pqSpherePropertyWidget.h" #include "ui_pqSpherePropertyWidget.h" #include "pqPointPickingHelper.h" #include "vtkBoundingBox.h" #include "vtkSMNewWidgetRepresentationProxy.h" #include "vtkSMPropertyGroup.h" #include "vtkSMPropertyHelper.h" //----------------------------------------------------------------------------- pqSpherePropertyWidget::pqSpherePropertyWidget( vtkSMProxy* smproxy, vtkSMPropertyGroup* smgroup, QWidget* parentObject) : Superclass("representations", "SphereWidgetRepresentation", smproxy, smgroup, parentObject) { Ui::SpherePropertyWidget ui; ui.setupUi(this); if (vtkSMProperty* center = smgroup->GetProperty("Center")) { this->addPropertyLink(ui.centerX, "text2", SIGNAL(textChangedAndEditingFinished()), center, 0); this->addPropertyLink(ui.centerY, "text2", SIGNAL(textChangedAndEditingFinished()), center, 1); this->addPropertyLink(ui.centerZ, "text2", SIGNAL(textChangedAndEditingFinished()), center, 2); ui.centerLabel->setText(center->GetXMLLabel()); ui.pickLabel->setText( ui.pickLabel->text().replace("'Center'", QString("'%1'").arg(center->GetXMLLabel()))); QString tooltip = this->getTooltip(center); ui.centerX->setToolTip(tooltip); ui.centerY->setToolTip(tooltip); ui.centerZ->setToolTip(tooltip); ui.centerLabel->setToolTip(tooltip); } else { qCritical("Missing required property for function 'Center'."); } if (vtkSMProperty* normal = smgroup->GetProperty("Normal")) { this->addPropertyLink(ui.normalX, "text2", SIGNAL(textChangedAndEditingFinished()), normal, 0); this->addPropertyLink(ui.normalY, "text2", SIGNAL(textChangedAndEditingFinished()), normal, 1); this->addPropertyLink(ui.normalZ, "text2", SIGNAL(textChangedAndEditingFinished()), normal, 2); ui.normalLabel->setText(normal->GetXMLLabel()); QString tooltip = this->getTooltip(normal); ui.normalX->setToolTip(tooltip); ui.normalY->setToolTip(tooltip); ui.normalZ->setToolTip(tooltip); ui.normalLabel->setToolTip(tooltip); } else { ui.normalLabel->hide(); ui.normalX->hide(); ui.normalY->hide(); ui.normalZ->hide(); } if (vtkSMProperty* radius = smgroup->GetProperty("Radius")) { this->addPropertyLink(ui.radius, "text2", SIGNAL(textChangedAndEditingFinished()), radius); ui.radiusLabel->setText(radius->GetXMLLabel()); QString tooltip = this->getTooltip(radius); ui.radius->setToolTip(tooltip); ui.radiusLabel->setToolTip(tooltip); } else { qCritical("Missing required property for function 'Radius'."); } if (smgroup->GetProperty("Input") == NULL) { this->connect(ui.centerOnBounds, SIGNAL(clicked()), SLOT(centerOnBounds())); } else { ui.centerOnBounds->hide(); } // link show3DWidget checkbox this->connect(ui.show3DWidget, SIGNAL(toggled(bool)), SLOT(setWidgetVisible(bool))); ui.show3DWidget->connect(this, SIGNAL(widgetVisibilityToggled(bool)), SLOT(setChecked(bool))); this->setWidgetVisible(ui.show3DWidget->isChecked()); pqPointPickingHelper* pickHelper = new pqPointPickingHelper(QKeySequence(tr("P")), false, this); pickHelper->connect(this, SIGNAL(viewChanged(pqView*)), SLOT(setView(pqView*))); pickHelper->connect(this, SIGNAL(widgetVisibilityUpdated(bool)), SLOT(setShortcutEnabled(bool))); this->connect( pickHelper, SIGNAL(pick(double, double, double)), SLOT(setCenter(double, double, double))); pqPointPickingHelper* pickHelper2 = new pqPointPickingHelper(QKeySequence(tr("Ctrl+P")), true, this); pickHelper2->connect(this, SIGNAL(viewChanged(pqView*)), SLOT(setView(pqView*))); pickHelper2->connect(this, SIGNAL(widgetVisibilityUpdated(bool)), SLOT(setShortcutEnabled(bool))); this->connect( pickHelper2, SIGNAL(pick(double, double, double)), SLOT(setCenter(double, double, double))); } //----------------------------------------------------------------------------- pqSpherePropertyWidget::~pqSpherePropertyWidget() { } //----------------------------------------------------------------------------- void pqSpherePropertyWidget::placeWidget() { // nothing to do. } //----------------------------------------------------------------------------- void pqSpherePropertyWidget::setCenter(double x, double y, double z) { vtkSMProxy* wdgProxy = this->widgetProxy(); double origin[3] = { x, y, z }; vtkSMPropertyHelper(wdgProxy, "Center").Set(origin, 3); wdgProxy->UpdateVTKObjects(); emit this->changeAvailable(); this->render(); } //----------------------------------------------------------------------------- void pqSpherePropertyWidget::centerOnBounds() { vtkBoundingBox bbox = this->dataBounds(); if (bbox.IsValid()) { vtkSMProxy* wdgProxy = this->widgetProxy(); double origin[3]; bbox.GetCenter(origin); vtkSMPropertyHelper(wdgProxy, "Center").Set(origin, 3); vtkSMPropertyHelper(wdgProxy, "Radius").Set(bbox.GetMaxLength() / 2.0); wdgProxy->UpdateVTKObjects(); emit this->changeAvailable(); this->render(); } }
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: gee@google.com (Adam Gee) #include "net/instaweb/config/rewrite_options_manager.h" #include "net/instaweb/rewriter/public/domain_lawyer.h" #include "net/instaweb/rewriter/public/rewrite_options.h" #include "net/instaweb/rewriter/public/rewrite_options_test_base.h" #include "pagespeed/kernel/base/callback.h" #include "pagespeed/kernel/base/gtest.h" #include "pagespeed/kernel/base/ref_counted_ptr.h" #include "pagespeed/kernel/base/scoped_ptr.h" #include "pagespeed/kernel/base/string.h" #include "pagespeed/kernel/base/string_util.h" #include "pagespeed/kernel/base/thread_system.h" #include "pagespeed/kernel/base/timer.h" #include "pagespeed/kernel/http/google_url.h" #include "pagespeed/kernel/http/http_names.h" #include "pagespeed/kernel/http/request_headers.h" #include "pagespeed/kernel/util/platform.h" namespace net_instaweb { namespace { template<class T> void Copy(T* to, T from) { *to = from; } class RewriteOptionsManagerTest : public RewriteOptionsTestBase<RewriteOptions> { protected: RewriteOptionsManagerTest() : timer_(Platform::CreateTimer()) { request_context_.reset( new RequestContext(thread_system()->NewMutex(), timer_.get())); } void RunGetRewriteOptionsTest() { // Initialize the pointer to some garbage; scoped_ptr<RewriteOptions> non_null(NewOptions()); ASSERT_TRUE(non_null.get()); GoogleUrl url("http://www.foo.com"); RequestHeaders request_headers; options_manager_.GetRewriteOptions( url, request_headers, NewCallback(this, &RewriteOptionsManagerTest::CheckNull)); } void CheckNull(RewriteOptions* rewrite_options) { EXPECT_TRUE(NULL == rewrite_options); } bool PrepareRequest(const RewriteOptions* rewrite_options, const RequestContextPtr& request_context, GoogleString* url, RequestHeaders* request_headers) { prepare_done_ = false; options_manager_.PrepareRequest( rewrite_options, request_context_, url, request_headers, NewCallback(this, &RewriteOptionsManagerTest::PrepareDone)); EXPECT_TRUE(prepare_done_); return prepare_success_; } RewriteOptionsManager options_manager_; RequestContextPtr request_context_; private: void PrepareDone(bool success) { prepare_success_ = success; prepare_done_ = true; } scoped_ptr<Timer> timer_; bool prepare_done_; bool prepare_success_; }; TEST_F(RewriteOptionsManagerTest, GetRewriteOptions) { RunGetRewriteOptionsTest(); } TEST_F(RewriteOptionsManagerTest, Prepare_NULLOptions) { GoogleString url; RequestHeaders request_headers; ASSERT_TRUE(PrepareRequest(NULL, request_context_, &url, &request_headers)); } TEST_F(RewriteOptionsManagerTest, Prepare_InvalidUrl) { scoped_ptr<RewriteOptions> default_options(NewOptions()); GoogleString url("invalid_url"); RequestHeaders request_headers; ASSERT_FALSE(PrepareRequest( default_options.get(), request_context_, &url, &request_headers)); } TEST_F(RewriteOptionsManagerTest, Prepare_NotProxy) { scoped_ptr<RewriteOptions> default_options(NewOptions()); GoogleString url("http://www.foo.com"); RequestHeaders request_headers; ASSERT_TRUE(PrepareRequest( default_options.get(), request_context_, &url, &request_headers)); // Domains that aren't proxied should have the host header. const GoogleString host_header = request_headers.Lookup1(HttpAttributes::kHost); EXPECT_STREQ("www.foo.com", host_header); } TEST_F(RewriteOptionsManagerTest, Prepare_Proxy) { scoped_ptr<RewriteOptions> default_options(NewOptions()); ASSERT_TRUE(default_options->WriteableDomainLawyer()->AddProxyDomainMapping( "www.foo.com", "www.origin.com", "", NULL)); GoogleString url("http://www.foo.com"); RequestHeaders request_headers; ASSERT_TRUE(PrepareRequest( default_options.get(), request_context_, &url, &request_headers)); ASSERT_TRUE(NULL == request_headers.Lookup1(HttpAttributes::kHost)); } TEST_F(RewriteOptionsManagerTest, Prepare_ProxySuffix) { scoped_ptr<RewriteOptions> default_options(NewOptions()); DomainLawyer* lawyer = default_options->WriteableDomainLawyer(); lawyer->set_proxy_suffix(".suffix"); GoogleString url("http://www.foo.com"); RequestHeaders request_headers; ASSERT_TRUE(PrepareRequest( default_options.get(), request_context_, &url, &request_headers)); EXPECT_FALSE(request_context_->IsSessionAuthorizedFetchOrigin( "http://www.foo.com")); EXPECT_STREQ("www.foo.com", request_headers.Lookup1(HttpAttributes::kHost)); request_headers.Clear(); url = "http://www.foo.com.suffix"; ASSERT_TRUE(PrepareRequest( default_options.get(), request_context_, &url, &request_headers)); EXPECT_TRUE(request_context_->IsSessionAuthorizedFetchOrigin( "http://www.foo.com")); EXPECT_STREQ("www.foo.com", request_headers.Lookup1(HttpAttributes::kHost)); } } // namespace } // namespace net_instaweb
//================================================================================== // BSD 2-Clause License // // Copyright (c) 2014-2022, NJIT, Duality Technologies Inc. and other contributors // // All rights reserved. // // Author TPOC: contact@openfhe.org // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //================================================================================== /* This is an example demo file that demonstrates timing of Parallel operations using openmp */ #define PROFILE // by defining this we activate the PROFILELOG() outputs #include <chrono> #include <fstream> #include <iostream> #include <thread> #include "openfhecore.h" #include "time.h" // function to verify our generated array void verify(float* foo, uint32_t array_size) { // verify that the data was generated correctly. bool goodflag = true; for (size_t i = 1; i < array_size; ++i) { if ((foo[i] - foo[i - 1]) != 1) { goodflag = goodflag & false; } } if (goodflag) { std::cout << "verification succeeded" << std::endl; } else { std::cout << "verification failed" << std::endl; for (size_t i = 0; i < array_size; ++i) { std::cout << foo[i] << " "; } std::cout << std::endl; } return; } int main(int argc, char* argv[]) { // note if you set dbg_flag = true then all the following OPENFHE_DEBUG() statments // print to stdout. OPENFHE_DEBUG_FLAG(true); lbcrypto::OpenFHEParallelControls.Enable(); uint32_t array_size = 1000; OPENFHE_DEBUGEXP(argc); OPENFHE_DEBUGEXP(argv[0]); if (argc < 2) { std::cout << "running " << argv[0] << " with default array size of 1000" << std::endl; } else { array_size = atoi(argv[1]); if (array_size <= 0) { std::cout << "error in argment " << argv[1] << " must be greater than zero " << std::endl; exit(-1); } } // build the array and zero it out. float* foo = new float[array_size]; for (size_t i = 0; i < array_size; i++) { foo[i] = 0; } TimeVar t_total; // define timer variable for TIC() TOC() timing functions. double timeTotal; // holds the resulting time std::cout << "Parallel computation demo using " << omp_get_num_procs() << " processors." << std::endl; std::cout << "and maximum of " << omp_get_max_threads() << " threads." << std::endl << std::endl; std::cout << "to change # threads from the default, execute at the comamnd line " << std::endl; std::cout << " For the bash shell, enter:" << std::endl << "export OMP_NUM_THREADS=<number of threads to use>" << std::endl << "For the csh or tcsh shell, enter: " << std::endl << " setenv OMP_NUM_THREADS <number of threads to use>" << std::endl; std::cout << " or use omp_set_num_threads() in your code." << std::endl << std::endl; std::cout << "HINT: use export OMP_DISPLAY_ENV=TRUE to see all your settings" << std::endl; int nthreads, tid; // determine how many threads we will have. #pragma omp parallel private(nthreads, tid) { /* Obtain thread number */ tid = omp_get_thread_num(); /* Only main thread does this */ if (tid == 0) { nthreads = omp_get_num_threads(); std::cout << "Confirmed Number of threads = " << nthreads << std::endl; } } // demonstrate debug functions (only active when dbg_flag = true) std::cout << "demonstrating OPENFHE_DEBUG()" << std::endl; OPENFHE_DEBUG("array_size = " << array_size); OPENFHE_DEBUGEXP(array_size); OPENFHE_DEBUGWHERE(array_size); #if !defined(NDEBUG) dbg_flag = false; #endif // these three no longer report any value OPENFHE_DEBUG("array_size = " << array_size); OPENFHE_DEBUGEXP(array_size); OPENFHE_DEBUGWHERE(array_size); std::cout << std::endl; // now run the parallel job TIC(t_total); // set the timer. // define a parallel loop that takes 10 milliseconds to execute then performs // a small task of filling in an array #pragma omp parallel for for (size_t i = 0; i < array_size; ++i) { float tmp = i; std::this_thread::sleep_for(std::chrono::milliseconds(10)); foo[i] = tmp; } // read the timer to get the computation time in miliseconds // look at debug.h to find other timers you can use timeTotal = TOC_MS(t_total); PROFILELOG("Total time with internal delay: " << "\t" << timeTotal << " ms"); verify(foo, array_size); std::cout << std::endl; // repeat the parallel process without the internal delay // clear out foo. for (size_t i = 0; i < array_size; i++) { foo[i] = 0; } TIC(t_total); // reset the timer. // define a parallel loop that takes 10 milliseconds to execute then performs // a small task of filling in an array #pragma omp parallel for for (size_t i = 0; i < array_size; ++i) { float tmp = i; foo[i] = tmp; } // read the timer to get the computation time in micro seconds timeTotal = TOC_US(t_total); PROFILELOG("Total time without internal delay: " << "\t" << timeTotal << " us"); verify(foo, array_size); return 0; }
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include "c_weapon__stubs.h" #include "basehlcombatweapon_shared.h" #include "c_basehlcombatweapon.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" STUB_WEAPON_CLASS( cycler_weapon, WeaponCycler, C_BaseCombatWeapon ); STUB_WEAPON_CLASS( weapon_binoculars, WeaponBinoculars, C_BaseHLCombatWeapon ); STUB_WEAPON_CLASS( weapon_bugbait, WeaponBugBait, C_BaseHLCombatWeapon ); STUB_WEAPON_CLASS( weapon_flaregun, Flaregun, C_BaseHLCombatWeapon ); STUB_WEAPON_CLASS( weapon_annabelle, WeaponAnnabelle, C_BaseHLCombatWeapon ); STUB_WEAPON_CLASS( weapon_gauss, WeaponGaussGun, C_BaseHLCombatWeapon ); STUB_WEAPON_CLASS( weapon_cubemap, WeaponCubemap, C_BaseCombatWeapon ); STUB_WEAPON_CLASS( weapon_alyxgun, WeaponAlyxGun, C_HLSelectFireMachineGun ); STUB_WEAPON_CLASS( weapon_citizenpackage, WeaponCitizenPackage, C_BaseHLCombatWeapon ); STUB_WEAPON_CLASS( weapon_citizensuitcase, WeaponCitizenSuitcase, C_WeaponCitizenPackage ); #ifndef HL2MP STUB_WEAPON_CLASS( weapon_ar2, WeaponAR2, C_HLMachineGun ); STUB_WEAPON_CLASS( weapon_frag, WeaponFrag, C_BaseHLCombatWeapon ); STUB_WEAPON_CLASS( weapon_rpg, WeaponRPG, C_BaseHLCombatWeapon ); STUB_WEAPON_CLASS( weapon_pistol, WeaponPistol, C_BaseHLCombatWeapon ); STUB_WEAPON_CLASS( weapon_shotgun, WeaponShotgun, C_BaseHLCombatWeapon ); STUB_WEAPON_CLASS( weapon_smg1, WeaponSMG1, C_HLSelectFireMachineGun ); STUB_WEAPON_CLASS( weapon_357, Weapon357, C_BaseHLCombatWeapon ); STUB_WEAPON_CLASS( weapon_crossbow, WeaponCrossbow, C_BaseHLCombatWeapon ); STUB_WEAPON_CLASS( weapon_slam, Weapon_SLAM, C_BaseHLCombatWeapon ); STUB_WEAPON_CLASS( weapon_crowbar, WeaponCrowbar, C_BaseHLBludgeonWeapon ); STUB_WEAPON_CLASS( weapon_psyarm, WeaponPsyArm, C_BaseHLCombatWeapon ); STUB_WEAPON_CLASS(weapon_silenced, WeaponSilenced, C_BaseHLCombatWeapon); STUB_WEAPON_CLASS(weapon_decoy, WeaponDecoy, C_BaseHLCombatWeapon); STUB_WEAPON_CLASS(weapon_flare, WeaponFlare, C_BaseHLCombatWeapon); #ifdef HL2_EPISODIC STUB_WEAPON_CLASS( weapon_hopwire, WeaponHopwire, C_BaseHLCombatWeapon ); //STUB_WEAPON_CLASS( weapon_proto1, WeaponProto1, C_BaseHLCombatWeapon ); #endif #ifdef HL2_LOSTCOAST STUB_WEAPON_CLASS( weapon_oldmanharpoon, WeaponOldManHarpoon, C_WeaponCitizenPackage ); #endif #endif
/* * 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/core/client/AWSError.h> #include <aws/core/utils/HashingUtils.h> #include <aws/globalaccelerator/GlobalAcceleratorErrors.h> using namespace Aws::Client; using namespace Aws::GlobalAccelerator; using namespace Aws::Utils; namespace Aws { namespace GlobalAccelerator { namespace GlobalAcceleratorErrorMapper { static const int LIMIT_EXCEEDED_HASH = HashingUtils::HashString("LimitExceededException"); static const int ACCELERATOR_NOT_FOUND_HASH = HashingUtils::HashString("AcceleratorNotFoundException"); static const int INCORRECT_CIDR_STATE_HASH = HashingUtils::HashString("IncorrectCidrStateException"); static const int INVALID_NEXT_TOKEN_HASH = HashingUtils::HashString("InvalidNextTokenException"); static const int BYOIP_CIDR_NOT_FOUND_HASH = HashingUtils::HashString("ByoipCidrNotFoundException"); static const int LISTENER_NOT_FOUND_HASH = HashingUtils::HashString("ListenerNotFoundException"); static const int ASSOCIATED_LISTENER_FOUND_HASH = HashingUtils::HashString("AssociatedListenerFoundException"); static const int INVALID_PORT_RANGE_HASH = HashingUtils::HashString("InvalidPortRangeException"); static const int ENDPOINT_GROUP_NOT_FOUND_HASH = HashingUtils::HashString("EndpointGroupNotFoundException"); static const int INTERNAL_SERVICE_ERROR_HASH = HashingUtils::HashString("InternalServiceErrorException"); static const int ENDPOINT_GROUP_ALREADY_EXISTS_HASH = HashingUtils::HashString("EndpointGroupAlreadyExistsException"); static const int INVALID_ARGUMENT_HASH = HashingUtils::HashString("InvalidArgumentException"); static const int ASSOCIATED_ENDPOINT_GROUP_FOUND_HASH = HashingUtils::HashString("AssociatedEndpointGroupFoundException"); static const int ACCELERATOR_NOT_DISABLED_HASH = HashingUtils::HashString("AcceleratorNotDisabledException"); AWSError<CoreErrors> GetErrorForName(const char* errorName) { int hashCode = HashingUtils::HashString(errorName); if (hashCode == LIMIT_EXCEEDED_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(GlobalAcceleratorErrors::LIMIT_EXCEEDED), false); } else if (hashCode == ACCELERATOR_NOT_FOUND_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(GlobalAcceleratorErrors::ACCELERATOR_NOT_FOUND), false); } else if (hashCode == INCORRECT_CIDR_STATE_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(GlobalAcceleratorErrors::INCORRECT_CIDR_STATE), false); } else if (hashCode == INVALID_NEXT_TOKEN_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(GlobalAcceleratorErrors::INVALID_NEXT_TOKEN), false); } else if (hashCode == BYOIP_CIDR_NOT_FOUND_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(GlobalAcceleratorErrors::BYOIP_CIDR_NOT_FOUND), false); } else if (hashCode == LISTENER_NOT_FOUND_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(GlobalAcceleratorErrors::LISTENER_NOT_FOUND), false); } else if (hashCode == ASSOCIATED_LISTENER_FOUND_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(GlobalAcceleratorErrors::ASSOCIATED_LISTENER_FOUND), false); } else if (hashCode == INVALID_PORT_RANGE_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(GlobalAcceleratorErrors::INVALID_PORT_RANGE), false); } else if (hashCode == ENDPOINT_GROUP_NOT_FOUND_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(GlobalAcceleratorErrors::ENDPOINT_GROUP_NOT_FOUND), false); } else if (hashCode == INTERNAL_SERVICE_ERROR_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(GlobalAcceleratorErrors::INTERNAL_SERVICE_ERROR), false); } else if (hashCode == ENDPOINT_GROUP_ALREADY_EXISTS_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(GlobalAcceleratorErrors::ENDPOINT_GROUP_ALREADY_EXISTS), false); } else if (hashCode == INVALID_ARGUMENT_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(GlobalAcceleratorErrors::INVALID_ARGUMENT), false); } else if (hashCode == ASSOCIATED_ENDPOINT_GROUP_FOUND_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(GlobalAcceleratorErrors::ASSOCIATED_ENDPOINT_GROUP_FOUND), false); } else if (hashCode == ACCELERATOR_NOT_DISABLED_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(GlobalAcceleratorErrors::ACCELERATOR_NOT_DISABLED), false); } return AWSError<CoreErrors>(CoreErrors::UNKNOWN, false); } } // namespace GlobalAcceleratorErrorMapper } // namespace GlobalAccelerator } // namespace Aws
/* * Copyright 2018 Google, Inc. * * 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 copyright holders 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. * * Authors: Gabe Black */ #ifndef __SYSTEMC_EXT_CORE_SC_EVENT_HH__ #define __SYSTEMC_EXT_CORE_SC_EVENT_HH__ #include <cassert> #include <set> #include <vector> #include "sc_port.hh" #include "sc_time.hh" namespace sc_gem5 { class Event; class DynamicSensitivityEventAndList; class DynamicSensitivityEventOrList; } namespace sc_core { class sc_event; class sc_event_and_expr; class sc_event_or_expr; class sc_interface; class sc_object; class sc_port_base; class sc_event_finder { protected: virtual ~sc_event_finder() {} public: // Should be "implementation defined" but used in the tests. virtual const sc_event &find_event(sc_interface *if_p=NULL) const = 0; virtual const sc_port_base *port() const = 0; }; template <class IF> class sc_event_finder_t : public sc_event_finder { public: sc_event_finder_t(const sc_port_base &p, const sc_event & (IF::*_method)() const) : _method(_method) { _port = dynamic_cast<const sc_port_b<IF> *>(&p); assert(_port); } virtual ~sc_event_finder_t() {} const sc_port_base *port() const { return _port; } const sc_event & find_event(sc_interface *if_p=NULL) const override { const IF *iface = if_p ? dynamic_cast<const IF *>(if_p) : dynamic_cast<const IF *>(_port->get_interface()); return (const_cast<IF *>(iface)->*_method)(); } private: const sc_port_b<IF> *_port; const sc_event &(IF::*_method)() const; }; class sc_event_and_list { public: sc_event_and_list(); sc_event_and_list(const sc_event_and_list &); sc_event_and_list(const sc_event &); sc_event_and_list &operator = (const sc_event_and_list &); ~sc_event_and_list(); int size() const; void swap(sc_event_and_list &); sc_event_and_list &operator &= (const sc_event &); sc_event_and_list &operator &= (const sc_event_and_list &); sc_event_and_expr operator & (const sc_event &) const; sc_event_and_expr operator & (const sc_event_and_list &); private: friend class sc_event_and_expr; friend class sc_gem5::DynamicSensitivityEventAndList; explicit sc_event_and_list(bool auto_delete); void insert(sc_event const &e); void insert(sc_event_and_list const &eal); std::set<const sc_event *> events; bool autoDelete; mutable unsigned busy; }; class sc_event_or_list { public: sc_event_or_list(); sc_event_or_list(const sc_event_or_list &); sc_event_or_list(const sc_event &); sc_event_or_list& operator = (const sc_event_or_list &); ~sc_event_or_list(); int size() const; void swap(sc_event_or_list &); sc_event_or_list &operator |= (const sc_event &); sc_event_or_list &operator |= (const sc_event_or_list &); sc_event_or_expr operator | (const sc_event &) const; sc_event_or_expr operator | (const sc_event_or_list &) const; private: friend class sc_event_or_expr; friend class sc_gem5::DynamicSensitivityEventOrList; explicit sc_event_or_list(bool auto_delete); void insert(sc_event const &e); void insert(sc_event_or_list const &eol); std::set<const sc_event *> events; bool autoDelete; mutable unsigned busy; }; class sc_event_and_expr { public: sc_event_and_expr(sc_event_and_expr const &e); operator const sc_event_and_list &() const; void insert(sc_event const &e) const; void insert(sc_event_and_list const &eal) const; ~sc_event_and_expr(); private: friend class sc_event_and_list; friend class sc_event; sc_event_and_expr(); mutable sc_event_and_list *list; }; sc_event_and_expr operator & (sc_event_and_expr, sc_event const &); sc_event_and_expr operator & (sc_event_and_expr, sc_event_and_list const &); class sc_event_or_expr { public: sc_event_or_expr(sc_event_or_expr const &e); operator const sc_event_or_list &() const; void insert(sc_event const &e) const; void insert(sc_event_or_list const &eol) const; ~sc_event_or_expr(); private: friend class sc_event_or_list; friend class sc_event; sc_event_or_expr(); mutable sc_event_or_list *list; }; sc_event_or_expr operator | (sc_event_or_expr, sc_event const &); sc_event_or_expr operator | (sc_event_or_expr, sc_event_or_list const &); class sc_event { public: sc_event(); explicit sc_event(const char *); ~sc_event(); const char *name() const; const char *basename() const; bool in_hierarchy() const; sc_object *get_parent_object() const; void notify(); void notify(const sc_time &); void notify(double, sc_time_unit); void cancel(); // Nonstandard // Returns whether this event is currently triggered. bool triggered() const; // Deprecated void notify_delayed(); void notify_delayed(const sc_time &); sc_event_and_expr operator & (const sc_event &) const; sc_event_and_expr operator & (const sc_event_and_list &) const; sc_event_or_expr operator | (const sc_event &) const; sc_event_or_expr operator | (const sc_event_or_list &) const; private: // Disabled sc_event(const sc_event &) {} sc_event &operator = (const sc_event &) { return *this; } friend class ::sc_gem5::Event; ::sc_gem5::Event *_gem5_event; }; const std::vector<sc_event *> &sc_get_top_level_events(); sc_event *sc_find_event(const char *); } // namespace sc_core #endif //__SYSTEMC_EXT_CORE_SC_INTERFACE_HH__
// Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "common_dyn_batch_regression.hpp" std::vector<CommonDynBatchFuncTestParams> supportedDynBatchValues = { { "GPU", 4, 3 }, { "GPU", 4, 2 }, { "GPU", 4, 1 }, { "GPU", 8, 5 }, { "GPU", 8, 4 }, { "GPU", 8, 3 }, }; INSTANTIATE_TEST_CASE_P(FunctionalTest_smoke, TestNoRegressionDynBatchFP32, ValuesIn(supportedDynBatchValues), getTestCaseName);
// Copyright 2018, OpenCensus Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 "opencensus/exporters/stats/stdout/stdout_exporter.h" #include <cstdint> #include <iostream> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "absl/time/time.h" #include "opencensus/stats/stats.h" namespace opencensus { namespace exporters { namespace stats { namespace { // Functions to format data for different aggregation types. std::string DataToString(double data) { return absl::StrCat(": ", data, "\n"); } std::string DataToString(int64_t data) { return absl::StrCat(": ", data, "\n"); } std::string DataToString(const opencensus::stats::Distribution& data) { std::string output = "\n"; std::vector<std::string> lines = absl::StrSplit(data.DebugString(), '\n'); // Add indent. for (const auto& line : lines) { absl::StrAppend(&output, " ", line, "\n"); } return output; } class Handler : public opencensus::stats::StatsExporter::Handler { public: explicit Handler(std::ostream* stream) : stream_(stream) {} void ExportViewData( const std::vector<std::pair<opencensus::stats::ViewDescriptor, opencensus::stats::ViewData>>& data) override; private: // Implements ExportViewData for supported data types. template <typename DataValueT> void ExportViewDataImpl( const opencensus::stats::ViewDescriptor& descriptor, absl::Time start_time, absl::Time end_time, const opencensus::stats::ViewData::DataMap<DataValueT>& data); std::ostream* stream_; }; void Handler::ExportViewData( const std::vector<std::pair<opencensus::stats::ViewDescriptor, opencensus::stats::ViewData>>& data) { for (const auto& datum : data) { const auto& view_data = datum.second; switch (view_data.type()) { case opencensus::stats::ViewData::Type::kDouble: ExportViewDataImpl(datum.first, view_data.start_time(), view_data.end_time(), view_data.double_data()); break; case opencensus::stats::ViewData::Type::kInt64: ExportViewDataImpl(datum.first, view_data.start_time(), view_data.end_time(), view_data.int_data()); break; case opencensus::stats::ViewData::Type::kDistribution: ExportViewDataImpl(datum.first, view_data.start_time(), view_data.end_time(), view_data.distribution_data()); break; } } } template <typename DataValueT> void Handler::ExportViewDataImpl( const opencensus::stats::ViewDescriptor& descriptor, absl::Time start_time, absl::Time end_time, const opencensus::stats::ViewData::DataMap<DataValueT>& data) { if (data.empty()) { *stream_ << absl::StrCat("No data for view \"", descriptor.name(), "\" from ", absl::FormatTime(start_time), ".\n\n"); return; } // Build a string so we can write it in one shot to minimize crosstalk if // multiple threads write to stream_ simultaneously. std::string output = absl::StrCat("Data for view \"", descriptor.name(), "\" from ", absl::FormatTime(start_time), " to ", absl::FormatTime(end_time), ":\n"); for (const auto& row : data) { absl::StrAppend(&output, " "); for (int i = 0; i < descriptor.columns().size(); ++i) { absl::StrAppend(&output, descriptor.columns()[i].name(), "=", row.first[i], " "); } absl::StrAppend(&output, DataToString(row.second)); } absl::StrAppend(&output, "\n"); *stream_ << output; } } // namespace // static void StdoutExporter::Register(std::ostream* stream) { opencensus::stats::StatsExporter::RegisterPushHandler( absl::make_unique<Handler>(stream)); } } // namespace stats } // namespace exporters } // namespace opencensus
#include "rewriter/cleanup.h" #include "ast/Helpers.h" #include "ast/ast.h" #include "ast/treemap/treemap.h" #include "core/core.h" using namespace std; namespace sorbet::rewriter { // This pass gets rid of some unnecessary nodes that are likely to have gotten created in the course of the rewriter // pass, specifically by removing EmptyTree nodes in places where they can be safely removed (i.e. as part of longer // sequences of expressions where they are not a return value) struct CleanupWalk { unique_ptr<ast::Expression> postTransformInsSeq(core::Context ctx, unique_ptr<ast::InsSeq> insSeq) { ast::InsSeq::STATS_store newStore; for (auto &m : insSeq->stats) { if (!ast::isa_tree<ast::EmptyTree>(m.get())) { newStore.emplace_back(move(m)); } } if (newStore.empty()) { return move(insSeq->expr); } insSeq->stats = std::move(newStore); return insSeq; } unique_ptr<ast::Expression> postTransformClassDef(core::Context ctx, unique_ptr<ast::ClassDef> classDef) { ast::ClassDef::RHS_store newStore; for (auto &m : classDef->rhs) { if (!ast::isa_tree<ast::EmptyTree>(m.get())) { newStore.emplace_back(move(m)); } } classDef->rhs = std::move(newStore); return classDef; } }; unique_ptr<ast::Expression> Cleanup::run(core::Context ctx, unique_ptr<ast::Expression> tree) { CleanupWalk cleanup; return ast::TreeMap::apply(ctx, cleanup, std::move(tree)); } } // namespace sorbet::rewriter
// // Copyright (c) 2008-2019 the Urho3D project. // // 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 "../../Precompiled.h" #include "../../Graphics/ConstantBuffer.h" #include "../../Graphics/Graphics.h" #include "../../Graphics/GraphicsImpl.h" #include "../../Graphics/ShaderProgram.h" #include "../../Graphics/ShaderVariation.h" #include "../../IO/Log.h" #include "../../DebugNew.h" namespace Urho3D { static const char* shaderParameterGroups[] = { "frame", "camera", "zone", "light", "material", "object", "custom" }; static unsigned NumberPostfix(const String& str) { for (unsigned i = 0; i < str.Length(); ++i) { if (IsDigit(str[i])) return ToUInt(str.CString() + i); } return M_MAX_UNSIGNED; } unsigned ShaderProgram::globalFrameNumber = 0; const void* ShaderProgram::globalParameterSources[MAX_SHADER_PARAMETER_GROUPS]; ShaderProgram::ShaderProgram(Graphics* graphics, ShaderVariation* vertexShader, ShaderVariation* pixelShader) : GPUObject(graphics), vertexShader_(vertexShader), pixelShader_(pixelShader) { for (auto& parameterSource : parameterSources_) parameterSource = (const void*)M_MAX_UNSIGNED; } ShaderProgram::~ShaderProgram() { Release(); } void ShaderProgram::OnDeviceLost() { GPUObject::OnDeviceLost(); if (graphics_ && graphics_->GetShaderProgram() == this) graphics_->SetShaders(nullptr, nullptr); linkerOutput_.Clear(); } void ShaderProgram::Release() { if (object_.name_) { if (!graphics_) return; if (!graphics_->IsDeviceLost()) { if (graphics_->GetShaderProgram() == this) graphics_->SetShaders(nullptr, nullptr); glDeleteProgram(object_.name_); } object_.name_ = 0; linkerOutput_.Clear(); shaderParameters_.Clear(); vertexAttributes_.Clear(); usedVertexAttributes_ = 0; for (bool& useTextureUnit : useTextureUnits_) useTextureUnit = false; for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i) constantBuffers_[i].Reset(); } } bool ShaderProgram::Link() { Release(); if (!vertexShader_ || !pixelShader_ || !vertexShader_->GetGPUObjectName() || !pixelShader_->GetGPUObjectName()) return false; object_.name_ = glCreateProgram(); if (!object_.name_) { linkerOutput_ = "Could not create shader program"; return false; } glAttachShader(object_.name_, vertexShader_->GetGPUObjectName()); glAttachShader(object_.name_, pixelShader_->GetGPUObjectName()); glLinkProgram(object_.name_); int linked, length; glGetProgramiv(object_.name_, GL_LINK_STATUS, &linked); if (!linked) { glGetProgramiv(object_.name_, GL_INFO_LOG_LENGTH, &length); linkerOutput_.Resize((unsigned)length); int outLength; glGetProgramInfoLog(object_.name_, length, &outLength, &linkerOutput_[0]); glDeleteProgram(object_.name_); object_.name_ = 0; } else linkerOutput_.Clear(); if (!object_.name_) return false; const int MAX_NAME_LENGTH = 256; char nameBuffer[MAX_NAME_LENGTH]; int attributeCount, uniformCount, elementCount, nameLength; GLenum type; glUseProgram(object_.name_); // Check for vertex attributes glGetProgramiv(object_.name_, GL_ACTIVE_ATTRIBUTES, &attributeCount); for (int i = 0; i < attributeCount; ++i) { glGetActiveAttrib(object_.name_, i, (GLsizei)MAX_NAME_LENGTH, &nameLength, &elementCount, &type, nameBuffer); String name = String(nameBuffer, nameLength); VertexElementSemantic semantic = MAX_VERTEX_ELEMENT_SEMANTICS; unsigned char semanticIndex = 0; // Go in reverse order so that "binormal" is detected before "normal" for (unsigned j = MAX_VERTEX_ELEMENT_SEMANTICS - 1; j < MAX_VERTEX_ELEMENT_SEMANTICS; --j) { if (name.Contains(ShaderVariation::elementSemanticNames[j], false)) { semantic = (VertexElementSemantic)j; unsigned index = NumberPostfix(name); if (index != M_MAX_UNSIGNED) semanticIndex = (unsigned char)index; break; } } if (semantic == MAX_VERTEX_ELEMENT_SEMANTICS) { URHO3D_LOGWARNING("Found vertex attribute " + name + " with no known semantic in shader program " + vertexShader_->GetFullName() + " " + pixelShader_->GetFullName()); continue; } int location = glGetAttribLocation(object_.name_, name.CString()); vertexAttributes_[MakePair((unsigned char)semantic, semanticIndex)] = location; usedVertexAttributes_ |= (1u << location); } // Check for constant buffers #ifndef GL_ES_VERSION_2_0 HashMap<unsigned, unsigned> blockToBinding; if (Graphics::GetGL3Support()) { int numUniformBlocks = 0; glGetProgramiv(object_.name_, GL_ACTIVE_UNIFORM_BLOCKS, &numUniformBlocks); for (int i = 0; i < numUniformBlocks; ++i) { glGetActiveUniformBlockName(object_.name_, (GLuint)i, MAX_NAME_LENGTH, &nameLength, nameBuffer); String name(nameBuffer, (unsigned)nameLength); unsigned blockIndex = glGetUniformBlockIndex(object_.name_, name.CString()); unsigned group = M_MAX_UNSIGNED; // Try to recognize the use of the buffer from its name for (unsigned j = 0; j < MAX_SHADER_PARAMETER_GROUPS; ++j) { if (name.Contains(shaderParameterGroups[j], false)) { group = j; break; } } // If name is not recognized, search for a digit in the name and use that as the group index if (group == M_MAX_UNSIGNED) group = NumberPostfix(name); if (group >= MAX_SHADER_PARAMETER_GROUPS) { URHO3D_LOGWARNING("Skipping unrecognized uniform block " + name + " in shader program " + vertexShader_->GetFullName() + " " + pixelShader_->GetFullName()); continue; } // Find total constant buffer data size int dataSize; glGetActiveUniformBlockiv(object_.name_, blockIndex, GL_UNIFORM_BLOCK_DATA_SIZE, &dataSize); if (!dataSize) continue; unsigned bindingIndex = group; // Vertex shader constant buffer bindings occupy slots starting from zero to maximum supported, pixel shader bindings // from that point onward ShaderType shaderType = VS; if (name.Contains("PS", false)) { bindingIndex += MAX_SHADER_PARAMETER_GROUPS; shaderType = PS; } glUniformBlockBinding(object_.name_, blockIndex, bindingIndex); blockToBinding[blockIndex] = bindingIndex; constantBuffers_[bindingIndex] = graphics_->GetOrCreateConstantBuffer(shaderType, bindingIndex, (unsigned)dataSize); } } #endif // Check for shader parameters and texture units glGetProgramiv(object_.name_, GL_ACTIVE_UNIFORMS, &uniformCount); for (int i = 0; i < uniformCount; ++i) { glGetActiveUniform(object_.name_, (GLuint)i, MAX_NAME_LENGTH, nullptr, &elementCount, &type, nameBuffer); int location = glGetUniformLocation(object_.name_, nameBuffer); // Check for array index included in the name and strip it String name(nameBuffer); unsigned index = name.Find('['); if (index != String::NPOS) { // If not the first index, skip if (name.Find("[0]", index) == String::NPOS) continue; name = name.Substring(0, index); } if (name[0] == 'c') { // Store constant uniform String paramName = name.Substring(1); ShaderParameter parameter{paramName, type, location}; bool store = location >= 0; #ifndef GL_ES_VERSION_2_0 // If running OpenGL 3, the uniform may be inside a constant buffer if (parameter.location_ < 0 && Graphics::GetGL3Support()) { int blockIndex, blockOffset; glGetActiveUniformsiv(object_.name_, 1, (const GLuint*)&i, GL_UNIFORM_BLOCK_INDEX, &blockIndex); glGetActiveUniformsiv(object_.name_, 1, (const GLuint*)&i, GL_UNIFORM_OFFSET, &blockOffset); if (blockIndex >= 0) { parameter.offset_ = blockOffset; parameter.bufferPtr_ = constantBuffers_[blockToBinding[blockIndex]]; store = true; } } #endif if (store) shaderParameters_[StringHash(paramName)] = parameter; } else if (location >= 0 && name[0] == 's') { // Set the samplers here so that they do not have to be set later unsigned unit = graphics_->GetTextureUnit(name.Substring(1)); if (unit >= MAX_TEXTURE_UNITS) unit = NumberPostfix(name); if (unit < MAX_TEXTURE_UNITS) { useTextureUnits_[unit] = true; glUniform1iv(location, 1, reinterpret_cast<int*>(&unit)); } } } // Rehash the parameter & vertex attributes maps to ensure minimal load factor vertexAttributes_.Rehash(NextPowerOfTwo(vertexAttributes_.Size())); shaderParameters_.Rehash(NextPowerOfTwo(shaderParameters_.Size())); return true; } ShaderVariation* ShaderProgram::GetVertexShader() const { return vertexShader_; } ShaderVariation* ShaderProgram::GetPixelShader() const { return pixelShader_; } bool ShaderProgram::HasParameter(StringHash param) const { return shaderParameters_.Find(param) != shaderParameters_.End(); } const ShaderParameter* ShaderProgram::GetParameter(StringHash param) const { HashMap<StringHash, ShaderParameter>::ConstIterator i = shaderParameters_.Find(param); if (i != shaderParameters_.End()) return &i->second_; else return nullptr; } bool ShaderProgram::NeedParameterUpdate(ShaderParameterGroup group, const void* source) { // If global framenumber has changed, invalidate all per-program parameter sources now if (globalFrameNumber != frameNumber_) { for (auto& parameterSource : parameterSources_) parameterSource = (const void*)M_MAX_UNSIGNED; frameNumber_ = globalFrameNumber; } // The shader program may use a mixture of constant buffers and individual uniforms even in the same group #ifndef GL_ES_VERSION_2_0 bool useBuffer = constantBuffers_[group].Get() || constantBuffers_[group + MAX_SHADER_PARAMETER_GROUPS].Get(); bool useIndividual = !constantBuffers_[group].Get() || !constantBuffers_[group + MAX_SHADER_PARAMETER_GROUPS].Get(); bool needUpdate = false; if (useBuffer && globalParameterSources[group] != source) { globalParameterSources[group] = source; needUpdate = true; } if (useIndividual && parameterSources_[group] != source) { parameterSources_[group] = source; needUpdate = true; } return needUpdate; #else if (parameterSources_[group] != source) { parameterSources_[group] = source; return true; } else return false; #endif } void ShaderProgram::ClearParameterSource(ShaderParameterGroup group) { // The shader program may use a mixture of constant buffers and individual uniforms even in the same group #ifndef GL_ES_VERSION_2_0 bool useBuffer = constantBuffers_[group].Get() || constantBuffers_[group + MAX_SHADER_PARAMETER_GROUPS].Get(); bool useIndividual = !constantBuffers_[group].Get() || !constantBuffers_[group + MAX_SHADER_PARAMETER_GROUPS].Get(); if (useBuffer) globalParameterSources[group] = (const void*)M_MAX_UNSIGNED; if (useIndividual) parameterSources_[group] = (const void*)M_MAX_UNSIGNED; #else parameterSources_[group] = (const void*)M_MAX_UNSIGNED; #endif } void ShaderProgram::ClearParameterSources() { ++globalFrameNumber; if (!globalFrameNumber) ++globalFrameNumber; #ifndef GL_ES_VERSION_2_0 for (auto& globalParameterSource : globalParameterSources) globalParameterSource = (const void*)M_MAX_UNSIGNED; #endif } void ShaderProgram::ClearGlobalParameterSource(ShaderParameterGroup group) { globalParameterSources[group] = (const void*)M_MAX_UNSIGNED; } }
#include "indextext.h" #include <memory> #include "core/ft/filters/kblayout.h" #include "core/ft/filters/synonyms.h" #include "core/ft/filters/translit.h" #include "core/rdxcontext.h" #include "estl/smart_lock.h" #include "tools/errors.h" #include "tools/logger.h" namespace reindexer { // Available stemmers for languages const char *stemLangs[] = {"en", "ru", "nl", "fin", "de", "da", "fr", "it", "hu", "no", "pt", "ro", "es", "sv", "tr", nullptr}; template <typename T> IndexText<T>::IndexText(const IndexText<T> &other) : IndexUnordered<T>(other), cache_ft_(new FtIdSetCache) { initSearchers(); } // Generic implemetation for string index template <typename T> void IndexText<T>::initSearchers() { holder_.stemmers_.clear(); holder_.translit_.reset(new Translit); holder_.kbLayout_.reset(new KbLayout); holder_.synonyms_.reset(new Synonyms); for (const char **lang = stemLangs; *lang; ++lang) { holder_.stemmers_.emplace(*lang, *lang); } size_t jsonPathIdx = 0; if (this->payloadType_) { for (unsigned i = 0; i < this->fields_.size(); i++) { auto fieldIdx = this->fields_[i]; if (fieldIdx == IndexValueType::SetByJsonPath) { assert(jsonPathIdx < this->fields_.getJsonPathsLength()); ftFields_.insert({this->fields_.getJsonPath(jsonPathIdx++), i}); } else { ftFields_.insert({this->payloadType_->Field(fieldIdx).Name(), i}); } } } } template <typename T> void IndexText<T>::Commit() { // Do nothing // Rebuild will be done on first select } template <typename T> void IndexText<T>::SetOpts(const IndexOpts &opts) { string oldCfg = this->opts_.config; this->opts_ = opts; if (oldCfg != opts.config) { try { cfg_->parse(this->opts_.config, ftFields_); } catch (...) { this->opts_.config = oldCfg; cfg_->parse(this->opts_.config, ftFields_); throw; } } } // Generic implemetation for string index template <typename T> SelectKeyResults IndexText<T>::SelectKey(const VariantArray &keys, CondType condition, SortType /*stype*/, Index::SelectOpts /*opts*/, BaseFunctionCtx::Ptr ctx, const RdxContext &rdxCtx) { const auto indexWard(rdxCtx.BeforeIndexWork()); if (keys.size() < 1 || (condition != CondEq && condition != CondSet)) { throw Error(errParams, "Full text index (%s) support only EQ or SET condition with 1 or 2 parameter", Index::Name()); } FtCtx::Ptr ftctx = reindexer::reinterpret_pointer_cast<FtCtx>(ctx); if (!ftctx) { throw Error(errParams, "Full text index (%s) may not be used without context", Index::Name()); } ftctx->PrepareAreas(ftFields_, this->name_); bool need_put = false; IdSetCacheKey ckey{keys, condition, 0}; auto cache_ft = cache_ft_->Get(ckey); SelectKeyResult res; if (cache_ft.valid) { if (!cache_ft.val.ids->size() || (ftctx->NeedArea() && !cache_ft.val.ctx->need_area_)) { need_put = true; } else { if (cfg_->logLevel >= LogInfo) { logPrintf(LogInfo, "Get search results for '%s' in '%s' from cache", keys[0].As<string>(), this->payloadType_ ? this->payloadType_->Name() : ""); } res.push_back(SingleSelectKeyResult(cache_ft.val.ids)); SelectKeyResults r(std::move(res)); assert(cache_ft.val.ctx); ftctx->SetData(cache_ft.val.ctx); return r; } } if (cfg_->logLevel >= LogInfo) { logPrintf(LogInfo, "Searching for '%s' in '%s' %s", keys[0].As<string>(), this->payloadType_ ? this->payloadType_->Name() : "", need_put ? "(will cache)" : ""); } // STEP 1: Parse search query dsl FtDSLQuery dsl(this->ftFields_, this->cfg_->stopWords, this->cfg_->extraWordSymbols); dsl.parse(keys[0].As<string>()); smart_lock<Mutex> lck(mtx_, rdxCtx); if (!this->isBuilt_) { // non atomic upgrade mutex to unique lck.unlock(); lck = smart_lock<Mutex>(mtx_, rdxCtx, true); if (!this->isBuilt_) { CommitFulltext(); need_put = false; } } auto mergedIds = Select(ftctx, dsl); if (mergedIds) { if (need_put && mergedIds->size()) cache_ft_->Put(ckey, FtIdSetCacheVal{mergedIds, ftctx->GetData()}); res.push_back(SingleSelectKeyResult(mergedIds)); } return SelectKeyResults(std::move(res)); } template <typename T> FieldsGetter IndexText<T>::Getter() { return FieldsGetter(this->fields_, this->payloadType_, this->KeyType()); } template class IndexText<unordered_str_map<FtKeyEntry>>; template class IndexText<unordered_payload_map<FtKeyEntry, true>>; } // namespace reindexer
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2017 The PIVX developers // Copyright (c) 2017-2018 The HUZU developers // Copyright (c) 2018 The ZEFIR developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "amount.h" #include "tinyformat.h" CFeeRate::CFeeRate(const CAmount& nFeePaid, size_t nSize) { if (nSize > 0) nSatoshisPerK = nFeePaid * 1000 / nSize; else nSatoshisPerK = 0; } CAmount CFeeRate::GetFee(size_t nSize) const { CAmount nFee = nSatoshisPerK * nSize / 1000; if (nFee == 0 && nSatoshisPerK > 0) nFee = nSatoshisPerK; return nFee; } std::string CFeeRate::ToString() const { return strprintf("%d.%08d ZEFIR/kB", nSatoshisPerK / COIN, nSatoshisPerK % COIN); }
//===-- FindSymbolsTests.cpp -------------------------*- C++ -*------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "FindTarget.h" #include "Selection.h" #include "TestTU.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclTemplate.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Casting.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Testing/Support/Annotations.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include <initializer_list> namespace clang { namespace clangd { namespace { // A referenced Decl together with its DeclRelationSet, for assertions. // // There's no great way to assert on the "content" of a Decl in the general case // that's both expressive and unambiguous (e.g. clearly distinguishes between // templated decls and their specializations). // // We use the result of pretty-printing the decl, with the {body} truncated. struct PrintedDecl { PrintedDecl(const char *Name, DeclRelationSet Relations = {}) : Name(Name), Relations(Relations) {} PrintedDecl(const Decl *D, DeclRelationSet Relations = {}) : Relations(Relations) { std::string S; llvm::raw_string_ostream OS(S); D->print(OS); llvm::StringRef FirstLine = llvm::StringRef(OS.str()).take_until([](char C) { return C == '\n'; }); FirstLine = FirstLine.rtrim(" {"); Name = FirstLine.rtrim(" {"); } std::string Name; DeclRelationSet Relations; }; bool operator==(const PrintedDecl &L, const PrintedDecl &R) { return std::tie(L.Name, L.Relations) == std::tie(R.Name, R.Relations); } llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const PrintedDecl &D) { return OS << D.Name << " Rel=" << D.Relations; } // The test cases in for targetDecl() take the form // - a piece of code (Code = "...") // - Code should have a single AST node marked as a [[range]] // - an EXPECT_DECLS() assertion that verify the type of node selected, and // all the decls that targetDecl() considers it to reference // Despite the name, these cases actually test allTargetDecls() for brevity. class TargetDeclTest : public ::testing::Test { protected: using Rel = DeclRelation; std::string Code; std::vector<const char *> Flags; // Asserts that `Code` has a marked selection of a node `NodeType`, // and returns allTargetDecls() as PrintedDecl structs. // Use via EXPECT_DECLS(). std::vector<PrintedDecl> assertNodeAndPrintDecls(const char *NodeType) { llvm::Annotations A(Code); auto TU = TestTU::withCode(A.code()); TU.ExtraArgs = Flags; auto AST = TU.build(); EXPECT_THAT(AST.getDiagnostics(), ::testing::IsEmpty()) << Code; llvm::Annotations::Range R = A.range(); SelectionTree Selection(AST.getASTContext(), AST.getTokens(), R.Begin, R.End); const SelectionTree::Node *N = Selection.commonAncestor(); if (!N) { ADD_FAILURE() << "No node selected!\n" << Code; return {}; } EXPECT_EQ(N->kind(), NodeType) << Selection; std::vector<PrintedDecl> ActualDecls; for (const auto &Entry : allTargetDecls(N->ASTNode)) ActualDecls.emplace_back(Entry.first, Entry.second); return ActualDecls; } }; // This is a macro to preserve line numbers in assertion failures. // It takes the expected decls as varargs to work around comma-in-macro issues. #define EXPECT_DECLS(NodeType, ...) \ EXPECT_THAT(assertNodeAndPrintDecls(NodeType), \ ::testing::UnorderedElementsAreArray( \ std::vector<PrintedDecl>({__VA_ARGS__}))) \ << Code using ExpectedDecls = std::vector<PrintedDecl>; TEST_F(TargetDeclTest, Exprs) { Code = R"cpp( int f(); int x = [[f]](); )cpp"; EXPECT_DECLS("DeclRefExpr", "int f()"); Code = R"cpp( struct S { S operator+(S) const; }; auto X = S() [[+]] S(); )cpp"; EXPECT_DECLS("DeclRefExpr", "S operator+(S) const"); } TEST_F(TargetDeclTest, UsingDecl) { Code = R"cpp( namespace foo { int f(int); int f(char); } using foo::f; int x = [[f]](42); )cpp"; // f(char) is not referenced! EXPECT_DECLS("DeclRefExpr", {"using foo::f", Rel::Alias}, {"int f(int)", Rel::Underlying}); Code = R"cpp( namespace foo { int f(int); int f(char); } [[using foo::f]]; )cpp"; // All overloads are referenced. EXPECT_DECLS("UsingDecl", {"using foo::f", Rel::Alias}, {"int f(int)", Rel::Underlying}, {"int f(char)", Rel::Underlying}); Code = R"cpp( struct X { int foo(); }; struct Y : X { using X::foo; }; int x = Y().[[foo]](); )cpp"; EXPECT_DECLS("MemberExpr", {"using X::foo", Rel::Alias}, {"int foo()", Rel::Underlying}); } TEST_F(TargetDeclTest, ConstructorInitList) { Code = R"cpp( struct X { int a; X() : [[a]](42) {} }; )cpp"; EXPECT_DECLS("CXXCtorInitializer", "int a"); Code = R"cpp( struct X { X() : [[X]](1) {} X(int); }; )cpp"; EXPECT_DECLS("RecordTypeLoc", "struct X"); } TEST_F(TargetDeclTest, DesignatedInit) { Flags = {"-xc"}; // array designators are a C99 extension. Code = R"c( struct X { int a; }; struct Y { int b; struct X c[2]; }; struct Y y = { .c[0].[[a]] = 1 }; )c"; EXPECT_DECLS("DesignatedInitExpr", "int a"); } TEST_F(TargetDeclTest, NestedNameSpecifier) { Code = R"cpp( namespace a { namespace b { int c; } } int x = a::[[b::]]c; )cpp"; EXPECT_DECLS("NestedNameSpecifierLoc", "namespace b"); Code = R"cpp( namespace a { struct X { enum { y }; }; } int x = a::[[X::]]y; )cpp"; EXPECT_DECLS("NestedNameSpecifierLoc", "struct X"); Code = R"cpp( template <typename T> int x = [[T::]]y; )cpp"; // FIXME: We don't do a good job printing TemplateTypeParmDecls, apparently! EXPECT_DECLS("NestedNameSpecifierLoc", ""); Code = R"cpp( namespace a { int x; } namespace b = a; int y = [[b]]::x; )cpp"; EXPECT_DECLS("NestedNameSpecifierLoc", {"namespace b = a", Rel::Alias}, {"namespace a", Rel::Underlying}); } TEST_F(TargetDeclTest, Types) { Code = R"cpp( struct X{}; [[X]] x; )cpp"; EXPECT_DECLS("RecordTypeLoc", "struct X"); Code = R"cpp( struct S{}; typedef S X; [[X]] x; )cpp"; EXPECT_DECLS("TypedefTypeLoc", {"typedef S X", Rel::Alias}, {"struct S", Rel::Underlying}); // FIXME: Auto-completion in a template requires disabling delayed template // parsing. Flags = {"-fno-delayed-template-parsing"}; Code = R"cpp( template<class T> void foo() { [[T]] x; } )cpp"; // FIXME: We don't do a good job printing TemplateTypeParmDecls, apparently! EXPECT_DECLS("TemplateTypeParmTypeLoc", ""); Flags.clear(); // FIXME: Auto-completion in a template requires disabling delayed template // parsing. Flags = {"-fno-delayed-template-parsing"}; Code = R"cpp( template<template<typename> class T> void foo() { [[T<int>]] x; } )cpp"; EXPECT_DECLS("TemplateSpecializationTypeLoc", "template <typename> class T"); Flags.clear(); Code = R"cpp( struct S{}; S X; [[decltype]](X) Y; )cpp"; EXPECT_DECLS("DecltypeTypeLoc", {"struct S", Rel::Underlying}); Code = R"cpp( struct S{}; [[auto]] X = S{}; )cpp"; // FIXME: deduced type missing in AST. https://llvm.org/PR42914 EXPECT_DECLS("AutoTypeLoc"); } TEST_F(TargetDeclTest, ClassTemplate) { Code = R"cpp( // Implicit specialization. template<int x> class Foo{}; [[Foo<42>]] B; )cpp"; EXPECT_DECLS("TemplateSpecializationTypeLoc", {"template<> class Foo<42>", Rel::TemplateInstantiation}, {"class Foo", Rel::TemplatePattern}); Code = R"cpp( // Explicit specialization. template<int x> class Foo{}; template<> class Foo<42>{}; [[Foo<42>]] B; )cpp"; EXPECT_DECLS("TemplateSpecializationTypeLoc", "template<> class Foo<42>"); Code = R"cpp( // Partial specialization. template<typename T> class Foo{}; template<typename T> class Foo<T*>{}; [[Foo<int*>]] B; )cpp"; EXPECT_DECLS("TemplateSpecializationTypeLoc", {"template<> class Foo<int *>", Rel::TemplateInstantiation}, {"template <typename T> class Foo<type-parameter-0-0 *>", Rel::TemplatePattern}); } TEST_F(TargetDeclTest, FunctionTemplate) { Code = R"cpp( // Implicit specialization. template<typename T> bool foo(T) { return false; }; bool x = [[foo]](42); )cpp"; EXPECT_DECLS("DeclRefExpr", {"template<> bool foo<int>(int)", Rel::TemplateInstantiation}, {"bool foo(T)", Rel::TemplatePattern}); Code = R"cpp( // Explicit specialization. template<typename T> bool foo(T) { return false; }; template<> bool foo<int>(int) { return false; }; bool x = [[foo]](42); )cpp"; EXPECT_DECLS("DeclRefExpr", "template<> bool foo<int>(int)"); } TEST_F(TargetDeclTest, VariableTemplate) { // Pretty-printer doesn't do a very good job of variable templates :-( Code = R"cpp( // Implicit specialization. template<typename T> int foo; int x = [[foo]]<char>; )cpp"; EXPECT_DECLS("DeclRefExpr", {"int foo", Rel::TemplateInstantiation}, {"int foo", Rel::TemplatePattern}); Code = R"cpp( // Explicit specialization. template<typename T> int foo; template <> bool foo<char>; int x = [[foo]]<char>; )cpp"; EXPECT_DECLS("DeclRefExpr", "bool foo"); Code = R"cpp( // Partial specialization. template<typename T> int foo; template<typename T> bool foo<T*>; bool x = [[foo]]<char*>; )cpp"; EXPECT_DECLS("DeclRefExpr", {"bool foo", Rel::TemplateInstantiation}, {"bool foo", Rel::TemplatePattern}); } TEST_F(TargetDeclTest, TypeAliasTemplate) { Code = R"cpp( template<typename T, int X> class SmallVector {}; template<typename U> using TinyVector = SmallVector<U, 1>; [[TinyVector<int>]] X; )cpp"; EXPECT_DECLS("TemplateSpecializationTypeLoc", {"template<> class SmallVector<int, 1>", Rel::TemplateInstantiation | Rel::Underlying}, {"class SmallVector", Rel::TemplatePattern | Rel::Underlying}, {"using TinyVector = SmallVector<U, 1>", Rel::Alias | Rel::TemplatePattern}); } TEST_F(TargetDeclTest, MemberOfTemplate) { Code = R"cpp( template <typename T> struct Foo { int x(T); }; int y = Foo<int>().[[x]](42); )cpp"; EXPECT_DECLS("MemberExpr", {"int x(int)", Rel::TemplateInstantiation}, {"int x(T)", Rel::TemplatePattern}); Code = R"cpp( template <typename T> struct Foo { template <typename U> int x(T, U); }; int y = Foo<char>().[[x]]('c', 42); )cpp"; EXPECT_DECLS("MemberExpr", {"template<> int x<int>(char, int)", Rel::TemplateInstantiation}, {"int x(T, U)", Rel::TemplatePattern}); } TEST_F(TargetDeclTest, Lambda) { Code = R"cpp( void foo(int x = 42) { auto l = [ [[x]] ]{ return x + 1; }; }; )cpp"; EXPECT_DECLS("DeclRefExpr", "int x = 42"); // It seems like this should refer to another var, with the outer param being // an underlying decl. But it doesn't seem to exist. Code = R"cpp( void foo(int x = 42) { auto l = [x]{ return [[x]] + 1; }; }; )cpp"; EXPECT_DECLS("DeclRefExpr", "int x = 42"); Code = R"cpp( void foo() { auto l = [x = 1]{ return [[x]] + 1; }; }; )cpp"; // FIXME: why both auto and int? EXPECT_DECLS("DeclRefExpr", "auto int x = 1"); } TEST_F(TargetDeclTest, OverloadExpr) { // FIXME: Auto-completion in a template requires disabling delayed template // parsing. Flags = {"-fno-delayed-template-parsing"}; Code = R"cpp( void func(int*); void func(char*); template <class T> void foo(T t) { [[func]](t); }; )cpp"; EXPECT_DECLS("UnresolvedLookupExpr", "void func(int *)", "void func(char *)"); Code = R"cpp( struct X { void func(int*); void func(char*); }; template <class T> void foo(X x, T t) { x.[[func]](t); }; )cpp"; EXPECT_DECLS("UnresolvedMemberExpr", "void func(int *)", "void func(char *)"); } TEST_F(TargetDeclTest, ObjC) { Flags = {"-xobjective-c"}; Code = R"cpp( @interface Foo {} -(void)bar; @end void test(Foo *f) { [f [[bar]] ]; } )cpp"; EXPECT_DECLS("ObjCMessageExpr", "- (void)bar"); Code = R"cpp( @interface Foo { @public int bar; } @end int test(Foo *f) { return [[f->bar]]; } )cpp"; EXPECT_DECLS("ObjCIvarRefExpr", "int bar"); Code = R"cpp( @interface Foo {} -(int) x; -(void) setX:(int)x; @end void test(Foo *f) { [[f.x]] = 42; } )cpp"; EXPECT_DECLS("ObjCPropertyRefExpr", "- (void)setX:(int)x"); Code = R"cpp( @interface Foo {} @property int x; @end void test(Foo *f) { [[f.x]] = 42; } )cpp"; EXPECT_DECLS("ObjCPropertyRefExpr", "@property(atomic, assign, unsafe_unretained, readwrite) int x"); Code = R"cpp( @protocol Foo @end id test() { return [[@protocol(Foo)]]; } )cpp"; EXPECT_DECLS("ObjCProtocolExpr", "@protocol Foo"); Code = R"cpp( @interface Foo @end void test([[Foo]] *p); )cpp"; EXPECT_DECLS("ObjCInterfaceTypeLoc", "@interface Foo"); Code = R"cpp( @protocol Foo @end void test([[id<Foo>]] p); )cpp"; EXPECT_DECLS("ObjCObjectTypeLoc", "@protocol Foo"); Code = R"cpp( @class C; @protocol Foo @end void test(C<[[Foo]]> *p); )cpp"; // FIXME: there's no AST node corresponding to 'Foo', so we're stuck. EXPECT_DECLS("ObjCObjectTypeLoc"); } class FindExplicitReferencesTest : public ::testing::Test { protected: struct AllRefs { std::string AnnotatedCode; std::string DumpedReferences; }; /// Parses \p Code, finds function '::foo' and annotates its body with results /// of findExplicitReferecnces. /// See actual tests for examples of annotation format. AllRefs annotateReferencesInFoo(llvm::StringRef Code) { TestTU TU; TU.Code = Code; // FIXME: Auto-completion in a template requires disabling delayed template // parsing. TU.ExtraArgs.push_back("-fno-delayed-template-parsing"); auto AST = TU.build(); auto *TestDecl = &findDecl(AST, "foo"); if (auto *T = llvm::dyn_cast<FunctionTemplateDecl>(TestDecl)) TestDecl = T->getTemplatedDecl(); auto &Func = llvm::cast<FunctionDecl>(*TestDecl); std::vector<ReferenceLoc> Refs; findExplicitReferences(Func.getBody(), [&Refs](ReferenceLoc R) { Refs.push_back(std::move(R)); }); auto &SM = AST.getSourceManager(); llvm::sort(Refs, [&](const ReferenceLoc &L, const ReferenceLoc &R) { return SM.isBeforeInTranslationUnit(L.NameLoc, R.NameLoc); }); std::string AnnotatedCode; unsigned NextCodeChar = 0; for (unsigned I = 0; I < Refs.size(); ++I) { auto &R = Refs[I]; SourceLocation Pos = R.NameLoc; assert(Pos.isValid()); if (Pos.isMacroID()) // FIXME: figure out how to show macro locations. Pos = SM.getExpansionLoc(Pos); assert(Pos.isFileID()); FileID File; unsigned Offset; std::tie(File, Offset) = SM.getDecomposedLoc(Pos); if (File == SM.getMainFileID()) { // Print the reference in a source code. assert(NextCodeChar <= Offset); AnnotatedCode += Code.substr(NextCodeChar, Offset - NextCodeChar); AnnotatedCode += "$" + std::to_string(I) + "^"; NextCodeChar = Offset; } } AnnotatedCode += Code.substr(NextCodeChar); std::string DumpedReferences; for (unsigned I = 0; I < Refs.size(); ++I) DumpedReferences += llvm::formatv("{0}: {1}\n", I, Refs[I]); return AllRefs{std::move(AnnotatedCode), std::move(DumpedReferences)}; } }; TEST_F(FindExplicitReferencesTest, All) { std::pair</*Code*/ llvm::StringRef, /*References*/ llvm::StringRef> Cases[] = { // Simple expressions. {R"cpp( int global; int func(); void foo(int param) { $0^global = $1^param + $2^func(); } )cpp", "0: targets = {global}\n" "1: targets = {param}\n" "2: targets = {func}\n"}, {R"cpp( struct X { int a; }; void foo(X x) { $0^x.$1^a = 10; } )cpp", "0: targets = {x}\n" "1: targets = {X::a}\n"}, // Namespaces and aliases. {R"cpp( namespace ns {} namespace alias = ns; void foo() { using namespace $0^ns; using namespace $1^alias; } )cpp", "0: targets = {ns}\n" "1: targets = {alias}\n"}, // Using declarations. {R"cpp( namespace ns { int global; } void foo() { using $0^ns::$1^global; } )cpp", "0: targets = {ns}\n" "1: targets = {ns::global}, qualifier = 'ns::'\n"}, // Simple types. {R"cpp( struct Struct { int a; }; using Typedef = int; void foo() { $0^Struct $1^x; $2^Typedef $3^y; static_cast<$4^Struct*>(0); } )cpp", "0: targets = {Struct}\n" "1: targets = {x}, decl\n" "2: targets = {Typedef}\n" "3: targets = {y}, decl\n" "4: targets = {Struct}\n"}, // Name qualifiers. {R"cpp( namespace a { namespace b { struct S { typedef int type; }; } } void foo() { $0^a::$1^b::$2^S $3^x; using namespace $4^a::$5^b; $6^S::$7^type $8^y; } )cpp", "0: targets = {a}\n" "1: targets = {a::b}, qualifier = 'a::'\n" "2: targets = {a::b::S}, qualifier = 'a::b::'\n" "3: targets = {x}, decl\n" "4: targets = {a}\n" "5: targets = {a::b}, qualifier = 'a::'\n" "6: targets = {a::b::S}\n" "7: targets = {a::b::S::type}, qualifier = 'struct S::'\n" "8: targets = {y}, decl\n"}, // Simple templates. {R"cpp( template <class T> struct vector { using value_type = T; }; template <> struct vector<bool> { using value_type = bool; }; void foo() { $0^vector<int> $1^vi; $2^vector<bool> $3^vb; } )cpp", "0: targets = {vector<int>}\n" "1: targets = {vi}, decl\n" "2: targets = {vector<bool>}\n" "3: targets = {vb}, decl\n"}, // Template type aliases. {R"cpp( template <class T> struct vector { using value_type = T; }; template <> struct vector<bool> { using value_type = bool; }; template <class T> using valias = vector<T>; void foo() { $0^valias<int> $1^vi; $2^valias<bool> $3^vb; } )cpp", "0: targets = {valias}\n" "1: targets = {vi}, decl\n" "2: targets = {valias}\n" "3: targets = {vb}, decl\n"}, // MemberExpr should know their using declaration. {R"cpp( struct X { void func(int); } struct Y : X { using X::func; }; void foo(Y y) { $0^y.$1^func(1); } )cpp", "0: targets = {y}\n" "1: targets = {Y::func}\n"}, // DeclRefExpr should know their using declaration. {R"cpp( namespace ns { void bar(int); } using ns::bar; void foo() { $0^bar(10); } )cpp", "0: targets = {bar}\n"}, // References from a macro. {R"cpp( #define FOO a #define BAR b void foo(int a, int b) { $0^FOO+$1^BAR; } )cpp", "0: targets = {a}\n" "1: targets = {b}\n"}, // No references from implicit nodes. {R"cpp( struct vector { int *begin(); int *end(); }; void foo() { for (int $0^x : $1^vector()) { $2^x = 10; } } )cpp", "0: targets = {x}, decl\n" "1: targets = {vector}\n" "2: targets = {x}\n"}, // Handle UnresolvedLookupExpr. {R"cpp( namespace ns1 { void func(char*); } namespace ns2 { void func(int*); } using namespace ns1; using namespace ns2; template <class T> void foo(T t) { $0^func($1^t); } )cpp", "0: targets = {ns1::func, ns2::func}\n" "1: targets = {t}\n"}, // Handle UnresolvedMemberExpr. {R"cpp( struct X { void func(char*); void func(int*); }; template <class T> void foo(X x, T t) { $0^x.$1^func($2^t); } )cpp", "0: targets = {x}\n" "1: targets = {X::func, X::func}\n" "2: targets = {t}\n"}, // Type template parameters. {R"cpp( template <class T> void foo() { static_cast<$0^T>(0); $1^T(); $2^T $3^t; } )cpp", "0: targets = {T}\n" "1: targets = {T}\n" "2: targets = {T}\n" "3: targets = {t}, decl\n"}, // Non-type template parameters. {R"cpp( template <int I> void foo() { int $0^x = $1^I; } )cpp", "0: targets = {x}, decl\n" "1: targets = {I}\n"}, // Template template parameters. {R"cpp( template <class T> struct vector {}; template <template<class> class TT, template<class> class ...TP> void foo() { $0^TT<int> $1^x; $2^foo<$3^TT>(); $4^foo<$5^vector>() $6^foo<$7^TP...>(); } )cpp", "0: targets = {TT}\n" "1: targets = {x}, decl\n" "2: targets = {foo}\n" "3: targets = {TT}\n" "4: targets = {foo}\n" "5: targets = {vector}\n" "6: targets = {foo}\n" "7: targets = {TP}\n"}, // Non-type template parameters with declarations. {R"cpp( int func(); template <int(*)()> struct wrapper {}; template <int(*FuncParam)()> void foo() { $0^wrapper<$1^func> $2^w; $3^FuncParam(); } )cpp", "0: targets = {wrapper<&func>}\n" "1: targets = {func}\n" "2: targets = {w}, decl\n" "3: targets = {FuncParam}\n"}, // declaration references. {R"cpp( namespace ns {} class S {}; void foo() { class $0^Foo { $1^Foo(); ~$2^Foo(); int $3^field; }; int $4^Var; enum $5^E { $6^ABC }; typedef int $7^INT; using $8^INT2 = int; namespace $9^NS = $10^ns; } )cpp", "0: targets = {Foo}, decl\n" "1: targets = {foo()::Foo::Foo}, decl\n" "2: targets = {Foo}\n" "3: targets = {foo()::Foo::field}, decl\n" "4: targets = {Var}, decl\n" "5: targets = {E}, decl\n" "6: targets = {foo()::ABC}, decl\n" "7: targets = {INT}, decl\n" "8: targets = {INT2}, decl\n" "9: targets = {NS}, decl\n" "10: targets = {ns}\n"}, // cxx constructor initializer. {R"cpp( class Base {}; void foo() { // member initializer class $0^X { int $1^abc; $2^X(): $3^abc() {} }; // base initializer class $4^Derived : public $5^Base { $6^Base $7^B; $8^Derived() : $9^Base() {} }; // delegating initializer class $10^Foo { $11^Foo(int$12^); $13^Foo(): $14^Foo(111) {} }; } )cpp", "0: targets = {X}, decl\n" "1: targets = {foo()::X::abc}, decl\n" "2: targets = {foo()::X::X}, decl\n" "3: targets = {foo()::X::abc}\n" "4: targets = {Derived}, decl\n" "5: targets = {Base}\n" "6: targets = {Base}\n" "7: targets = {foo()::Derived::B}, decl\n" "8: targets = {foo()::Derived::Derived}, decl\n" "9: targets = {Base}\n" "10: targets = {Foo}, decl\n" "11: targets = {foo()::Foo::Foo}, decl\n" // FIXME: we should exclude the built-in type. "12: targets = {}, decl\n" "13: targets = {foo()::Foo::Foo}, decl\n" "14: targets = {Foo}\n"}, }; for (const auto &C : Cases) { llvm::StringRef ExpectedCode = C.first; llvm::StringRef ExpectedRefs = C.second; auto Actual = annotateReferencesInFoo(llvm::Annotations(ExpectedCode).code()); EXPECT_EQ(ExpectedCode, Actual.AnnotatedCode); EXPECT_EQ(ExpectedRefs, Actual.DumpedReferences) << ExpectedCode; } } } // namespace } // namespace clangd } // namespace clang
// Copyright (c) 2019-2021 MicroBitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util.h> #include <amount.h> #include <snapshot.h> #include <util/time.h> #include <util/system.h> #include <util/strencodings.h> #include <primitives/transaction.h> #include <support/httplib.h> #include <support/csv.h> #include <core_io.h> #include <random> #include <fs.h> std::string TimestampStr() { return FormatISO8601DateTime(GetTimeMicros() / 1000000) + " "; } CScript ReadScriptSnapshot(const std::string& s) { size_t pos = s.find(" "); size_t initial_pos = 0; std::vector<std::string> splited; while(pos != std::string::npos) { splited.push_back(s.substr(initial_pos, pos - initial_pos)); initial_pos = pos + 1; pos = s.find(" ", initial_pos); } splited.push_back(s.substr(initial_pos, std::min(pos, s.size()) - initial_pos + 1)); if (splited.size() == 5) { // It's p2pkh script // Some sanity checks assert(splited[0] == "OP_DUP"); assert(splited[1] == "OP_HASH160"); assert(splited[2].length() == 40); assert(splited[3] == "OP_EQUALVERIFY"); assert(splited[4] == "OP_CHECKSIG"); return CScript() << OP_DUP << OP_HASH160 << ParseHex(splited[2]) << OP_EQUALVERIFY << OP_CHECKSIG; } else { // It's p2sh script // Some sanity checks assert(splited[0] == "OP_HASH160"); assert(splited[1].length() == 40); assert(splited[2] == "OP_EQUAL"); return CScript() << OP_HASH160 << ParseHex(splited[1]) << OP_EQUAL; } } bool FetchSnapshot(fs::path &path, SnapshotProvider provider) { httplib::Client cli(provider.address.c_str()); auto result = cli.Get(provider.path.c_str()); if (result && result->status == 200) { std::cout << TimestampStr() << "Shapshot: Successfully fetched snapshot file" << std::endl; FILE *snapshot_file = fsbridge::fopen(path, "w"); fwrite(result->body.data(), 1, result->body.size(), snapshot_file); fclose(snapshot_file); return true; } else { std::cout << TimestampStr() << "Shapshot: Failed to fetch snapshot file from the server" << std::endl; return false; } } std::vector<SnapshotEntry> LoadSnapshot(fs::path &path) { std::vector<SnapshotEntry> vSnapshot; fs::ifstream stream(path); csv::parser snapshot(stream); for (auto& row : snapshot) { SnapshotEntry utxo; bool key = false; for (auto& field : row) { if (!key) { key = true; utxo.script = ReadScriptSnapshot(field); } else { key = false; std::istringstream iss(field); iss >> utxo.amount; vSnapshot.push_back(utxo); } } } return vSnapshot; } std::vector<SnapshotEntry> EmptySnapshot() { std::vector<SnapshotEntry> vSnapshot; return vSnapshot; } std::vector<SnapshotEntry> InitSnapshot(const std::string fileName, std::vector<SnapshotProvider> providers) { fs::path snapshot_dir = gArgs.GetDataDirBase() / "snapshot"; fs::path path = snapshot_dir / fileName; fs::create_directories(snapshot_dir); if (!fs::exists(path)) { // Pick random snapshot provider std::random_device random_device; std::mt19937 engine {random_device()}; std::uniform_int_distribution<int> dist(0, providers.size() - 1); int provider_index = dist(engine); std::cout << TimestampStr() << "Shapshot: File " << fileName << " not found, trying to fetch it from " << providers[provider_index].address << providers[provider_index].path << std::endl; bool loaded = FetchSnapshot(path, providers[provider_index]); assert(loaded); } return LoadSnapshot(path); }
/* Copyright (c) 2020 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License. */ #include "graph/planner/SequentialPlanner.h" #include "graph/planner/plan/Logic.h" #include "graph/planner/plan/Query.h" #include "graph/validator/SequentialValidator.h" #include "parser/Sentence.h" namespace nebula { namespace graph { bool SequentialPlanner::match(AstContext* astCtx) { return astCtx->sentence->kind() == Sentence::Kind::kSequential; } StatusOr<SubPlan> SequentialPlanner::transform(AstContext* astCtx) { SubPlan subPlan; auto* seqCtx = static_cast<SequentialAstContext*>(astCtx); auto* qctx = seqCtx->qctx; const auto& validators = seqCtx->validators; subPlan.root = validators.back()->root(); ifBuildDataCollect(subPlan, qctx); for (auto iter = validators.begin(); iter < validators.end() - 1; ++iter) { // Remove left tail kStart plannode before append plan. // It allows that kUse sentence to append kMatch Sentence. // For example: Use ...; Match ... rmLeftTailStartNode((iter + 1)->get(), iter->get()->sentence()->kind()); NG_RETURN_IF_ERROR((iter + 1)->get()->appendPlan(iter->get()->root())); } if (validators.front()->tail()->isSingleInput()) { subPlan.tail = seqCtx->startNode; NG_RETURN_IF_ERROR(validators.front()->appendPlan(subPlan.tail)); } else { subPlan.tail = validators.front()->tail(); } VLOG(1) << subPlan; return subPlan; } void SequentialPlanner::ifBuildDataCollect(SubPlan& subPlan, QueryContext* qctx) { switch (subPlan.root->kind()) { case PlanNode::Kind::kSort: case PlanNode::Kind::kLimit: case PlanNode::Kind::kSample: case PlanNode::Kind::kDedup: case PlanNode::Kind::kUnion: case PlanNode::Kind::kUnionAllVersionVar: case PlanNode::Kind::kIntersect: case PlanNode::Kind::kCartesianProduct: case PlanNode::Kind::kMinus: case PlanNode::Kind::kFilter: { auto* dc = DataCollect::make(qctx, DataCollect::DCKind::kRowBasedMove); dc->addDep(subPlan.root); dc->setInputVars({subPlan.root->outputVar()}); dc->setColNames(subPlan.root->colNames()); subPlan.root = dc; break; } default: break; } } // When appending plans, it need to remove left tail plannode. // Because the left tail plannode is StartNode which needs to be removed, // and remain one size for add dependency // TODO: It's a temporary solution, remove it after Execute multiple sequences one by one. void SequentialPlanner::rmLeftTailStartNode(Validator* validator, Sentence::Kind appendPlanKind) { if (appendPlanKind != Sentence::Kind::kUse || validator->tail()->kind() != PlanNode::Kind::kStart || validator->root()->dependencies().size() == 0UL) { return; } PlanNode* node = validator->root(); while (node->dependencies()[0]->dependencies().size() > 0UL) { node = const_cast<PlanNode*>(node->dependencies()[0]); } if (node->dependencies().size() == 1UL) { // Remain one size for add dependency node->dependencies()[0] = nullptr; validator->setTail(node); } } } // namespace graph } // namespace nebula
#define PUT(x) std::cout << #x << "=" << (x) << std::endl; #include <cybozu/test.hpp> #include <cybozu/benchmark.hpp> #include <cybozu/xorshift.hpp> #include <fstream> #include <time.h> #include <mcl/she.hpp> #include <mcl/ecparam.hpp> // for secp192k1 using namespace mcl::she; SecretKey g_sec; CYBOZU_TEST_AUTO(log) { #if MCLBN_FP_UNIT_SIZE == 4 const mcl::CurveParam& cp = mcl::BN254; puts("BN254"); #elif MCLBN_FP_UNIT_SIZE == 6 const mcl::CurveParam& cp = mcl::BN381_1; puts("BN381_1"); #elif MCLBN_FP_UNIT_SIZE == 8 const mcl::CurveParam& cp = mcl::BN462; puts("BN462"); #endif init(cp); G1 P; hashAndMapToG1(P, "abc"); for (int i = -5; i < 5; i++) { G1 iP; G1::mul(iP, P, i); CYBOZU_TEST_EQUAL(mcl::she::local::log(P, iP), i); } } //#define PAPER #ifdef PAPER double clk2msec(const cybozu::CpuClock& clk, int n) { const double rate = (1 / 3.4e9) * 1.e3; // 3.4GHz return clk.getClock() / (double)clk.getCount() / n * rate; } CYBOZU_TEST_AUTO(bench2) { puts("msec"); setTryNum(1 << 16); useDecG1ViaGT(true); useDecG2ViaGT(true); #if 0 setRangeForDLP(1 << 21); #else { const char *tblName = "../she-dlp-table/she-dlp-0-20-gt.bin"; std::ifstream ifs(tblName, std::ios::binary); getHashTableGT().load(ifs); } #endif SecretKey sec; sec.setByCSPRNG(); PublicKey pub; sec.getPublicKey(pub); PrecomputedPublicKey ppub; ppub.init(pub); const int C = 500; double t1, t2; int64_t m = (1ll << 31) - 12345; CipherTextG1 c1, d1; CipherTextG2 c2, d2; CipherTextGT ct, dt; CYBOZU_BENCH_C("", C, ppub.enc, c1, m); t1 = clk2msec(cybozu::bench::g_clk, C); CYBOZU_TEST_EQUAL(sec.dec(c1), m); CYBOZU_BENCH_C("", C, ppub.enc, c2, m); t2 = clk2msec(cybozu::bench::g_clk, C); CYBOZU_TEST_EQUAL(sec.dec(c2), m); printf("Enc G1 %.2e\n", t1); printf("Enc G2 %.2e\n", t2); printf("Enc L1(G1+G2) %.2e\n", t1 + t2); CYBOZU_BENCH_C("", C, ppub.enc, ct, m); t1 = clk2msec(cybozu::bench::g_clk, C); CYBOZU_TEST_EQUAL(sec.dec(ct), m); printf("Enc L2 %.2e\n", t1); CYBOZU_BENCH_C("", C, sec.dec, c1); t1 = clk2msec(cybozu::bench::g_clk, C); printf("Dec L1 %.2e\n", t1); CYBOZU_BENCH_C("", C, sec.dec, ct); t1 = clk2msec(cybozu::bench::g_clk, C); printf("Dec L2 %.2e\n", t1); pub.enc(ct, 1234); CYBOZU_BENCH_C("", C, sec.dec, ct); t1 = clk2msec(cybozu::bench::g_clk, C); printf("Dec L2(small) %.2e\n", t1); CYBOZU_BENCH_C("", C, add, d1, d1, c1); t1 = clk2msec(cybozu::bench::g_clk, C); CYBOZU_BENCH_C("", C, add, d2, d2, c2); t2 = clk2msec(cybozu::bench::g_clk, C); printf("Add G1 %.2e\n", t1); printf("Add G2 %.2e\n", t2); printf("Add L1(G1+G2) %.2e\n", t1 + t2); CYBOZU_BENCH_C("", C, add, dt, dt, ct); t1 = clk2msec(cybozu::bench::g_clk, C); printf("Add L2 %.2e\n", t1); CYBOZU_BENCH_C("", C, mul, ct, c1, c2); t1 = clk2msec(cybozu::bench::g_clk, C); printf("Mul %.2e\n", t1); CYBOZU_BENCH_C("", C, ppub.reRand, c1); t1 = clk2msec(cybozu::bench::g_clk, C); CYBOZU_BENCH_C("", C, ppub.reRand, c2); t2 = clk2msec(cybozu::bench::g_clk, C); printf("ReRand G1 %.2e\n", t1); printf("ReRand G2 %.2e\n", t2); printf("ReRand L1(G1+G2) %.2e\n", t1 + t2); CYBOZU_BENCH_C("", C, ppub.reRand, ct); t1 = clk2msec(cybozu::bench::g_clk, C); printf("ReRand L2 %.2e\n", t1); } #endif template<class G, class HashTbl> void GAHashTableTest(int maxSize, int tryNum, const G& P, const HashTbl& hashTbl) { for (int i = -maxSize; i <= maxSize; i++) { G xP; G::mul(xP, P, i); CYBOZU_TEST_EQUAL(hashTbl.basicLog(xP), i); } for (int i = -maxSize * tryNum; i <= maxSize * tryNum; i++) { G xP; G::mul(xP, P, i); CYBOZU_TEST_EQUAL(hashTbl.log(xP), i); } } template<class G> void HashTableTest(const G& P) { mcl::she::local::HashTable<G> hashTbl, hashTbl2; const int maxSize = 100; const int tryNum = 3; hashTbl.init(P, maxSize, tryNum); GAHashTableTest(maxSize, tryNum, P, hashTbl); std::stringstream ss; hashTbl.save(ss); hashTbl2.load(ss); GAHashTableTest(maxSize, tryNum, P, hashTbl2); } CYBOZU_TEST_AUTO(HashTable) { G1 P; hashAndMapToG1(P, "abc"); G2 Q; hashAndMapToG2(Q, "abc"); HashTableTest(P); HashTableTest(Q); } template<class HashTbl> void GTHashTableTest(int maxSize, int tryNum, const GT& g, const HashTbl& hashTbl) { for (int i = -maxSize; i <= maxSize; i++) { GT gx; GT::pow(gx, g, i); CYBOZU_TEST_EQUAL(hashTbl.basicLog(gx), i); } for (int i = -maxSize * tryNum; i <= maxSize * tryNum; i++) { GT gx; GT::pow(gx, g, i); CYBOZU_TEST_EQUAL(hashTbl.log(gx), i); } } CYBOZU_TEST_AUTO(GTHashTable) { mcl::she::local::HashTable<GT, false> hashTbl, hashTbl2; GT g; { G1 P; hashAndMapToG1(P, "abc"); G2 Q; hashAndMapToG2(Q, "abc"); pairing(g, P, Q); } const int maxSize = 100; const int tryNum = 3; hashTbl.init(g, maxSize, tryNum); GTHashTableTest(maxSize, tryNum, g, hashTbl); std::stringstream ss; hashTbl.save(ss); hashTbl2.load(ss); GTHashTableTest(maxSize, tryNum, g, hashTbl2); } CYBOZU_TEST_AUTO(enc_dec) { SecretKey& sec = g_sec; sec.setByCSPRNG(); setRangeForDLP(1024); PublicKey pub; sec.getPublicKey(pub); CipherText c; for (int i = -5; i < 5; i++) { pub.enc(c, i); CYBOZU_TEST_EQUAL(sec.dec(c), i); pub.reRand(c); CYBOZU_TEST_EQUAL(sec.dec(c), i); } PrecomputedPublicKey ppub; ppub.init(pub); CipherTextG1 c1; CipherTextG2 c2; CipherTextGT ct1, ct2; for (int i = -5; i < 5; i++) { pub.enc(ct1, i); CYBOZU_TEST_EQUAL(sec.dec(ct1), i); CYBOZU_TEST_EQUAL(sec.isZero(ct1), i == 0); ppub.enc(ct2, i); CYBOZU_TEST_EQUAL(sec.dec(ct2), i); ppub.enc(c1, i); CYBOZU_TEST_EQUAL(sec.dec(c1), i); CYBOZU_TEST_EQUAL(sec.decViaGT(c1), i); CYBOZU_TEST_EQUAL(sec.isZero(c1), i == 0); ct1.clear(); pub.convert(ct1, c1); CYBOZU_TEST_EQUAL(sec.dec(ct1), i); ppub.enc(c2, i); CYBOZU_TEST_EQUAL(sec.dec(c2), i); CYBOZU_TEST_EQUAL(sec.decViaGT(c2), i); CYBOZU_TEST_EQUAL(sec.isZero(c2), i == 0); ct1.clear(); pub.convert(ct1, c2); CYBOZU_TEST_EQUAL(sec.dec(ct1), i); pub.enc(c, i); CYBOZU_TEST_EQUAL(sec.isZero(c), i == 0); } } template<class CT, class PK> void ZkpBinTest(const SecretKey& sec, const PK& pub) { CT c; ZkpBin zkp; for (int m = 0; m < 2; m++) { pub.encWithZkpBin(c, zkp, m); CYBOZU_TEST_EQUAL(sec.dec(c), m); CYBOZU_TEST_ASSERT(pub.verify(c, zkp)); zkp.d_[0] += 1; CYBOZU_TEST_ASSERT(!pub.verify(c, zkp)); } CYBOZU_TEST_EXCEPTION(pub.encWithZkpBin(c, zkp, 2), cybozu::Exception); } CYBOZU_TEST_AUTO(ZkpBin) { const SecretKey& sec = g_sec; PublicKey pub; sec.getPublicKey(pub); ZkpBinTest<CipherTextG1>(sec, pub); ZkpBinTest<CipherTextG2>(sec, pub); PrecomputedPublicKey ppub; ppub.init(pub); ZkpBinTest<CipherTextG1>(sec, ppub); ZkpBinTest<CipherTextG2>(sec, ppub); } template<class PubT> void ZkpEqTest(const SecretKey& sec, const PubT& pub) { CipherTextG1 c1; CipherTextG2 c2; ZkpEq zkp; for (int m = -4; m < 4; m++) { pub.encWithZkpEq(c1, c2, zkp, m); CYBOZU_TEST_EQUAL(sec.dec(c1), m); CYBOZU_TEST_EQUAL(sec.dec(c2), m); CYBOZU_TEST_ASSERT(pub.verify(c1, c2, zkp)); zkp.d_[0] += 1; CYBOZU_TEST_ASSERT(!pub.verify(c1, c2, zkp)); } } CYBOZU_TEST_AUTO(ZkpEq) { const SecretKey& sec = g_sec; PublicKey pub; sec.getPublicKey(pub); PrecomputedPublicKey ppub; ppub.init(pub); ZkpEqTest(sec, pub); ZkpEqTest(sec, ppub); } template<class PK> void ZkpBinEqTest(const SecretKey& sec, const PK& pub) { CipherTextG1 c1; CipherTextG2 c2; ZkpBinEq zkp; for (int m = 0; m < 2; m++) { pub.encWithZkpBinEq(c1, c2, zkp, m); CYBOZU_TEST_EQUAL(sec.dec(c1), m); CYBOZU_TEST_EQUAL(sec.dec(c2), m); CYBOZU_TEST_ASSERT(pub.verify(c1, c2, zkp)); zkp.d_[0] += 1; CYBOZU_TEST_ASSERT(!pub.verify(c1, c2, zkp)); } CYBOZU_TEST_EXCEPTION(pub.encWithZkpBinEq(c1, c2, zkp, 2), cybozu::Exception); } CYBOZU_TEST_AUTO(ZkpBinEq) { const SecretKey& sec = g_sec; PublicKey pub; sec.getPublicKey(pub); ZkpBinEqTest(sec, pub); PrecomputedPublicKey ppub; ppub.init(pub); ZkpBinEqTest(sec, ppub); } CYBOZU_TEST_AUTO(ZkpDec) { const SecretKey& sec = g_sec; PublicKey pub; sec.getPublicKey(pub); CipherTextG1 c; int m = 123; pub.enc(c, m); ZkpDec zkp; CYBOZU_TEST_EQUAL(sec.decWithZkpDec(zkp, c, pub), m); CYBOZU_TEST_ASSERT(pub.verify(c, m, zkp)); CYBOZU_TEST_ASSERT(!pub.verify(c, m + 1, zkp)); CipherTextG1 c2; pub.enc(c2, m); CYBOZU_TEST_ASSERT(!pub.verify(c2, m, zkp)); zkp.d_[0] += 1; CYBOZU_TEST_ASSERT(!pub.verify(c, m, zkp)); } CYBOZU_TEST_AUTO(add_sub_mul) { const SecretKey& sec = g_sec; PublicKey pub; sec.getPublicKey(pub); for (int m1 = -5; m1 < 5; m1++) { for (int m2 = -5; m2 < 5; m2++) { CipherText c1, c2, c3; pub.enc(c1, m1); pub.enc(c2, m2); add(c3, c1, c2); CYBOZU_TEST_EQUAL(m1 + m2, sec.dec(c3)); pub.reRand(c3); CYBOZU_TEST_EQUAL(m1 + m2, sec.dec(c3)); sub(c3, c1, c2); CYBOZU_TEST_EQUAL(m1 - m2, sec.dec(c3)); mul(c3, c1, 5); CYBOZU_TEST_EQUAL(m1 * 5, sec.dec(c3)); mul(c3, c1, -123); CYBOZU_TEST_EQUAL(m1 * -123, sec.dec(c3)); mul(c3, c1, c2); CYBOZU_TEST_EQUAL(m1 * m2, sec.dec(c3)); pub.reRand(c3); CYBOZU_TEST_EQUAL(m1 * m2, sec.dec(c3)); CipherText::mul(c3, c3, -25); CYBOZU_TEST_EQUAL(m1 * m2 * -25, sec.dec(c3)); pub.enc(c1, m1, true); CYBOZU_TEST_EQUAL(m1, sec.dec(c1)); pub.enc(c2, m2, true); add(c3, c1, c2); CYBOZU_TEST_EQUAL(m1 + m2, sec.dec(c3)); } } } CYBOZU_TEST_AUTO(largeEnc) { const SecretKey& sec = g_sec; PublicKey pub; sec.getPublicKey(pub); Fr x; x.setRand(); CipherTextG1 c1, c2; pub.enc(c1, x); const int64_t m = 123; pub.enc(c2, x + m); sub(c1, c1, c2); CYBOZU_TEST_EQUAL(sec.dec(c1), -m); pub.enc(c1, 0); mul(c1, c1, x); CYBOZU_TEST_ASSERT(sec.isZero(c1)); pub.enc(c1, 1); mul(c1, c1, x); CYBOZU_TEST_ASSERT(!sec.isZero(c1)); } CYBOZU_TEST_AUTO(add_mul_add_sub) { const SecretKey& sec = g_sec; PublicKey pub; sec.getPublicKey(pub); int m[8] = { 1, -2, 3, 4, -5, 6, -7, 8 }; CipherText c[8]; for (int i = 0; i < 8; i++) { pub.enc(c[i], m[i]); CYBOZU_TEST_EQUAL(sec.dec(c[i]), m[i]); CYBOZU_TEST_ASSERT(!c[i].isMultiplied()); CipherText mc; pub.convert(mc, c[i]); CYBOZU_TEST_ASSERT(mc.isMultiplied()); CYBOZU_TEST_EQUAL(sec.dec(mc), m[i]); } int ok1 = (m[0] + m[1]) * (m[2] + m[3]); int ok2 = (m[4] + m[5]) * (m[6] + m[7]); int ok = ok1 + ok2; for (int i = 0; i < 4; i++) { c[i * 2].add(c[i * 2 + 1]); CYBOZU_TEST_EQUAL(sec.dec(c[i * 2]), m[i * 2] + m[i * 2 + 1]); } c[0].mul(c[2]); CYBOZU_TEST_EQUAL(sec.dec(c[0]), ok1); c[4].mul(c[6]); CYBOZU_TEST_EQUAL(sec.dec(c[4]), ok2); c[0].add(c[4]); CYBOZU_TEST_EQUAL(sec.dec(c[0]), ok); c[0].sub(c[4]); CYBOZU_TEST_EQUAL(sec.dec(c[0]), ok1); } CYBOZU_TEST_AUTO(finalExp) { const SecretKey& sec = g_sec; PublicKey pub; sec.getPublicKey(pub); const int64_t m11 = 5; const int64_t m12 = 3; const int64_t m21 = -2; const int64_t m22 = 9; CipherTextG1 c11, c12; CipherTextG2 c21, c22; CipherTextGT ct1, ct2, ct; pub.enc(c11, m11); pub.enc(c12, m12); pub.enc(c21, m21); pub.enc(c22, m22); CipherTextGT::mulML(ct1, c11, c21); CipherTextGT::finalExp(ct, ct1); CYBOZU_TEST_EQUAL(sec.dec(ct), m11 * m21); CipherTextGT::mulML(ct2, c12, c22); CipherTextGT::finalExp(ct, ct2); CYBOZU_TEST_EQUAL(sec.dec(ct), m12 * m22); CipherTextGT::add(ct1, ct1, ct2); CipherTextGT::finalExp(ct1, ct1); CYBOZU_TEST_EQUAL(sec.dec(ct1), (m11 * m21) + (m12 * m22)); } CYBOZU_TEST_AUTO(innerProduct) { const SecretKey& sec = g_sec; PublicKey pub; sec.getPublicKey(pub); cybozu::XorShift rg; const size_t n = 1000; std::vector<int> v1, v2; std::vector<CipherText> c1, c2; v1.resize(n); v2.resize(n); c1.resize(n); c2.resize(n); int innerProduct = 0; for (size_t i = 0; i < n; i++) { v1[i] = rg() % 2; v2[i] = rg() % 2; innerProduct += v1[i] * v2[i]; pub.enc(c1[i], v1[i]); pub.enc(c2[i], v2[i]); } CipherText c, t; CipherText::mul(c, c1[0], c2[0]); for (size_t i = 1; i < n; i++) { CipherText::mul(t, c1[i], c2[i]); c.add(t); } CYBOZU_TEST_EQUAL(innerProduct, sec.dec(c)); } template<class T> T testIo(const T& x) { std::stringstream ss; ss << x; T y; ss >> y; CYBOZU_TEST_EQUAL(x, y); return y; } CYBOZU_TEST_AUTO(io) { setRangeForDLP(100); int64_t m; for (int i = 0; i < 2; i++) { if (i == 1) { Fp::setIoMode(mcl::IoSerialize); G1::setIoMode(mcl::IoSerialize); } SecretKey sec; sec.setByCSPRNG(); testIo(sec); PublicKey pub; sec.getPublicKey(pub); testIo(pub); CipherTextG1 g1; pub.enc(g1, 3); m = sec.dec(testIo(g1)); CYBOZU_TEST_EQUAL(m, 3); CipherTextG2 g2; pub.enc(g2, 5); testIo(g2); CipherTextA ca; pub.enc(ca, -4); m = sec.dec(testIo(ca)); CYBOZU_TEST_EQUAL(m, -4); CipherTextGT ct; CipherTextGT::mul(ct, g1, g2); m = sec.dec(testIo(ct)); CYBOZU_TEST_EQUAL(m, 15); } } #ifndef PAPER CYBOZU_TEST_AUTO(bench) { const SecretKey& sec = g_sec; PublicKey pub; sec.getPublicKey(pub); CipherText c1, c2, c3; CYBOZU_BENCH("enc", pub.enc, c1, 5); pub.enc(c2, 4); CYBOZU_BENCH("add", c1.add, c2); CYBOZU_BENCH("mul", CipherText::mul, c3, c1, c2); pub.enc(c1, 5); pub.enc(c2, 4); c1.mul(c2); CYBOZU_BENCH("dec", sec.dec, c1); c2 = c1; CYBOZU_BENCH("add after mul", c1.add, c2); } #endif CYBOZU_TEST_AUTO(saveHash) { mcl::she::local::HashTable<G1> hashTbl1, hashTbl2; hashTbl1.init(SHE::P_, 1234, 123); std::stringstream ss; hashTbl1.save(ss); hashTbl2.load(ss); CYBOZU_TEST_ASSERT(hashTbl1 == hashTbl2); } static inline void putK(double t) { printf("%.2e\n", t * 1e-3); } template<class CT> void decBench(const char *msg, int C, const SecretKey& sec, const PublicKey& pub, int64_t (SecretKey::*dec)(const CT& c, bool *pok) const = &SecretKey::dec) { int64_t begin = 1 << 20; int64_t end = 1LL << 32; while (begin < end) { CT c; int64_t x = begin - 1; pub.enc(c, x); printf("m=%08x ", (uint32_t)x); CYBOZU_BENCH_C(msg, C, (sec.*dec), c, 0); CYBOZU_TEST_EQUAL((sec.*dec)(c, 0), x); begin *= 2; } int64_t mTbl[] = { -0x80000003ll, 0x80000000ll, 0x80000005ll }; for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(mTbl); i++) { int64_t m = mTbl[i]; CT c; pub.enc(c, m); CYBOZU_TEST_EQUAL((sec.*dec)(c, 0), m); } } #if !defined(PAPER) && defined(NDEBUG) CYBOZU_TEST_AUTO(hashBench) { SecretKey& sec = g_sec; sec.setByCSPRNG(); const int C = 500; const size_t hashSize = 1u << 21; clock_t begin = clock(), end; setRangeForG1DLP(hashSize); end = clock(); printf("init G1 DLP %f\n", double(end - begin) / CLOCKS_PER_SEC); begin = end; setRangeForG2DLP(hashSize); end = clock(); printf("init G2 DLP %f\n", double(end - begin) / CLOCKS_PER_SEC); begin = end; setRangeForGTDLP(hashSize); end = clock(); printf("init GT DLP %f\n", double(end - begin) / CLOCKS_PER_SEC); PublicKey pub; sec.getPublicKey(pub); PrecomputedPublicKey ppub; ppub.init(pub); puts("Kclk"); cybozu::bench::setPutCallback(putK); decBench<CipherTextG1>("decG1", C, sec, pub); puts(""); decBench<CipherTextG2>("decG2", C, sec, pub); puts(""); decBench<CipherTextGT>("decGT", C, sec, pub); puts(""); decBench<CipherTextG1>("decG1ViaGT", C, sec, pub, &SecretKey::decViaGT); puts(""); decBench<CipherTextG2>("decG2ViaGT", C, sec, pub, &SecretKey::decViaGT); G1 P, P2; G2 Q, Q2; GT e, e2; mpz_class mr; { Fr r; r.setRand(); mr = r.getMpz(); } hashAndMapToG1(P, "abc"); hashAndMapToG2(Q, "abc"); pairing(e, P, Q); P2.clear(); Q2.clear(); e2 = 1; printf("large m\n"); CYBOZU_BENCH_C("G1::add ", C, G1::add, P2, P2, P); CYBOZU_BENCH_C("G1::mul ", C, G1::mul, P, P, mr); CYBOZU_BENCH_C("G2::add ", C, G2::add, Q2, Q2, Q); CYBOZU_BENCH_C("G2::mul ", C, G2::mul, Q, Q, mr); CYBOZU_BENCH_C("GT::mul ", C, GT::mul, e2, e2, e); CYBOZU_BENCH_C("GT::pow ", C, GT::pow, e, e, mr); CYBOZU_BENCH_C("G1window", C, SHE::PhashTbl_.mulByWindowMethod, P2, mr); CYBOZU_BENCH_C("G2window", C, SHE::QhashTbl_.mulByWindowMethod, Q2, mr); CYBOZU_BENCH_C("GTwindow", C, SHE::ePQhashTbl_.mulByWindowMethod, e, mr); #if 1 typedef mcl::GroupMtoA<Fp12> AG; mcl::fp::WindowMethod<AG> wm; wm.init(static_cast<AG&>(e), Fr::getBitSize(), 10); for (int i = 0; i < 100; i++) { GT t1, t2; GT::pow(t1, e, i); wm.mul(static_cast<AG&>(t2), i); CYBOZU_TEST_EQUAL(t1, t2); } // CYBOZU_BENCH_C("GTwindow", C, wm.mul, static_cast<AG&>(e), mr); #endif CYBOZU_BENCH_C("miller ", C, millerLoop, e, P, Q); CYBOZU_BENCH_C("finalExp", C, finalExp, e, e); CYBOZU_BENCH_C("precomML", C, precomputedMillerLoop, e, P, SHE::Qcoeff_); CipherTextG1 c1, c11; CipherTextG2 c2, c21; CipherTextGT ct, ct1; int m = int(hashSize - 1); printf("small m = %d\n", m); CYBOZU_BENCH_C("G1::mul ", C, G1::mul, P, P, m); CYBOZU_BENCH_C("G2::mul ", C, G2::mul, Q, Q, m); CYBOZU_BENCH_C("GT::pow ", C, GT::pow, e, e, m); CYBOZU_BENCH_C("G1window", C, SHE::PhashTbl_.mulByWindowMethod, P2, m); CYBOZU_BENCH_C("G2window", C, SHE::QhashTbl_.mulByWindowMethod, Q2, m); CYBOZU_BENCH_C("GTwindow", C, SHE::ePQhashTbl_.mulByWindowMethod, e, m); // CYBOZU_BENCH_C("GTwindow", C, wm.mul, static_cast<AG&>(e), m); CYBOZU_BENCH_C("encG1 ", C, pub.enc, c1, m); CYBOZU_BENCH_C("encG2 ", C, pub.enc, c2, m); CYBOZU_BENCH_C("encGT ", C, pub.enc, ct, m); CYBOZU_BENCH_C("encG1pre", C, ppub.enc, c1, m); CYBOZU_BENCH_C("encG2pre", C, ppub.enc, c2, m); CYBOZU_BENCH_C("encGTpre", C, ppub.enc, ct, m); CYBOZU_BENCH_C("decG1 ", C, sec.dec, c1); CYBOZU_BENCH_C("decG2 ", C, sec.dec, c2); CYBOZU_BENCH_C("degGT ", C, sec.dec, ct); CYBOZU_BENCH_C("CT:mul ", C, CipherTextGT::mul, ct, c1, c2); CYBOZU_BENCH_C("CT:mulML", C, CipherTextGT::mulML, ct, c1, c2); CYBOZU_BENCH_C("CT:finalExp", C, CipherTextGT::finalExp, ct, ct); c11 = c1; c21 = c2; ct1 = ct; CYBOZU_BENCH_C("addG1 ", C, CipherTextG1::add, c1, c1, c11); CYBOZU_BENCH_C("addG2 ", C, CipherTextG2::add, c2, c2, c21); CYBOZU_BENCH_C("addGT ", C, CipherTextGT::add, ct, ct, ct1); CYBOZU_BENCH_C("reRandG1", C, pub.reRand, c1); CYBOZU_BENCH_C("reRandG2", C, pub.reRand, c2); CYBOZU_BENCH_C("reRandGT", C, pub.reRand, ct); CYBOZU_BENCH_C("reRandG1pre", C, ppub.reRand, c1); CYBOZU_BENCH_C("reRandG2pre", C, ppub.reRand, c2); CYBOZU_BENCH_C("reRandGTpre", C, ppub.reRand, ct); CYBOZU_BENCH_C("mulG1 ", C, CipherTextG1::mul, c1, c1, m); CYBOZU_BENCH_C("mulG2 ", C, CipherTextG2::mul, c2, c2, m); CYBOZU_BENCH_C("mulGT ", C, CipherTextGT::mul, ct, ct, m); CYBOZU_BENCH_C("convG1toGT", C, pub.convert, ct, c1); CYBOZU_BENCH_C("convG2toGT", C, pub.convert, ct, c2); } #endif CYBOZU_TEST_AUTO(liftedElGamal) { const size_t hashSize = 1024; const mcl::EcParam& param = mcl::ecparam::secp256k1; initG1only(param, hashSize); const size_t byteSize = (param.bitSize + 7) / 8; SecretKey sec; sec.setByCSPRNG(); PublicKey pub; sec.getPublicKey(pub); CipherTextG1 c1, c2, c3; int m1 = 12, m2 = 34; pub.enc(c1, m1); pub.enc(c2, m2); CYBOZU_TEST_EQUAL(sec.dec(c1), m1); CYBOZU_TEST_EQUAL(sec.dec(c2), m2); add(c3, c1, c2); CYBOZU_TEST_EQUAL(sec.dec(c3), m1 + m2); neg(c1, c2); CYBOZU_TEST_EQUAL(sec.dec(c1), -m2); mul(c1, c2, m1); CYBOZU_TEST_EQUAL(sec.dec(c1), m2 * m1); char buf[1024]; size_t n = sec.serialize(buf, sizeof(buf)); CYBOZU_TEST_EQUAL(n, byteSize); SecretKey sec2; n = sec2.deserialize(buf, n); CYBOZU_TEST_EQUAL(n, byteSize); CYBOZU_TEST_EQUAL(sec, sec2); n = pub.serialize(buf, sizeof(buf)); CYBOZU_TEST_EQUAL(n, byteSize + 1); // +1 is for sign of y PublicKey pub2; n = pub2.deserialize(buf, n); CYBOZU_TEST_EQUAL(n, byteSize + 1); CYBOZU_TEST_EQUAL(pub, pub2); PublicKey pub3; sec2.getPublicKey(pub3); CYBOZU_TEST_EQUAL(pub, pub3); }
/********************************************************************** * File: points.cpp (Formerly coords.c) * Description: Member functions for coordinate classes. * Author: Ray Smith * Created: Fri Mar 15 08:58:17 GMT 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifdef _MSC_VER #define _USE_MATH_DEFINES #endif // _MSC_VER #include <algorithm> #include <cstdlib> #include "helpers.h" #include "serialis.h" #include "points.h" ELISTIZE (ICOORDELT) //turn to list bool FCOORD::normalise() { //Convert to unit vec float len = length (); if (len < 0.0000000001) { return false; } xcoord /= len; ycoord /= len; return true; } // Set from the given x,y, shrinking the vector to fit if needed. void ICOORD::set_with_shrink(int x, int y) { // Fit the vector into an ICOORD, which is 16 bit. int factor = 1; int max_extent = std::max(abs(x), abs(y)); if (max_extent > INT16_MAX) factor = max_extent / INT16_MAX + 1; xcoord = x / factor; ycoord = y / factor; } // The fortran/basic sgn function returns -1, 0, 1 if x < 0, x == 0, x > 0 // respectively. static int sign(int x) { if (x < 0) return -1; else return x > 0 ? 1 : 0; } // Writes to the given file. Returns false in case of error. bool ICOORD::Serialize(FILE* fp) const { return tesseract::Serialize(fp, &xcoord) && tesseract::Serialize(fp, &ycoord); } // Reads from the given file. Returns false in case of error. // If swap is true, assumes a big/little-endian swap is needed. bool ICOORD::DeSerialize(bool swap, FILE* fp) { if (!tesseract::DeSerialize(fp, &xcoord)) return false; if (!tesseract::DeSerialize(fp, &ycoord)) return false; if (swap) { ReverseN(&xcoord, sizeof(xcoord)); ReverseN(&ycoord, sizeof(ycoord)); } return true; } // Setup for iterating over the pixels in a vector by the well-known // Bresenham rendering algorithm. // Starting with major/2 in the accumulator, on each step add major_step, // and then add minor to the accumulator. When the accumulator >= major // subtract major and step a minor step. void ICOORD::setup_render(ICOORD* major_step, ICOORD* minor_step, int* major, int* minor) const { int abs_x = abs(xcoord); int abs_y = abs(ycoord); if (abs_x >= abs_y) { // X-direction is major. major_step->xcoord = sign(xcoord); major_step->ycoord = 0; minor_step->xcoord = 0; minor_step->ycoord = sign(ycoord); *major = abs_x; *minor = abs_y; } else { // Y-direction is major. major_step->xcoord = 0; major_step->ycoord = sign(ycoord); minor_step->xcoord = sign(xcoord); minor_step->ycoord = 0; *major = abs_y; *minor = abs_x; } } // Returns the standard feature direction corresponding to this. // See binary_angle_plus_pi below for a description of the direction. uint8_t FCOORD::to_direction() const { return binary_angle_plus_pi(angle()); } // Sets this with a unit vector in the given standard feature direction. void FCOORD::from_direction(uint8_t direction) { double radians = angle_from_direction(direction); xcoord = cos(radians); ycoord = sin(radians); } // Converts an angle in radians (from ICOORD::angle or FCOORD::angle) to a // standard feature direction as an unsigned angle in 256ths of a circle // measured anticlockwise from (-1, 0). uint8_t FCOORD::binary_angle_plus_pi(double radians) { return Modulo(IntCastRounded((radians + M_PI) * 128.0 / M_PI), 256); } // Inverse of binary_angle_plus_pi returns an angle in radians for the // given standard feature direction. double FCOORD::angle_from_direction(uint8_t direction) { return direction * M_PI / 128.0 - M_PI; } // Returns the point on the given line nearest to this, ie the point such // that the vector point->this is perpendicular to the line. // The line is defined as a line_point and a dir_vector for its direction. FCOORD FCOORD::nearest_pt_on_line(const FCOORD& line_point, const FCOORD& dir_vector) const { FCOORD point_vector(*this - line_point); // The dot product (%) is |dir_vector||point_vector|cos theta, so dividing by // the square of the length of dir_vector gives us the fraction of dir_vector // to add to line1 to get the appropriate point, so // result = line1 + lambda dir_vector. double lambda = point_vector % dir_vector / dir_vector.sqlength(); return line_point + (dir_vector * lambda); }
#ifndef BUILDING_NODE_EXTENSION #define BUILDING_NODE_EXTENSION #endif #include "MediaStream.h" #include <future> // NOLINT #include "lib/json.hpp" #include "ThreadPool.h" using v8::HandleScope; using v8::Function; using v8::FunctionTemplate; using v8::Local; using v8::Persistent; using v8::Exception; using v8::Value; using json = nlohmann::json; DEFINE_LOGGER(MediaStream, "ErizoAPI.MediaStream"); StatCallWorker::StatCallWorker(Nan::Callback *callback, std::weak_ptr<erizo::MediaStream> weak_stream) : Nan::AsyncWorker{callback}, weak_stream_{weak_stream}, stat_{""} { } void StatCallWorker::Execute() { std::promise<std::string> stat_promise; std::future<std::string> stat_future = stat_promise.get_future(); if (auto stream = weak_stream_.lock()) { stream->getJSONStats([&stat_promise] (std::string stats) { stat_promise.set_value(stats); }); } else { stat_promise.set_value(std::string("{}")); } stat_future.wait(); stat_ = stat_future.get(); } void StatCallWorker::HandleOKCallback() { Local<Value> argv[] = { Nan::New<v8::String>(stat_).ToLocalChecked() }; Nan::AsyncResource resource("erizo::addon.statCall"); callback->Call(1, argv, &resource); } void destroyAsyncHandle(uv_handle_t *handle) { delete handle; } Nan::Persistent<Function> MediaStream::constructor; MediaStream::MediaStream() : closed_{false}, id_{"undefined"} { async_stats_ = new uv_async_t; async_event_ = new uv_async_t; close_future_async_ = new uv_async_t; uv_async_init(uv_default_loop(), async_stats_, &MediaStream::statsCallback); uv_async_init(uv_default_loop(), async_event_, &MediaStream::eventCallback); uv_async_init(uv_default_loop(), close_future_async_, &MediaStream::closePromiseResolver); } MediaStream::~MediaStream() { boost::mutex::scoped_lock lock(mutex); closeEvents(); ELOG_DEBUG("%s, message: Destroyed", toLog()); } void MediaStream::closeEvents() { has_stats_callback_ = false; has_event_callback_ = false; if (!uv_is_closing(reinterpret_cast<uv_handle_t*>(async_stats_))) { ELOG_DEBUG("%s, message: Closing Stats handle", toLog()); uv_close(reinterpret_cast<uv_handle_t*>(async_stats_), destroyAsyncHandle); } async_stats_ = nullptr; if (!uv_is_closing(reinterpret_cast<uv_handle_t*>(async_event_))) { ELOG_DEBUG("%s, message: Closing MediaStreamEvent handle", toLog()); uv_close(reinterpret_cast<uv_handle_t*>(async_event_), destroyAsyncHandle); } async_event_ = nullptr; if (!uv_is_closing(reinterpret_cast<uv_handle_t*>(close_future_async_))) { ELOG_DEBUG("%s, message: Closing future handle", toLog()); uv_close(reinterpret_cast<uv_handle_t*>(close_future_async_), destroyAsyncHandle); } close_future_async_ = nullptr; } boost::future<void> MediaStream::close() { auto close_promise = std::make_shared<boost::promise<void>>(); ELOG_DEBUG("%s, message: Trying to close", toLog()); if (closed_) { ELOG_DEBUG("%s, message: Already closed", toLog()); close_promise->set_value(); return close_promise->get_future(); } ELOG_DEBUG("%s, message: Closing", toLog()); closed_ = true; if (me) { me->setMediaStreamStatsListener(nullptr); me->setMediaStreamEventListener(nullptr); me->close().then([this, close_promise] (boost::future<void>) { me.reset(); close_promise->set_value(); }); } else { close_promise->set_value(); } ELOG_DEBUG("%s, message: Closed", toLog()); return close_promise->get_future(); } std::string MediaStream::toLog() { return "id: " + id_; } void MediaStream::computePromiseTimes(erizo::time_point promise_start, erizo::time_point promise_resolved, erizo::time_point promise_notified) { promise_durations_.add(promise_resolved - promise_start); promise_delays_.add(promise_notified - promise_resolved); } NAN_MODULE_INIT(MediaStream::Init) { // Prepare constructor template Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New); tpl->SetClassName(Nan::New("MediaStream").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Prototype Nan::SetPrototypeMethod(tpl, "close", close); Nan::SetPrototypeMethod(tpl, "configure", configure); Nan::SetPrototypeMethod(tpl, "setAudioReceiver", setAudioReceiver); Nan::SetPrototypeMethod(tpl, "setVideoReceiver", setVideoReceiver); Nan::SetPrototypeMethod(tpl, "getCurrentState", getCurrentState); Nan::SetPrototypeMethod(tpl, "generatePLIPacket", generatePLIPacket); Nan::SetPrototypeMethod(tpl, "getStats", getStats); Nan::SetPrototypeMethod(tpl, "getPeriodicStats", getPeriodicStats); Nan::SetPrototypeMethod(tpl, "setFeedbackReports", setFeedbackReports); Nan::SetPrototypeMethod(tpl, "setSlideShowMode", setSlideShowMode); Nan::SetPrototypeMethod(tpl, "muteStream", muteStream); Nan::SetPrototypeMethod(tpl, "setMaxVideoBW", setMaxVideoBW); Nan::SetPrototypeMethod(tpl, "setQualityLayer", setQualityLayer); Nan::SetPrototypeMethod(tpl, "enableSlideShowBelowSpatialLayer", enableSlideShowBelowSpatialLayer); Nan::SetPrototypeMethod(tpl, "onMediaStreamEvent", onMediaStreamEvent); Nan::SetPrototypeMethod(tpl, "setVideoConstraints", setVideoConstraints); Nan::SetPrototypeMethod(tpl, "setMetadata", setMetadata); Nan::SetPrototypeMethod(tpl, "setPeriodicKeyframeRequests", setPeriodicKeyframeRequests); Nan::SetPrototypeMethod(tpl, "hasPeriodicKeyframeRequests", hasPeriodicKeyframeRequests); Nan::SetPrototypeMethod(tpl, "enableHandler", enableHandler); Nan::SetPrototypeMethod(tpl, "disableHandler", disableHandler); Nan::SetPrototypeMethod(tpl, "getDurationDistribution", getDurationDistribution); Nan::SetPrototypeMethod(tpl, "getDelayDistribution", getDelayDistribution); Nan::SetPrototypeMethod(tpl, "resetStats", resetStats); constructor.Reset(Nan::GetFunction(tpl).ToLocalChecked()); Nan::Set(target, Nan::New("MediaStream").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked()); } NAN_METHOD(MediaStream::New) { if (info.Length() < 3) { Nan::ThrowError("Wrong number of arguments"); } if (info.IsConstructCall()) { // Invoked as a constructor with 'new MediaStream()' ThreadPool* thread_pool = Nan::ObjectWrap::Unwrap<ThreadPool>(Nan::To<v8::Object>(info[0]).ToLocalChecked()); WebRtcConnection* connection = Nan::ObjectWrap::Unwrap<WebRtcConnection>(Nan::To<v8::Object>(info[1]).ToLocalChecked()); std::shared_ptr<erizo::WebRtcConnection> wrtc = connection->me; Nan::Utf8String paramId(Nan::To<v8::String>(info[2]).ToLocalChecked()); std::string wrtc_id = std::string(*paramId); Nan::Utf8String paramLabel(Nan::To<v8::String>(info[3]).ToLocalChecked()); std::string stream_label = std::string(*paramLabel); bool is_publisher = Nan::To<bool>(info[5]).FromJust(); int session_version = Nan::To<int>(info[6]).FromJust(); std::shared_ptr<erizo::Worker> worker = thread_pool->me->getLessUsedWorker(); MediaStream* obj = new MediaStream(); obj->me = std::make_shared<erizo::MediaStream>(worker, wrtc, wrtc_id, stream_label, is_publisher, session_version); obj->me->init(); obj->msink = obj->me; obj->id_ = wrtc_id; obj->label_ = stream_label; ELOG_DEBUG("%s, message: Created", obj->toLog()); obj->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } else { // TODO(pedro) Check what happens here } } NAN_METHOD(MediaStream::close) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); v8::Local<v8::Promise::Resolver> resolver = v8::Promise::Resolver::New(Nan::GetCurrentContext()).ToLocalChecked(); Nan::Persistent<v8::Promise::Resolver> *persistent = new Nan::Persistent<v8::Promise::Resolver>(resolver); obj->Ref(); erizo::time_point promise_start = erizo::clock::now(); obj->close().then( [persistent, obj, promise_start] (boost::future<void>) { ELOG_DEBUG("%s, MediaStream Close is finished, resolving promise", obj->toLog()); obj->notifyFuture(persistent, promise_start); }); info.GetReturnValue().Set(resolver->GetPromise()); } NAN_METHOD(MediaStream::configure) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); std::shared_ptr<erizo::MediaStream> me = obj->me; if (!me || obj->closed_) { return; } bool force = info.Length() > 0 ? Nan::To<bool>(info[0]).FromJust() : false; bool r = me->configure(force); info.GetReturnValue().Set(Nan::New(r)); } NAN_METHOD(MediaStream::setSlideShowMode) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); std::shared_ptr<erizo::MediaStream> me = obj->me; if (!me || obj->closed_) { return; } bool v = Nan::To<bool>(info[0]).FromJust(); me->setSlideShowMode(v); info.GetReturnValue().Set(Nan::New(v)); } NAN_METHOD(MediaStream::muteStream) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); std::shared_ptr<erizo::MediaStream> me = obj->me; if (!me || obj->closed_) { return; } bool mute_video = Nan::To<bool>(info[0]).FromJust(); bool mute_audio = Nan::To<bool>(info[1]).FromJust(); me->muteStream(mute_video, mute_audio); } NAN_METHOD(MediaStream::setMaxVideoBW) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); std::shared_ptr<erizo::MediaStream> me = obj->me; if (!me || obj->closed_) { return; } int max_video_bw = Nan::To<int>(info[0]).FromJust(); me->setMaxVideoBW(max_video_bw); } NAN_METHOD(MediaStream::setVideoConstraints) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); std::shared_ptr<erizo::MediaStream> me = obj->me; if (!me || obj->closed_) { return; } int max_video_width = Nan::To<int>(info[0]).FromJust(); int max_video_height = Nan::To<int>(info[1]).FromJust(); int max_video_frame_rate = Nan::To<int>(info[2]).FromJust(); me->setVideoConstraints(max_video_width, max_video_height, max_video_frame_rate); } NAN_METHOD(MediaStream::setMetadata) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); std::shared_ptr<erizo::MediaStream> me = obj->me; if (!me || obj->closed_) { return; } Nan::Utf8String json_param(Nan::To<v8::String>(info[0]).ToLocalChecked()); std::string metadata_string = std::string(*json_param); json metadata_json = json::parse(metadata_string); std::map<std::string, std::string> metadata; for (json::iterator item = metadata_json.begin(); item != metadata_json.end(); ++item) { std::string value = item.value().dump(); if (item.value().is_object()) { value = "[object]"; } if (item.value().is_string()) { value = item.value(); } metadata[item.key()] = value; } me->setMetadata(metadata); info.GetReturnValue().Set(Nan::New(true)); } NAN_METHOD(MediaStream::getCurrentState) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); std::shared_ptr<erizo::MediaStream> me = obj->me; if (!me || obj->closed_) { return; } int state = me->getCurrentState(); info.GetReturnValue().Set(Nan::New(state)); } NAN_METHOD(MediaStream::setAudioReceiver) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); std::shared_ptr<erizo::MediaStream> me = obj->me; if (!me || obj->closed_) { return; } MediaSink* param = Nan::ObjectWrap::Unwrap<MediaSink>(Nan::To<v8::Object>(info[0]).ToLocalChecked()); me->setAudioSink(param->msink); me->setEventSink(param->msink); } NAN_METHOD(MediaStream::setVideoReceiver) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); std::shared_ptr<erizo::MediaStream> me = obj->me; if (!me || obj->closed_) { return; } MediaSink* param = Nan::ObjectWrap::Unwrap<MediaSink>(Nan::To<v8::Object>(info[0]).ToLocalChecked()); me->setVideoSink(param->msink); me->setEventSink(param->msink); } NAN_METHOD(MediaStream::generatePLIPacket) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); std::shared_ptr<erizo::MediaStream> me = obj->me; if (!me || obj->closed_) { return; } me->sendPLI(); } NAN_METHOD(MediaStream::enableHandler) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); std::shared_ptr<erizo::MediaStream> me = obj->me; if (!me || obj->closed_) { return; } Nan::Utf8String param(Nan::To<v8::String>(info[0]).ToLocalChecked()); std::string name = std::string(*param); me->enableHandler(name); return; } NAN_METHOD(MediaStream::disableHandler) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); std::shared_ptr<erizo::MediaStream> me = obj->me; if (!me || obj->closed_) { return; } Nan::Utf8String param(Nan::To<v8::String>(info[0]).ToLocalChecked()); std::string name = std::string(*param); me->disableHandler(name); } NAN_METHOD(MediaStream::setQualityLayer) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); std::shared_ptr<erizo::MediaStream> me = obj->me; if (!me || obj->closed_) { return; } int spatial_layer = Nan::To<int>(info[0]).FromJust(); int temporal_layer = Nan::To<int>(info[1]).FromJust(); me->setQualityLayer(spatial_layer, temporal_layer); } NAN_METHOD(MediaStream::enableSlideShowBelowSpatialLayer) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); std::shared_ptr<erizo::MediaStream> me = obj->me; if (!me || obj->closed_) { return; } bool enabled = Nan::To<bool>(info[0]).FromJust(); int spatial_layer = Nan::To<int>(info[1]).FromJust(); me->enableSlideShowBelowSpatialLayer(enabled, spatial_layer); } NAN_METHOD(MediaStream::setPeriodicKeyframeRequests) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); std::shared_ptr<erizo::MediaStream> me = obj->me; if (!me || obj->closed_) { return; } bool activated = Nan::To<bool>(info[0]).FromJust(); int interval = 0; if (info.Length() > 1) { interval = Nan::To<int>(info[1]).FromJust(); } me->setPeriodicKeyframeRequests(activated, interval); } NAN_METHOD(MediaStream::hasPeriodicKeyframeRequests) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); std::shared_ptr<erizo::MediaStream> me = obj->me; if (!me || obj->closed_) { return; } bool has_periodic_requests = me->isRequestingPeriodicKeyframes(); info.GetReturnValue().Set(Nan::New(has_periodic_requests)); } NAN_METHOD(MediaStream::getDurationDistribution) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); PromiseDurationDistribution duration_distribution = obj->promise_durations_; v8::Local<v8::Array> array = Nan::New<v8::Array>(5); Nan::Set(array, 0, Nan::New(duration_distribution.duration_0_10_ms)); Nan::Set(array, 1, Nan::New(duration_distribution.duration_10_50_ms)); Nan::Set(array, 2, Nan::New(duration_distribution.duration_50_100_ms)); Nan::Set(array, 3, Nan::New(duration_distribution.duration_100_1000_ms)); Nan::Set(array, 4, Nan::New(duration_distribution.duration_1000_ms)); info.GetReturnValue().Set(array); } NAN_METHOD(MediaStream::getDelayDistribution) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); PromiseDurationDistribution duration_distribution = obj->promise_delays_; v8::Local<v8::Array> array = Nan::New<v8::Array>(5); Nan::Set(array, 0, Nan::New(duration_distribution.duration_0_10_ms)); Nan::Set(array, 1, Nan::New(duration_distribution.duration_10_50_ms)); Nan::Set(array, 2, Nan::New(duration_distribution.duration_50_100_ms)); Nan::Set(array, 3, Nan::New(duration_distribution.duration_100_1000_ms)); Nan::Set(array, 4, Nan::New(duration_distribution.duration_1000_ms)); info.GetReturnValue().Set(array); } NAN_METHOD(MediaStream::resetStats) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); obj->promise_durations_.reset(); obj->promise_delays_.reset(); } NAN_METHOD(MediaStream::getStats) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); Nan::Callback *callback = new Nan::Callback(info[0].As<Function>()); if (!obj->me || info.Length() != 1 || obj->closed_) { Local<Value> argv[] = { Nan::New<v8::String>("{}").ToLocalChecked() }; Nan::Call(*callback, 1, argv); return; } AsyncQueueWorker(new StatCallWorker(callback, obj->me)); } NAN_METHOD(MediaStream::getPeriodicStats) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); if (!obj->me || info.Length() != 1 || obj->closed_) { return; } obj->me->setMediaStreamStatsListener(obj); obj->has_stats_callback_ = true; obj->stats_callback_ = new Nan::Callback(info[0].As<Function>()); } NAN_METHOD(MediaStream::setFeedbackReports) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); std::shared_ptr<erizo::MediaStream> me = obj->me; if (!me || obj->closed_) { return; } bool v = Nan::To<bool>(info[0]).FromJust(); int fbreps = Nan::To<int>(info[1]).FromJust(); // From bps to Kbps me->setFeedbackReports(v, fbreps); } NAN_METHOD(MediaStream::onMediaStreamEvent) { MediaStream* obj = Nan::ObjectWrap::Unwrap<MediaStream>(info.Holder()); std::shared_ptr<erizo::MediaStream> me = obj->me; if (!me || obj->closed_) { return; } me ->setMediaStreamEventListener(obj); obj->has_event_callback_ = true; obj->event_callback_ = new Nan::Callback(info[0].As<Function>()); } void MediaStream::notifyStats(const std::string& message) { boost::mutex::scoped_lock lock(mutex); if (!has_stats_callback_) { return; } if (!async_stats_) { return; } stats_messages.push(message); async_stats_->data = this; uv_async_send(async_stats_); } void MediaStream::notifyMediaStreamEvent(const std::string& type, const std::string& message) { boost::mutex::scoped_lock lock(mutex); if (!has_event_callback_) { return; } if (!async_event_) { return; } event_messages.push(std::make_pair(type, message)); async_event_->data = this; uv_async_send(async_event_); } NAUV_WORK_CB(MediaStream::statsCallback) { Nan::HandleScope scope; MediaStream* obj = reinterpret_cast<MediaStream*>(async->data); if (!obj || !obj->me || obj->closed_) { return; } boost::mutex::scoped_lock lock(obj->mutex); if (obj->has_stats_callback_) { while (!obj->stats_messages.empty()) { Local<Value> args[] = {Nan::New(obj->stats_messages.front().c_str()).ToLocalChecked()}; Nan::AsyncResource resource("erizo::addon.stream.statsCallback"); resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), obj->stats_callback_->GetFunction(), 1, args); obj->stats_messages.pop(); } } } NAUV_WORK_CB(MediaStream::eventCallback) { Nan::HandleScope scope; MediaStream* obj = reinterpret_cast<MediaStream*>(async->data); if (!obj || !obj->me || obj->closed_) { return; } boost::mutex::scoped_lock lock(obj->mutex); ELOG_DEBUG("%s, message: eventsCallback", obj->toLog()); if (obj->has_event_callback_) { while (!obj->event_messages.empty()) { Local<Value> args[] = {Nan::New(obj->event_messages.front().first.c_str()).ToLocalChecked(), Nan::New(obj->event_messages.front().second.c_str()).ToLocalChecked()}; Nan::AsyncResource resource("erizo::addon.stream.eventCallback"); resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), obj->event_callback_->GetFunction(), 2, args); obj->event_messages.pop(); } } ELOG_DEBUG("%s, message: eventsCallback finished", obj->toLog()); } void MediaStream::notifyFuture(Nan::Persistent<v8::Promise::Resolver> *persistent, erizo::time_point promise_start) { boost::mutex::scoped_lock lock(mutex); if (!close_future_async_) { return; } StreamResultTuple result_tuple(persistent, promise_start, erizo::clock::now()); futures.push(result_tuple); close_future_async_->data = this; uv_async_send(close_future_async_); } NAUV_WORK_CB(MediaStream::closePromiseResolver) { Nan::HandleScope scope; MediaStream* obj = reinterpret_cast<MediaStream*>(async->data); if (!obj) { // closed_ will always be true here return; } boost::mutex::scoped_lock lock(obj->mutex); ELOG_DEBUG("%s, message: closePromiseResolver", obj->toLog()); obj->Ref(); while (!obj->futures.empty()) { auto persistent = std::get<0>(obj->futures.front()); v8::Local<v8::Promise::Resolver> resolver = Nan::New(*persistent); erizo::time_point promise_start = std::get<1>(obj->futures.front()); erizo::time_point promise_resolved = std::get<2>(obj->futures.front()); erizo::time_point promise_notified = erizo::clock::now(); obj->computePromiseTimes(promise_start, promise_resolved, promise_notified); resolver->Resolve(Nan::GetCurrentContext(), Nan::New("").ToLocalChecked()).IsNothing(); persistent->Reset(); delete persistent; obj->futures.pop(); obj->Unref(); v8::Isolate::GetCurrent()->RunMicrotasks(); } obj->closeEvents(); obj->Unref(); ELOG_DEBUG("%s, message: closePromiseResolver finished", obj->toLog()); }
// RUN: %clang_cc1 -fsycl-is-device -triple spir64 -IInputs -emit-llvm %s -o - | FileCheck %s // This test ensures that we don't generate a kernel before we have instantiated // all the kernel declarations, which can change the name of a kernel in the // unnamed kernel case. Previously we would have duplicate manglings of the // below example, because the marking of 'lambda' as a kernel changed the name // of the kernel before it. #include "Inputs/sycl.hpp" int main() { sycl::handler h; auto lambda = []() {}; h.single_task([]() {}); h.single_task(lambda); } // Make sure the kernels are instantiated in the correct order, and named // correctly. // CHECK: define{{.*}}spir_kernel void @_ZTSZ4mainEUlvE0_() // CHECK: define{{.*}}spir_kernel void @_ZTSZ4mainEUlvE_()
// RUN: %clang_cc1 -fsyntax-only -verify %s // RUN: %clang_cc1 -fsyntax-only -verify -std=c++98 %s // RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 %s // A type-parameter defines its identifier to be a type-name (if // declared with class or typename) or template-name (if declared with // template) in the scope of the template declaration. template<typename T> struct X0 { T* value; }; template<template<class T> class Y> struct X1 { Y<int> value; }; // [Note: because of the name lookup rules, a template-parameter that // could be interpreted as either a non-type template-parameter or a // type-parameter (because its identifier is the name of an already // existing class) is taken as a type-parameter. For example, class T { /* ... */ }; // expected-note{{candidate constructor (the implicit copy constructor) not viable}} #if __cplusplus >= 201103L // C++11 or later // expected-note@-2 {{candidate constructor (the implicit move constructor) not viable}} #endif int i; template<class T, T i> struct X2 { void f(T t) { T t1 = i; // template-parameters T and i ::T t2 = ::i; // global namespace members T and i \ // expected-error{{no viable conversion}} } }; namespace PR6831 { namespace NA { struct S; } namespace NB { struct S; } using namespace NA; using namespace NB; template <typename S> void foo(); template <int S> void bar(); template <template<typename> class S> void baz(); }
// Copyright (c) 2012 The Bitcoin developers // Copyright (c) 2013-2014 Dogecoin Developers // Copyright (c) 2013-2014 Team Mooncoin // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <math.h> #include <stdlib.h> #include "bloom.h" #include "main.h" #include "script.h" #define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455 #define LN2 0.6931471805599453094172321214581765680755001343602552 using namespace std; static const unsigned char bit_mask[8] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80}; CBloomFilter::CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweakIn, unsigned char nFlagsIn) : // The ideal size for a bloom filter with a given number of elements and false positive rate is: // - nElements * log(fp rate) / ln(2)^2 // We ignore filter parameters which will create a bloom filter larger than the protocol limits vData(min((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8), // The ideal number of hash functions is filter size * ln(2) / number of elements // Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits // See http://en.wikipedia.org/wiki/Bloom_filter for an explanation of these formulas isFull(false), isEmpty(false), nHashFuncs(min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)), nTweak(nTweakIn), nFlags(nFlagsIn) { } inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const { // 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values. return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8); } void CBloomFilter::insert(const vector<unsigned char>& vKey) { if (isFull) return; for (unsigned int i = 0; i < nHashFuncs; i++) { unsigned int nIndex = Hash(i, vKey); // Sets bit nIndex of vData vData[nIndex >> 3] |= bit_mask[7 & nIndex]; } isEmpty = false; } void CBloomFilter::insert(const COutPoint& outpoint) { CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); stream << outpoint; vector<unsigned char> data(stream.begin(), stream.end()); insert(data); } void CBloomFilter::insert(const uint256& hash) { vector<unsigned char> data(hash.begin(), hash.end()); insert(data); } bool CBloomFilter::contains(const vector<unsigned char>& vKey) const { if (isFull) return true; if (isEmpty) return false; for (unsigned int i = 0; i < nHashFuncs; i++) { unsigned int nIndex = Hash(i, vKey); // Checks bit nIndex of vData if (!(vData[nIndex >> 3] & bit_mask[7 & nIndex])) return false; } return true; } bool CBloomFilter::contains(const COutPoint& outpoint) const { CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); stream << outpoint; vector<unsigned char> data(stream.begin(), stream.end()); return contains(data); } bool CBloomFilter::contains(const uint256& hash) const { vector<unsigned char> data(hash.begin(), hash.end()); return contains(data); } bool CBloomFilter::IsWithinSizeConstraints() const { return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS; } bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx, const uint256& hash) { bool fFound = false; // Match if the filter contains the hash of tx // for finding tx when they appear in a block if (isFull) return true; if (isEmpty) return false; if (contains(hash)) fFound = true; for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; // Match if the filter contains any arbitrary script data element in any scriptPubKey in tx // If this matches, also add the specific output that was matched. // This means clients don't have to update the filter themselves when a new relevant tx // is discovered in order to find spending transactions, which avoids round-tripping and race conditions. CScript::const_iterator pc = txout.scriptPubKey.begin(); vector<unsigned char> data; while (pc < txout.scriptPubKey.end()) { opcodetype opcode; if (!txout.scriptPubKey.GetOp(pc, opcode, data)) break; if (data.size() != 0 && contains(data)) { fFound = true; if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL) insert(COutPoint(hash, i)); else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY) { txnouttype type; vector<vector<unsigned char> > vSolutions; if (Solver(txout.scriptPubKey, type, vSolutions) && (type == TX_PUBKEY || type == TX_MULTISIG)) insert(COutPoint(hash, i)); } break; } } } if (fFound) return true; BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Match if the filter contains an outpoint tx spends if (contains(txin.prevout)) return true; // Match if the filter contains any arbitrary script data element in any scriptSig in tx CScript::const_iterator pc = txin.scriptSig.begin(); vector<unsigned char> data; while (pc < txin.scriptSig.end()) { opcodetype opcode; if (!txin.scriptSig.GetOp(pc, opcode, data)) break; if (data.size() != 0 && contains(data)) return true; } } return false; } void CBloomFilter::UpdateEmptyFull() { bool full = true; bool empty = true; for (unsigned int i = 0; i < vData.size(); i++) { full &= vData[i] == 0xff; empty &= vData[i] == 0; } isFull = full; isEmpty = empty; }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autocomplete/autocomplete_classifier.h" #include "base/auto_reset.h" #include "chrome/browser/autocomplete/autocomplete_controller.h" #include "chrome/browser/autocomplete/autocomplete_input.h" #include "chrome/browser/autocomplete/autocomplete_match.h" #include "chrome/browser/autocomplete/autocomplete_provider.h" #include "googleurl/src/gurl.h" // static const int AutocompleteClassifier::kDefaultOmniboxProviders = AutocompleteProvider::TYPE_BOOKMARK | AutocompleteProvider::TYPE_BUILTIN | AutocompleteProvider::TYPE_HISTORY_CONTENTS | AutocompleteProvider::TYPE_HISTORY_QUICK | AutocompleteProvider::TYPE_HISTORY_URL | AutocompleteProvider::TYPE_KEYWORD | AutocompleteProvider::TYPE_SEARCH | AutocompleteProvider::TYPE_SHORTCUTS | AutocompleteProvider::TYPE_ZERO_SUGGEST; // static const int AutocompleteClassifier::kInstantExtendedOmniboxProviders = AutocompleteProvider::TYPE_BUILTIN | AutocompleteProvider::TYPE_HISTORY_QUICK | AutocompleteProvider::TYPE_HISTORY_URL | AutocompleteProvider::TYPE_KEYWORD | // TODO: remove TYPE_SEARCH once it's no longer needed to pass // the Instant suggestion through via FinalizeInstantQuery. AutocompleteProvider::TYPE_SEARCH | AutocompleteProvider::TYPE_ZERO_SUGGEST; AutocompleteClassifier::AutocompleteClassifier(Profile* profile) : controller_(new AutocompleteController(profile, NULL, kDefaultOmniboxProviders)), inside_classify_(false) { } AutocompleteClassifier::~AutocompleteClassifier() { // We should only reach here after Shutdown() has been called. DCHECK(!controller_.get()); } void AutocompleteClassifier::Classify(const string16& text, const string16& desired_tld, bool prefer_keyword, bool allow_exact_keyword_match, AutocompleteMatch* match, GURL* alternate_nav_url) { DCHECK(!inside_classify_); base::AutoReset<bool> reset(&inside_classify_, true); controller_->Start(AutocompleteInput( text, string16::npos, desired_tld, true, prefer_keyword, allow_exact_keyword_match, AutocompleteInput::BEST_MATCH)); DCHECK(controller_->done()); const AutocompleteResult& result = controller_->result(); if (result.empty()) { if (alternate_nav_url) *alternate_nav_url = GURL(); return; } DCHECK(result.default_match() != result.end()); *match = *result.default_match(); if (alternate_nav_url) *alternate_nav_url = result.alternate_nav_url(); } void AutocompleteClassifier::Shutdown() { controller_.reset(); }
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/panorama/model/CreateApplicationInstanceRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Panorama::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; CreateApplicationInstanceRequest::CreateApplicationInstanceRequest() : m_nameHasBeenSet(false), m_descriptionHasBeenSet(false), m_manifestPayloadHasBeenSet(false), m_manifestOverridesPayloadHasBeenSet(false), m_applicationInstanceIdToReplaceHasBeenSet(false), m_runtimeRoleArnHasBeenSet(false), m_defaultRuntimeContextDeviceHasBeenSet(false), m_tagsHasBeenSet(false) { } Aws::String CreateApplicationInstanceRequest::SerializePayload() const { JsonValue payload; if(m_nameHasBeenSet) { payload.WithString("Name", m_name); } if(m_descriptionHasBeenSet) { payload.WithString("Description", m_description); } if(m_manifestPayloadHasBeenSet) { payload.WithObject("ManifestPayload", m_manifestPayload.Jsonize()); } if(m_manifestOverridesPayloadHasBeenSet) { payload.WithObject("ManifestOverridesPayload", m_manifestOverridesPayload.Jsonize()); } if(m_applicationInstanceIdToReplaceHasBeenSet) { payload.WithString("ApplicationInstanceIdToReplace", m_applicationInstanceIdToReplace); } if(m_runtimeRoleArnHasBeenSet) { payload.WithString("RuntimeRoleArn", m_runtimeRoleArn); } if(m_defaultRuntimeContextDeviceHasBeenSet) { payload.WithString("DefaultRuntimeContextDevice", m_defaultRuntimeContextDevice); } if(m_tagsHasBeenSet) { JsonValue tagsJsonMap; for(auto& tagsItem : m_tags) { tagsJsonMap.WithString(tagsItem.first, tagsItem.second); } payload.WithObject("Tags", std::move(tagsJsonMap)); } return payload.View().WriteReadable(); }
#include <gtest/gtest.h> extern "C" { #include "implement_strstr.h" } TEST(implement_strstr_test, strStr_28_1) { EXPECT_EQ(2, strStr_28_1("hello", "ll")); EXPECT_EQ(-1, strStr_28_1("aaaaa", "bba")); EXPECT_EQ(0, strStr_28_1("", "")); } TEST(implement_strstr_test, strStr_28_2) { EXPECT_EQ(2, strStr_28_2("hello", "ll")); EXPECT_EQ(-1, strStr_28_2("aaaaa", "bba")); EXPECT_EQ(0, strStr_28_2("", "")); }
//@HEADER // ************************************************************************ // // Kokkos v. 2.0 // Copyright (2014) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // Kokkos is licensed under 3-clause BSD terms of use: // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact Christian R. Trott (crtrott@sandia.gov) // // ************************************************************************ //@HEADER #define KOKKOS_IMPL_COMPILING_LIBRARY true #include <Kokkos_Core.hpp> namespace Kokkos { namespace Impl { KOKKOS_IMPL_VIEWCOPY_ETI_INST(double****, LayoutLeft, LayoutRight, OpenMP, int64_t) KOKKOS_IMPL_VIEWCOPY_ETI_INST(double****, LayoutLeft, LayoutLeft, OpenMP, int64_t) KOKKOS_IMPL_VIEWCOPY_ETI_INST(double****, LayoutLeft, LayoutStride, OpenMP, int64_t) KOKKOS_IMPL_VIEWFILL_ETI_INST(double****, LayoutLeft, OpenMP, int64_t) } // namespace Impl } // namespace Kokkos
/* Proposition.cpp (exercise 4.1.4) Description: * */ #include "Proposition.hpp" /////////////////////////// // Constructors/Destructor: /////////////////////////// Proposition::Proposition() noexcept : data() { } Proposition::Proposition(bool input) noexcept : data(input) { } Proposition::Proposition(const std::bitset<1> &input) noexcept : data(input) { } Proposition::Proposition(const Proposition &input) noexcept : data(input.data) { } Proposition::~Proposition() noexcept { } /////////////////////////// // Overloaded Operators: /////////////////////////// Proposition Proposition::operator==(const Proposition &input) const noexcept { return Proposition(this->data == input.data); } Proposition& Proposition::operator!=(const Proposition &input) noexcept { if (this != &input) { this->data[0] != input.data[0]; } return *this; } Proposition Proposition::operator&(const Proposition &input) const noexcept { return Proposition(this->data[0] & input.data[0]); } Proposition Proposition::operator|(const Proposition &input) const noexcept { return Proposition(this->data[0] | input.data[0]); } Proposition Proposition::operator^(const Proposition &input) const noexcept { return Proposition(this->data[0] ^ input.data[0]); } Proposition& Proposition::operator=(const Proposition &input) noexcept { if (this != &input) { data[0] = input.data[0]; } return *this; } Proposition& Proposition::operator=(bool input) noexcept { data[0] = input; return *this; }
#ifndef PYTHONIC_INCLUDE_IO__IO_TEXTIOWRAPPER_FILENO_HPP #define PYTHONIC_INCLUDE_IO__IO_TEXTIOWRAPPER_FILENO_HPP #include "pythonic/include/__builtin__/file/fileno.hpp" PYTHONIC_NS_BEGIN namespace io { namespace _io { namespace TextIOWrapper { USING_FUNCTOR(fileno, __builtin__::file::functor::fileno); } } } PYTHONIC_NS_END #endif
/* USER CODE BEGIN Header */ /* * Project Name: Library for the LM75A temperature sensor by NXP and Texas Instruments. * File: main.c * Description: test file to show/test library functions * Author: Gavin Lyons. * IC: STM32F303 * IDE: STM32cubeIDE C++ * Created DEC 2021 * Description: See URL for full details. * URL: https://github.com/gavinlyonsrepo/STM32_projects */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include <stdint.h> #include <stdbool.h> #include <stdio.h> #include <string.h> /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include <LM75A.h> /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ I2C_HandleTypeDef hi2c1; UART_HandleTypeDef huart2; /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); static void MX_GPIO_Init(void); static void MX_USART2_UART_Init(void); static void MX_I2C1_Init(void); /* USER CODE BEGIN PFP */ // Only needed for LIB_TEST void checkTrueValue(const char* caption, const bool value, const bool expected); const char* getFaultQueueValueString(const FaultQueueValue value); const char* getOsPolarityString(const OsPolarity value); const char* getDeviceModeString(DeviceMode value); void checkFaultQueueValue(const char* caption, const FaultQueueValue value, const FaultQueueValue expected); void checkOsPolarityValue(const char* caption, const OsPolarity value, const OsPolarity expected); void checkDeviceModeValue(const char* caption, const DeviceMode value, const DeviceMode expected); void checkTemperatureResult(const char* caption, const float value); void checkTemperatureValue(const char* caption, const float value, const float expected); /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ LIB_LM75A lm75a(&hi2c1, LM75A_DEFAULT_ADDRESS << 1); char uart_buf[50]; int uart_buf_len; bool testResult = true; #define LIB_BASIC //#define LIB_TEST #ifdef LIB_BASIC bool Temp_type_Celsius = true; //true for Celsius , False for Farenheit bool basic_usage_or_test = true; // true for basic , false for full library test float temperature = 0.0; bool is_shutdown = false; #endif #ifdef LIB_TEST float oldHysterisisTemperature; float oldOsTripTemperature; FaultQueueValue oldFaultQueueValue; OsPolarity oldOsPolarity; DeviceMode oldDeviceMode; float newHysterisisTemperature = 62.0f; float newOsTripTemperature = 59.0f; FaultQueueValue newFaultQueueValue = FaultQueueValue::NUMBER_OF_FAULTS_6; OsPolarity newOsPolarity = OsPolarity::OS_POLARITY_ACTIVEHIGH; DeviceMode newDeviceMode = DeviceMode::DEVICE_MODE_INTERRUPT; #endif /* USER CODE END 0 */ /** * @brief The application entry point. * @retval int */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); MX_USART2_UART_Init(); MX_I2C1_Init(); /* USER CODE BEGIN 2 */ uart_buf_len = sprintf(uart_buf, "\nLM75A Start\r\n"); HAL_UART_Transmit(&huart2, (uint8_t*) uart_buf, uart_buf_len, 100); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { #ifdef LIB_BASIC //Celsius if (Temp_type_Celsius == true) { temperature = lm75a.getTemperature(); temperature *= 100; uart_buf_len = sprintf(uart_buf, "\nTemperature : %u.%u *C \r\n", ((unsigned int) temperature / 100), ((unsigned int) temperature % 100)); HAL_UART_Transmit(&huart2, (uint8_t*) uart_buf, uart_buf_len, 100); } else { //Farenheit temperature = lm75a.getTemperatureInFarenheit(); temperature *= 1000; uart_buf_len = sprintf(uart_buf, "\nTemperature : %u.%u *F \r\n", ((unsigned int) temperature / 1000), ((unsigned int) temperature % 100)); HAL_UART_Transmit(&huart2, (uint8_t*) uart_buf, uart_buf_len, 100); } // Hysteris temperature = lm75a.getHysterisisTemperature(); temperature *= 100; uart_buf_len = sprintf(uart_buf, "Hysteris temperature: %u.%u *C \r\n", ((unsigned int) temperature / 100), ((unsigned int) temperature % 100)); HAL_UART_Transmit(&huart2, (uint8_t*) uart_buf, uart_buf_len, 100); // OS trip temperature temperature = lm75a.getOSTripTemperature(); temperature *= 100; uart_buf_len = sprintf(uart_buf, "OS trip temperature: %u.%u *C \r\n", ((unsigned int) temperature / 100), ((unsigned int) temperature % 100)); HAL_UART_Transmit(&huart2, (uint8_t*) uart_buf, uart_buf_len, 100); // Shutdown uart_buf_len = sprintf(uart_buf, "Shutting Down\r\n"); HAL_UART_Transmit(&huart2, (uint8_t*) uart_buf, uart_buf_len, 100); lm75a.shutdown(); is_shutdown = lm75a.isShutdown(); uart_buf_len = sprintf(uart_buf, "Is shutdown?: %u \r\n", ((unsigned int) is_shutdown)); HAL_UART_Transmit(&huart2, (uint8_t*) uart_buf, uart_buf_len, 100); HAL_Delay(5000); ///Wake up uart_buf_len = sprintf(uart_buf, "Waking up\r\n"); HAL_UART_Transmit(&huart2, (uint8_t*) uart_buf, uart_buf_len, 100); lm75a.wakeup(); is_shutdown = lm75a.isShutdown(); uart_buf_len = sprintf(uart_buf, "Is shutdown?: %u \r\n", ((unsigned int) is_shutdown)); HAL_UART_Transmit(&huart2, (uint8_t*) uart_buf, uart_buf_len, 100); HAL_Delay(5000); #endif #ifdef LIB_TEST // Test 1 : Test comms checkTrueValue("isConnected", lm75a.isConnected(), true); HAL_Delay(2000); // Test 2 testing temperature getters (4*) checkTemperatureResult("getTemperature", lm75a.getTemperature()); checkTemperatureResult("getTemperatureInFarenheit", lm75a.getTemperatureInFarenheit()); checkTemperatureResult("getHysterisisTemperature", lm75a.getHysterisisTemperature()); checkTemperatureResult("getOSTripTemperature", lm75a.getOSTripTemperature()); HAL_UART_Transmit(&huart2, (uint8_t*)'\n', 1, 100); // Test 3 Testing other getters checkFaultQueueValue("getFaultQueueValue", lm75a.getFaultQueueValue(), FaultQueueValue::NUMBER_OF_FAULTS_1); checkOsPolarityValue("getOsPolarity", lm75a.getOsPolarity(), OsPolarity::OS_POLARITY_ACTIVELOW); checkDeviceModeValue("getDeviceMode", lm75a.getDeviceMode(), DeviceMode::DEVICE_MODE_COMPARATOR); HAL_Delay(2000); // Test 4 : Testing temperature setters oldHysterisisTemperature = lm75a.getHysterisisTemperature(); oldOsTripTemperature = lm75a.getOSTripTemperature(); lm75a.setHysterisisTemperature(newHysterisisTemperature); lm75a.setOsTripTemperature(newOsTripTemperature); checkTemperatureValue("setHysterisisTemperature", lm75a.getHysterisisTemperature(), newHysterisisTemperature); checkTemperatureValue("setOsTripTemperature", lm75a.getOSTripTemperature(), newOsTripTemperature); lm75a.setHysterisisTemperature(oldHysterisisTemperature); lm75a.setOsTripTemperature(oldOsTripTemperature); HAL_Delay(2000); // Test 5 "Testing other setters"); oldFaultQueueValue = lm75a.getFaultQueueValue(); oldOsPolarity = lm75a.getOsPolarity(); oldDeviceMode = lm75a.getDeviceMode(); lm75a.setFaultQueueValue(newFaultQueueValue); lm75a.setOsPolarity(newOsPolarity); lm75a.setDeviceMode(newDeviceMode); checkFaultQueueValue("setFaultQueueValue: ", lm75a.getFaultQueueValue(), newFaultQueueValue); checkOsPolarityValue("setOsPolarity", lm75a.getOsPolarity(), newOsPolarity); checkDeviceModeValue("setDeviceMode", lm75a.getDeviceMode(), newDeviceMode); lm75a.setFaultQueueValue(oldFaultQueueValue); lm75a.setOsPolarity(oldOsPolarity); lm75a.setDeviceMode(oldDeviceMode); HAL_Delay(2000); // Test 6 lm75a.shutdown(); checkTrueValue("shutdown", lm75a.isShutdown(), true); HAL_Delay(2000); lm75a.wakeup(); checkTrueValue("shutdown", lm75a.isShutdown(), false); HAL_Delay(2000); uart_buf_len = sprintf(uart_buf, "\nTest Result %u\r\n",(uint8_t)testResult); HAL_UART_Transmit(&huart2, (uint8_t*) uart_buf, uart_buf_len, 100); while(1){}; // stay here test over #endif /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = { 0 }; RCC_ClkInitTypeDef RCC_ClkInitStruct = { 0 }; RCC_PeriphCLKInitTypeDef PeriphClkInit = { 0 }; /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB buses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK) { Error_Handler(); } PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_I2C1; PeriphClkInit.I2c1ClockSelection = RCC_I2C1CLKSOURCE_HSI; if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK) { Error_Handler(); } } /** * @brief I2C1 Initialization Function * @param None * @retval None */ static void MX_I2C1_Init(void) { /* USER CODE BEGIN I2C1_Init 0 */ /* USER CODE END I2C1_Init 0 */ /* USER CODE BEGIN I2C1_Init 1 */ /* USER CODE END I2C1_Init 1 */ hi2c1.Instance = I2C1; hi2c1.Init.Timing = 0x2000090E; hi2c1.Init.OwnAddress1 = 0; hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE; hi2c1.Init.OwnAddress2 = 0; hi2c1.Init.OwnAddress2Masks = I2C_OA2_NOMASK; hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE; hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE; if (HAL_I2C_Init(&hi2c1) != HAL_OK) { Error_Handler(); } /** Configure Analogue filter */ if (HAL_I2CEx_ConfigAnalogFilter(&hi2c1, I2C_ANALOGFILTER_ENABLE) != HAL_OK) { Error_Handler(); } /** Configure Digital filter */ if (HAL_I2CEx_ConfigDigitalFilter(&hi2c1, 0) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN I2C1_Init 2 */ /* USER CODE END I2C1_Init 2 */ } /** * @brief USART2 Initialization Function * @param None * @retval None */ static void MX_USART2_UART_Init(void) { /* USER CODE BEGIN USART2_Init 0 */ /* USER CODE END USART2_Init 0 */ /* USER CODE BEGIN USART2_Init 1 */ /* USER CODE END USART2_Init 1 */ huart2.Instance = USART2; huart2.Init.BaudRate = 38400; huart2.Init.WordLength = UART_WORDLENGTH_8B; huart2.Init.StopBits = UART_STOPBITS_1; huart2.Init.Parity = UART_PARITY_NONE; huart2.Init.Mode = UART_MODE_TX_RX; huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE; huart2.Init.OverSampling = UART_OVERSAMPLING_16; huart2.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE; huart2.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT; if (HAL_UART_Init(&huart2) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN USART2_Init 2 */ /* USER CODE END USART2_Init 2 */ } /** * @brief GPIO Initialization Function * @param None * @retval None */ static void MX_GPIO_Init(void) { /* GPIO Ports Clock Enable */ __HAL_RCC_GPIOF_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); } /* USER CODE BEGIN 4 */ void checkTrueValue(const char* caption, const bool value, const bool expected) { bool fail = value != expected; if (fail) { testResult = false; uart_buf_len = sprintf(uart_buf, "%s : %u FAIL \r\n\n", caption , (uint8_t)value); } else { uart_buf_len = sprintf(uart_buf, "%s : %u: PASS\r\n\n", caption , (uint8_t)value); } HAL_UART_Transmit(&huart2, (uint8_t*) uart_buf, uart_buf_len, 100); } const char* getFaultQueueValueString(const FaultQueueValue value) { switch (value) { case FaultQueueValue::NUMBER_OF_FAULTS_1: return "NUMBER_OF_FAULTS_1"; case FaultQueueValue::NUMBER_OF_FAULTS_2: return "NUMBER_OF_FAULTS_2"; case FaultQueueValue::NUMBER_OF_FAULTS_4: return "NUMBER_OF_FAULTS_4"; case FaultQueueValue::NUMBER_OF_FAULTS_6: return "NUMBER_OF_FAULTS_4"; default: return "** ILLEGAL VALUE **"; } } const char* getOsPolarityString(const OsPolarity value) { switch (value) { case OsPolarity::OS_POLARITY_ACTIVEHIGH: return "OS_POLARITY_ACTIVEHIGH"; case OsPolarity::OS_POLARITY_ACTIVELOW: return "OS_POLARITY_ACTIVELOW"; default: return "** ILLEGAL VALUE **"; } } const char* getDeviceModeString(DeviceMode value) { switch (value) { case DeviceMode::DEVICE_MODE_COMPARATOR: return "DEVICE_MODE_COMPARATOR"; case DeviceMode::DEVICE_MODE_INTERRUPT: return "DEVICE_MODE_INTERRUPT"; default: return "** ILLEGAL VALUE **"; } } void checkTemperatureValue(const char* caption, const float value, const float expected) { bool fail = value != expected; if (fail) { testResult = false; uart_buf_len = sprintf(uart_buf, "%s : %u: %u FAIL\r\n", caption , (uint8_t)value, (uint8_t)expected); } else { uart_buf_len = sprintf(uart_buf, "%s : %u: PASS\r\n", caption , (uint8_t)value); } HAL_UART_Transmit(&huart2, (uint8_t*) uart_buf, uart_buf_len, 100); } void checkTemperatureResult(const char* caption, const float value) { bool fail = value == LM75A_INVALID_TEMPERATURE; if (fail) { testResult = false; uart_buf_len = sprintf(uart_buf, "%s : %u: FAIL LM75A_INVALID_TEMPERATURE\r\n", caption , (uint8_t)value); } else { uart_buf_len = sprintf(uart_buf, "%s : %u: PASS\r\n", caption , (uint8_t)value); } HAL_UART_Transmit(&huart2, (uint8_t*) uart_buf, uart_buf_len, 100); } void checkOsPolarityValue(const char* caption, const OsPolarity value, const OsPolarity expected) { bool fail = value != expected; if (fail) { testResult = false; uart_buf_len = sprintf(uart_buf, "%s : %d: FAIL \r\n", caption , (uint8_t)expected); } else { uart_buf_len = sprintf(uart_buf, "%s : %d: PASS\r\n", caption , (uint8_t)expected); } HAL_UART_Transmit(&huart2, (uint8_t*) uart_buf, uart_buf_len, 100); } void checkDeviceModeValue(const char* caption, const DeviceMode value, const DeviceMode expected) { bool fail = value != expected; if (fail) { testResult = false; uart_buf_len = sprintf(uart_buf, "%s : %d: FAIL Expected\r\n", caption , (uint8_t)expected); } else { uart_buf_len = sprintf(uart_buf, "%s : %d: PASS \r\n\n", caption , (uint8_t)expected); } HAL_UART_Transmit(&huart2, (uint8_t*) uart_buf, uart_buf_len, 100); } void checkFaultQueueValue(const char* caption, const FaultQueueValue value, const FaultQueueValue expected) { bool fail = value != expected; if (fail) { testResult = false; uart_buf_len = sprintf(uart_buf, "%s : %d: FAIL Expected\r\n", caption , (uint8_t)expected); } else { uart_buf_len = sprintf(uart_buf, "%s : %d: PASS \r\n", caption , (uint8_t)expected); } HAL_UART_Transmit(&huart2, (uint8_t*) uart_buf, uart_buf_len, 100); } /* USER CODE END 4 */ /** * @brief This function is executed in case of error occurrence. * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
// // Unit tests for denial-of-service detection/prevention code // #include <algorithm> #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/date_time/posix_time/posix_time_types.hpp> #include <boost/test/unit_test.hpp> #include <boost/foreach.hpp> #include "main.h" #include "wallet.h" #include "net.h" #include "util.h" #include <stdint.h> // Tests this internal-to-main.cpp method: extern bool AddOrphanTx(const CDataStream& vMsg); extern unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans); extern std::map<uint256, CDataStream*> mapOrphanTransactions; extern std::map<uint256, std::map<uint256, CDataStream*> > mapOrphanTransactionsByPrev; CService ip(uint32_t i) { struct in_addr s; s.s_addr = i; return CService(CNetAddr(s), GetDefaultPort()); } BOOST_AUTO_TEST_SUITE(DoS_tests) BOOST_AUTO_TEST_CASE(DoS_banning) { CNode::ClearBanned(); CAddress addr1(ip(0xa0b0c001)); CNode dummyNode1(INVALID_SOCKET, addr1, "", true); dummyNode1.Misbehaving(100); // Should get banned BOOST_CHECK(CNode::IsBanned(addr1)); BOOST_CHECK(!CNode::IsBanned(ip(0xa0b0c001|0x0000ff00))); // Different IP, not banned CAddress addr2(ip(0xa0b0c002)); CNode dummyNode2(INVALID_SOCKET, addr2, "", true); dummyNode2.Misbehaving(50); BOOST_CHECK(!CNode::IsBanned(addr2)); // 2 not banned yet... BOOST_CHECK(CNode::IsBanned(addr1)); // ... but 1 still should be dummyNode2.Misbehaving(50); BOOST_CHECK(CNode::IsBanned(addr2)); } BOOST_AUTO_TEST_CASE(DoS_banscore) { CNode::ClearBanned(); mapArgs["-banscore"] = "111"; // because 11 is my favorite number CAddress addr1(ip(0xa0b0c001)); CNode dummyNode1(INVALID_SOCKET, addr1, "", true); dummyNode1.Misbehaving(100); BOOST_CHECK(!CNode::IsBanned(addr1)); dummyNode1.Misbehaving(10); BOOST_CHECK(!CNode::IsBanned(addr1)); dummyNode1.Misbehaving(1); BOOST_CHECK(CNode::IsBanned(addr1)); mapArgs.erase("-banscore"); } BOOST_AUTO_TEST_CASE(DoS_bantime) { CNode::ClearBanned(); int64 nStartTime = GetTime(); SetMockTime(nStartTime); // Overrides future calls to GetTime() CAddress addr(ip(0xa0b0c001)); CNode dummyNode(INVALID_SOCKET, addr, "", true); dummyNode.Misbehaving(100); BOOST_CHECK(CNode::IsBanned(addr)); SetMockTime(nStartTime+60*60); BOOST_CHECK(CNode::IsBanned(addr)); SetMockTime(nStartTime+60*60*24+1); BOOST_CHECK(!CNode::IsBanned(addr)); } static bool CheckNBits(unsigned int nbits1, int64 time1, unsigned int nbits2, int64 time2)\ { if (time1 > time2) return CheckNBits(nbits2, time2, nbits1, time1); int64 deltaTime = time2-time1; CBigNum required; required.SetCompact(ComputeMinWork(nbits1, deltaTime)); CBigNum have; have.SetCompact(nbits2); return (have <= required); } BOOST_AUTO_TEST_CASE(DoS_checknbits) { using namespace boost::assign; // for 'map_list_of()' // Timestamps,nBits from the bitcoin blockchain. // These are the block-chain checkpoint blocks typedef std::map<int64, unsigned int> BlockData; BlockData chainData = map_list_of(1239852051,486604799)(1262749024,486594666) (1279305360,469854461)(1280200847,469830746)(1281678674,469809688) (1296207707,453179945)(1302624061,453036989)(1309640330,437004818) (1313172719,436789733); // Make sure CheckNBits considers every combination of block-chain-lock-in-points // "sane": BOOST_FOREACH(const BlockData::value_type& i, chainData) { BOOST_FOREACH(const BlockData::value_type& j, chainData) { BOOST_CHECK(CheckNBits(i.second, i.first, j.second, j.first)); } } // Test a couple of insane combinations: BlockData::value_type firstcheck = *(chainData.begin()); BlockData::value_type lastcheck = *(chainData.rbegin()); // First checkpoint difficulty at or a while after the last checkpoint time should fail when // compared to last checkpoint BOOST_CHECK(!CheckNBits(firstcheck.second, lastcheck.first+60*10, lastcheck.second, lastcheck.first)); BOOST_CHECK(!CheckNBits(firstcheck.second, lastcheck.first+60*60*24*14, lastcheck.second, lastcheck.first)); // ... but OK if enough time passed for difficulty to adjust downward: BOOST_CHECK(CheckNBits(firstcheck.second, lastcheck.first+60*60*24*365*4, lastcheck.second, lastcheck.first)); } CTransaction RandomOrphan() { std::map<uint256, CDataStream*>::iterator it; it = mapOrphanTransactions.lower_bound(GetRandHash()); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); const CDataStream* pvMsg = it->second; CTransaction tx; CDataStream(*pvMsg) >> tx; return tx; } BOOST_AUTO_TEST_CASE(DoS_mapOrphans) { CKey key; key.MakeNewKey(true); CBasicKeyStore keystore; keystore.AddKey(key); // 50 orphan transactions: for (int i = 0; i < 50; i++) { CTransaction tx; tx.vin.resize(1); tx.vin[0].prevout.n = 0; tx.vin[0].prevout.hash = GetRandHash(); tx.vin[0].scriptSig << OP_1; tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID()); CDataStream ds(SER_DISK, CLIENT_VERSION); ds << tx; AddOrphanTx(ds); } // ... and 50 that depend on other orphans: for (int i = 0; i < 50; i++) { CTransaction txPrev = RandomOrphan(); CTransaction tx; tx.vin.resize(1); tx.vin[0].prevout.n = 0; tx.vin[0].prevout.hash = txPrev.GetHash(); tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID()); SignSignature(keystore, txPrev, tx, 0); CDataStream ds(SER_DISK, CLIENT_VERSION); ds << tx; AddOrphanTx(ds); } // This really-big orphan should be ignored: for (int i = 0; i < 10; i++) { CTransaction txPrev = RandomOrphan(); CTransaction tx; tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID()); tx.vin.resize(500); for (unsigned int j = 0; j < tx.vin.size(); j++) { tx.vin[j].prevout.n = j; tx.vin[j].prevout.hash = txPrev.GetHash(); } SignSignature(keystore, txPrev, tx, 0); // Re-use same signature for other inputs // (they don't have to be valid for this test) for (unsigned int j = 1; j < tx.vin.size(); j++) tx.vin[j].scriptSig = tx.vin[0].scriptSig; CDataStream ds(SER_DISK, CLIENT_VERSION); ds << tx; BOOST_CHECK(!AddOrphanTx(ds)); } // Test LimitOrphanTxSize() function: LimitOrphanTxSize(40); BOOST_CHECK(mapOrphanTransactions.size() <= 40); LimitOrphanTxSize(10); BOOST_CHECK(mapOrphanTransactions.size() <= 10); LimitOrphanTxSize(0); BOOST_CHECK(mapOrphanTransactions.empty()); BOOST_CHECK(mapOrphanTransactionsByPrev.empty()); } BOOST_AUTO_TEST_CASE(DoS_checkSig) { // Test signature caching code (see key.cpp Verify() methods) CKey key; key.MakeNewKey(true); CBasicKeyStore keystore; keystore.AddKey(key); // 100 orphan transactions: static const int NPREV=100; CTransaction orphans[NPREV]; for (int i = 0; i < NPREV; i++) { CTransaction& tx = orphans[i]; tx.vin.resize(1); tx.vin[0].prevout.n = 0; tx.vin[0].prevout.hash = GetRandHash(); tx.vin[0].scriptSig << OP_1; tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID()); CDataStream ds(SER_DISK, CLIENT_VERSION); ds << tx; AddOrphanTx(ds); } // Create a transaction that depends on orphans: CTransaction tx; tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID()); tx.vin.resize(NPREV); for (unsigned int j = 0; j < tx.vin.size(); j++) { tx.vin[j].prevout.n = 0; tx.vin[j].prevout.hash = orphans[j].GetHash(); } // Creating signatures primes the cache: boost::posix_time::ptime mst1 = boost::posix_time::microsec_clock::local_time(); for (unsigned int j = 0; j < tx.vin.size(); j++) BOOST_CHECK(SignSignature(keystore, orphans[j], tx, j)); boost::posix_time::ptime mst2 = boost::posix_time::microsec_clock::local_time(); boost::posix_time::time_duration msdiff = mst2 - mst1; long nOneValidate = msdiff.total_milliseconds(); if (fDebug) printf("DoS_Checksig sign: %ld\n", nOneValidate); // ... now validating repeatedly should be quick: // 2.8GHz machine, -g build: Sign takes ~760ms, // uncached Verify takes ~250ms, cached Verify takes ~50ms // (for 100 single-signature inputs) mst1 = boost::posix_time::microsec_clock::local_time(); for (unsigned int i = 0; i < 5; i++) for (unsigned int j = 0; j < tx.vin.size(); j++) BOOST_CHECK(VerifySignature(orphans[j], tx, j, true, SIGHASH_ALL)); mst2 = boost::posix_time::microsec_clock::local_time(); msdiff = mst2 - mst1; long nManyValidate = msdiff.total_milliseconds(); if (fDebug) printf("DoS_Checksig five: %ld\n", nManyValidate); BOOST_CHECK_MESSAGE(nManyValidate < nOneValidate, "Signature cache timing failed"); // Empty a signature, validation should fail: CScript save = tx.vin[0].scriptSig; tx.vin[0].scriptSig = CScript(); BOOST_CHECK(!VerifySignature(orphans[0], tx, 0, true, SIGHASH_ALL)); tx.vin[0].scriptSig = save; // Swap signatures, validation should fail: std::swap(tx.vin[0].scriptSig, tx.vin[1].scriptSig); BOOST_CHECK(!VerifySignature(orphans[0], tx, 0, true, SIGHASH_ALL)); BOOST_CHECK(!VerifySignature(orphans[1], tx, 1, true, SIGHASH_ALL)); std::swap(tx.vin[0].scriptSig, tx.vin[1].scriptSig); // Exercise -maxsigcachesize code: mapArgs["-maxsigcachesize"] = "10"; // Generate a new, different signature for vin[0] to trigger cache clear: CScript oldSig = tx.vin[0].scriptSig; BOOST_CHECK(SignSignature(keystore, orphans[0], tx, 0)); BOOST_CHECK(tx.vin[0].scriptSig != oldSig); for (unsigned int j = 0; j < tx.vin.size(); j++) BOOST_CHECK(VerifySignature(orphans[j], tx, j, true, SIGHASH_ALL)); mapArgs.erase("-maxsigcachesize"); LimitOrphanTxSize(0); } BOOST_AUTO_TEST_SUITE_END()
// Formatting library for C++ - time formatting tests // // Copyright (c) 2012 - present, Victor Zverovich // All rights reserved. // // For the license information refer to format.h. #include "fmt/chrono.h" #include "gtest-extra.h" // EXPECT_THROW_MSG using fmt::runtime; auto make_tm() -> std::tm { auto time = std::tm(); time.tm_mday = 1; return time; } auto make_hour(int h) -> std::tm { auto time = make_tm(); time.tm_hour = h; return time; } auto make_minute(int m) -> std::tm { auto time = make_tm(); time.tm_min = m; return time; } auto make_second(int s) -> std::tm { auto time = make_tm(); time.tm_sec = s; return time; } TEST(chrono_test, format_tm) { auto tm = std::tm(); tm.tm_year = 116; tm.tm_mon = 3; tm.tm_mday = 25; tm.tm_hour = 11; tm.tm_min = 22; tm.tm_sec = 33; EXPECT_EQ(fmt::format("The date is {:%Y-%m-%d %H:%M:%S}.", tm), "The date is 2016-04-25 11:22:33."); EXPECT_EQ(fmt::format(L"The date is {:%Y-%m-%d %H:%M:%S}.", tm), L"The date is 2016-04-25 11:22:33."); } TEST(chrono_test, grow_buffer) { auto s = std::string("{:"); for (int i = 0; i < 30; ++i) s += "%c"; s += "}\n"; auto t = std::time(nullptr); fmt::format(fmt::runtime(s), *std::localtime(&t)); } TEST(chrono_test, format_to_empty_container) { auto time = std::tm(); time.tm_sec = 42; auto s = std::string(); fmt::format_to(std::back_inserter(s), "{:%S}", time); EXPECT_EQ(s, "42"); } TEST(chrono_test, empty_result) { EXPECT_EQ(fmt::format("{}", std::tm()), ""); } auto equal(const std::tm& lhs, const std::tm& rhs) -> bool { return lhs.tm_sec == rhs.tm_sec && lhs.tm_min == rhs.tm_min && lhs.tm_hour == rhs.tm_hour && lhs.tm_mday == rhs.tm_mday && lhs.tm_mon == rhs.tm_mon && lhs.tm_year == rhs.tm_year && lhs.tm_wday == rhs.tm_wday && lhs.tm_yday == rhs.tm_yday && lhs.tm_isdst == rhs.tm_isdst; } TEST(chrono_test, localtime) { auto t = std::time(nullptr); auto tm = *std::localtime(&t); EXPECT_TRUE(equal(tm, fmt::localtime(t))); } TEST(chrono_test, gmtime) { auto t = std::time(nullptr); auto tm = *std::gmtime(&t); EXPECT_TRUE(equal(tm, fmt::gmtime(t))); } template <typename TimePoint> auto strftime(TimePoint tp) -> std::string { auto t = std::chrono::system_clock::to_time_t(tp); auto tm = *std::localtime(&t); char output[256] = {}; std::strftime(output, sizeof(output), "%Y-%m-%d %H:%M:%S", &tm); return output; } TEST(chrono_test, time_point) { auto t1 = std::chrono::system_clock::now(); EXPECT_EQ(strftime(t1), fmt::format("{:%Y-%m-%d %H:%M:%S}", t1)); using time_point = std::chrono::time_point<std::chrono::system_clock, std::chrono::seconds>; auto t2 = time_point(std::chrono::seconds(42)); EXPECT_EQ(strftime(t2), fmt::format("{:%Y-%m-%d %H:%M:%S}", t2)); } #ifndef FMT_STATIC_THOUSANDS_SEPARATOR TEST(chrono_test, format_default) { EXPECT_EQ("42s", fmt::format("{}", std::chrono::seconds(42))); EXPECT_EQ("42as", fmt::format("{}", std::chrono::duration<int, std::atto>(42))); EXPECT_EQ("42fs", fmt::format("{}", std::chrono::duration<int, std::femto>(42))); EXPECT_EQ("42ps", fmt::format("{}", std::chrono::duration<int, std::pico>(42))); EXPECT_EQ("42ns", fmt::format("{}", std::chrono::nanoseconds(42))); EXPECT_EQ("42µs", fmt::format("{}", std::chrono::microseconds(42))); EXPECT_EQ("42ms", fmt::format("{}", std::chrono::milliseconds(42))); EXPECT_EQ("42cs", fmt::format("{}", std::chrono::duration<int, std::centi>(42))); EXPECT_EQ("42ds", fmt::format("{}", std::chrono::duration<int, std::deci>(42))); EXPECT_EQ("42s", fmt::format("{}", std::chrono::seconds(42))); EXPECT_EQ("42das", fmt::format("{}", std::chrono::duration<int, std::deca>(42))); EXPECT_EQ("42hs", fmt::format("{}", std::chrono::duration<int, std::hecto>(42))); EXPECT_EQ("42ks", fmt::format("{}", std::chrono::duration<int, std::kilo>(42))); EXPECT_EQ("42Ms", fmt::format("{}", std::chrono::duration<int, std::mega>(42))); EXPECT_EQ("42Gs", fmt::format("{}", std::chrono::duration<int, std::giga>(42))); EXPECT_EQ("42Ts", fmt::format("{}", std::chrono::duration<int, std::tera>(42))); EXPECT_EQ("42Ps", fmt::format("{}", std::chrono::duration<int, std::peta>(42))); EXPECT_EQ("42Es", fmt::format("{}", std::chrono::duration<int, std::exa>(42))); EXPECT_EQ("42m", fmt::format("{}", std::chrono::minutes(42))); EXPECT_EQ("42h", fmt::format("{}", std::chrono::hours(42))); EXPECT_EQ( "42[15]s", fmt::format("{}", std::chrono::duration<int, std::ratio<15, 1>>(42))); EXPECT_EQ( "42[15/4]s", fmt::format("{}", std::chrono::duration<int, std::ratio<15, 4>>(42))); } TEST(chrono_test, format_wide) { EXPECT_EQ(L"42s", fmt::format(L"{}", std::chrono::seconds(42))); } TEST(chrono_test, align) { auto s = std::chrono::seconds(42); EXPECT_EQ("42s ", fmt::format("{:5}", s)); EXPECT_EQ("42s ", fmt::format("{:{}}", s, 5)); EXPECT_EQ(" 42s", fmt::format("{:>5}", s)); EXPECT_EQ("**42s**", fmt::format("{:*^7}", s)); EXPECT_EQ("03:25:45 ", fmt::format("{:12%H:%M:%S}", std::chrono::seconds(12345))); EXPECT_EQ(" 03:25:45", fmt::format("{:>12%H:%M:%S}", std::chrono::seconds(12345))); EXPECT_EQ("~~03:25:45~~", fmt::format("{:~^12%H:%M:%S}", std::chrono::seconds(12345))); EXPECT_EQ("03:25:45 ", fmt::format("{:{}%H:%M:%S}", std::chrono::seconds(12345), 12)); } TEST(chrono_test, format_specs) { EXPECT_EQ("%", fmt::format("{:%%}", std::chrono::seconds(0))); EXPECT_EQ("\n", fmt::format("{:%n}", std::chrono::seconds(0))); EXPECT_EQ("\t", fmt::format("{:%t}", std::chrono::seconds(0))); EXPECT_EQ("00", fmt::format("{:%S}", std::chrono::seconds(0))); EXPECT_EQ("00", fmt::format("{:%S}", std::chrono::seconds(60))); EXPECT_EQ("42", fmt::format("{:%S}", std::chrono::seconds(42))); EXPECT_EQ("01.234", fmt::format("{:%S}", std::chrono::milliseconds(1234))); EXPECT_EQ("00", fmt::format("{:%M}", std::chrono::minutes(0))); EXPECT_EQ("00", fmt::format("{:%M}", std::chrono::minutes(60))); EXPECT_EQ("42", fmt::format("{:%M}", std::chrono::minutes(42))); EXPECT_EQ("01", fmt::format("{:%M}", std::chrono::seconds(61))); EXPECT_EQ("00", fmt::format("{:%H}", std::chrono::hours(0))); EXPECT_EQ("00", fmt::format("{:%H}", std::chrono::hours(24))); EXPECT_EQ("14", fmt::format("{:%H}", std::chrono::hours(14))); EXPECT_EQ("01", fmt::format("{:%H}", std::chrono::minutes(61))); EXPECT_EQ("12", fmt::format("{:%I}", std::chrono::hours(0))); EXPECT_EQ("12", fmt::format("{:%I}", std::chrono::hours(12))); EXPECT_EQ("12", fmt::format("{:%I}", std::chrono::hours(24))); EXPECT_EQ("04", fmt::format("{:%I}", std::chrono::hours(4))); EXPECT_EQ("02", fmt::format("{:%I}", std::chrono::hours(14))); EXPECT_EQ("03:25:45", fmt::format("{:%H:%M:%S}", std::chrono::seconds(12345))); EXPECT_EQ("03:25", fmt::format("{:%R}", std::chrono::seconds(12345))); EXPECT_EQ("03:25:45", fmt::format("{:%T}", std::chrono::seconds(12345))); EXPECT_EQ("12345", fmt::format("{:%Q}", std::chrono::seconds(12345))); EXPECT_EQ("s", fmt::format("{:%q}", std::chrono::seconds(12345))); } TEST(chrono_test, invalid_specs) { auto sec = std::chrono::seconds(0); EXPECT_THROW_MSG(fmt::format(runtime("{:%a}"), sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format(runtime("{:%A}"), sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format(runtime("{:%c}"), sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format(runtime("{:%x}"), sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format(runtime("{:%Ex}"), sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format(runtime("{:%X}"), sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format(runtime("{:%EX}"), sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format(runtime("{:%D}"), sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format(runtime("{:%F}"), sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format(runtime("{:%Ec}"), sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format(runtime("{:%w}"), sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format(runtime("{:%u}"), sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format(runtime("{:%b}"), sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format(runtime("{:%B}"), sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format(runtime("{:%z}"), sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format(runtime("{:%Z}"), sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format(runtime("{:%Eq}"), sec), fmt::format_error, "invalid format"); EXPECT_THROW_MSG(fmt::format(runtime("{:%Oq}"), sec), fmt::format_error, "invalid format"); } auto format_tm(const std::tm& time, fmt::string_view spec, const std::locale& loc) -> std::string { auto& facet = std::use_facet<std::time_put<char>>(loc); std::ostringstream os; os.imbue(loc); facet.put(os, os, ' ', &time, spec.begin(), spec.end()); return os.str(); } # define EXPECT_TIME(spec, time, duration) \ { \ auto jp_loc = std::locale("ja_JP.utf8"); \ EXPECT_EQ(format_tm(time, spec, jp_loc), \ fmt::format(jp_loc, "{:L" spec "}", duration)); \ } TEST(chrono_test, locale) { auto loc_name = "ja_JP.utf8"; bool has_locale = false; auto loc = std::locale(); try { loc = std::locale(loc_name); has_locale = true; } catch (const std::runtime_error&) { } if (!has_locale) { fmt::print("{} locale is missing.\n", loc_name); return; } EXPECT_TIME("%OH", make_hour(14), std::chrono::hours(14)); EXPECT_TIME("%OI", make_hour(14), std::chrono::hours(14)); EXPECT_TIME("%OM", make_minute(42), std::chrono::minutes(42)); EXPECT_TIME("%OS", make_second(42), std::chrono::seconds(42)); auto time = make_tm(); time.tm_hour = 3; time.tm_min = 25; time.tm_sec = 45; auto sec = std::chrono::seconds(12345); EXPECT_TIME("%r", time, sec); EXPECT_TIME("%p", time, sec); } using dms = std::chrono::duration<double, std::milli>; TEST(chrono_test, format_default_fp) { typedef std::chrono::duration<float> fs; EXPECT_EQ("1.234s", fmt::format("{}", fs(1.234))); typedef std::chrono::duration<float, std::milli> fms; EXPECT_EQ("1.234ms", fmt::format("{}", fms(1.234))); typedef std::chrono::duration<double> ds; EXPECT_EQ("1.234s", fmt::format("{}", ds(1.234))); EXPECT_EQ("1.234ms", fmt::format("{}", dms(1.234))); } TEST(chrono_test, format_precision) { EXPECT_THROW_MSG(fmt::format(runtime("{:.2}"), std::chrono::seconds(42)), fmt::format_error, "precision not allowed for this argument type"); EXPECT_EQ("1.2ms", fmt::format("{:.1}", dms(1.234))); EXPECT_EQ("1.23ms", fmt::format("{:.{}}", dms(1.234), 2)); } TEST(chrono_test, format_full_specs) { EXPECT_EQ("1.2ms ", fmt::format("{:6.1}", dms(1.234))); EXPECT_EQ(" 1.23ms", fmt::format("{:>8.{}}", dms(1.234), 2)); EXPECT_EQ(" 1.2ms ", fmt::format("{:^{}.{}}", dms(1.234), 7, 1)); EXPECT_EQ(" 1.23ms ", fmt::format("{0:^{2}.{1}}", dms(1.234), 2, 8)); EXPECT_EQ("=1.234ms=", fmt::format("{:=^{}.{}}", dms(1.234), 9, 3)); EXPECT_EQ("*1.2340ms*", fmt::format("{:*^10.4}", dms(1.234))); } TEST(chrono_test, format_simple_q) { typedef std::chrono::duration<float> fs; EXPECT_EQ("1.234 s", fmt::format("{:%Q %q}", fs(1.234))); typedef std::chrono::duration<float, std::milli> fms; EXPECT_EQ("1.234 ms", fmt::format("{:%Q %q}", fms(1.234))); typedef std::chrono::duration<double> ds; EXPECT_EQ("1.234 s", fmt::format("{:%Q %q}", ds(1.234))); EXPECT_EQ("1.234 ms", fmt::format("{:%Q %q}", dms(1.234))); } TEST(chrono_test, format_precision_q) { EXPECT_THROW_MSG(fmt::format(runtime("{:.2%Q %q}"), std::chrono::seconds(42)), fmt::format_error, "precision not allowed for this argument type"); EXPECT_EQ("1.2 ms", fmt::format("{:.1%Q %q}", dms(1.234))); EXPECT_EQ("1.23 ms", fmt::format("{:.{}%Q %q}", dms(1.234), 2)); } TEST(chrono_test, format_full_specs_q) { EXPECT_EQ("1.2 ms ", fmt::format("{:7.1%Q %q}", dms(1.234))); EXPECT_EQ(" 1.23 ms", fmt::format("{:>8.{}%Q %q}", dms(1.234), 2)); EXPECT_EQ(" 1.2 ms ", fmt::format("{:^{}.{}%Q %q}", dms(1.234), 8, 1)); EXPECT_EQ(" 1.23 ms ", fmt::format("{0:^{2}.{1}%Q %q}", dms(1.234), 2, 9)); EXPECT_EQ("=1.234 ms=", fmt::format("{:=^{}.{}%Q %q}", dms(1.234), 10, 3)); EXPECT_EQ("*1.2340 ms*", fmt::format("{:*^11.4%Q %q}", dms(1.234))); } TEST(chrono_test, invalid_width_id) { EXPECT_THROW(fmt::format(runtime("{:{o}"), std::chrono::seconds(0)), fmt::format_error); } TEST(chrono_test, invalid_colons) { EXPECT_THROW(fmt::format(runtime("{0}=:{0::"), std::chrono::seconds(0)), fmt::format_error); } TEST(chrono_test, negative_durations) { EXPECT_EQ("-12345", fmt::format("{:%Q}", std::chrono::seconds(-12345))); EXPECT_EQ("-03:25:45", fmt::format("{:%H:%M:%S}", std::chrono::seconds(-12345))); EXPECT_EQ("-00:01", fmt::format("{:%M:%S}", std::chrono::duration<double>(-1))); EXPECT_EQ("s", fmt::format("{:%q}", std::chrono::seconds(-12345))); EXPECT_EQ("-00.127", fmt::format("{:%S}", std::chrono::duration<signed char, std::milli>{-127})); auto min = std::numeric_limits<int>::min(); EXPECT_EQ(fmt::format("{}", min), fmt::format("{:%Q}", std::chrono::duration<int>(min))); } TEST(chrono_test, special_durations) { EXPECT_EQ( "40.", fmt::format("{:%S}", std::chrono::duration<double>(1e20)).substr(0, 3)); auto nan = std::numeric_limits<double>::quiet_NaN(); EXPECT_EQ( "nan nan nan nan nan:nan nan", fmt::format("{:%I %H %M %S %R %r}", std::chrono::duration<double>(nan))); fmt::format("{:%S}", std::chrono::duration<float, std::atto>(1.79400457e+31f)); EXPECT_EQ(fmt::format("{}", std::chrono::duration<float, std::exa>(1)), "1Es"); EXPECT_EQ(fmt::format("{}", std::chrono::duration<float, std::atto>(1)), "1as"); EXPECT_EQ(fmt::format("{:%R}", std::chrono::duration<char, std::mega>{2}), "03:33"); EXPECT_EQ(fmt::format("{:%T}", std::chrono::duration<char, std::mega>{2}), "03:33:20"); } TEST(chrono_test, unsigned_duration) { EXPECT_EQ("42s", fmt::format("{}", std::chrono::duration<unsigned>(42))); } #endif // FMT_STATIC_THOUSANDS_SEPARATOR
/* All Paths from Source Lead to Destination https://leetcode.com/problems/all-paths-from-source-lead-to-destination/ Given the edges of a directed graph where edges[i] = [ai, bi] indicates there is an edge between nodes ai and bi, and two nodes source and destination of this graph, determine whether or not all paths starting from source eventually, end at destination, that is: At least one path exists from the source node to the destination node If a path exists from the source node to a node with no outgoing edges, then that node is equal to destination. The number of possible paths from source to destination is a finite number. Return true if and only if all roads from source lead to destination. Example 1: Input: n = 3, edges = [[0,1],[0,2]], source = 0, destination = 2 Output: false Explanation: It is possible to reach and get stuck on both node 1 and node 2. Example 2: Input: n = 4, edges = [[0,1],[0,3],[1,2],[2,1]], source = 0, destination = 3 Output: false Explanation: We have two possibilities: to end at node 3, or to loop over node 1 and node 2 indefinitely. Example 3: Input: n = 4, edges = [[0,1],[0,2],[1,3],[2,3]], source = 0, destination = 3 Output: true Example 4: Input: n = 3, edges = [[0,1],[1,1],[1,2]], source = 0, destination = 2 Output: false Explanation: All paths from the source node end at the destination node, but there are an infinite number of paths, such as 0-1-2, 0-1-1-2, 0-1-1-1-2, 0-1-1-1-1-2, and so on. Example 5: Input: n = 2, edges = [[0,1],[1,1]], source = 0, destination = 1 Output: false Explanation: There is infinite self-loop at destination node. Constraints: 1 <= n <= 104 0 <= edges.length <= 104 edges.length == 2 0 <= ai, bi <= n - 1 0 <= source <= n - 1 0 <= destination <= n - 1 The given graph may have self-loops and parallel edges. */ class Solution { public: // vis = -1 : not visited // vis = 0 : visiting // vis = 1. : visited vector<int> vis; vector<vector<int>> g; bool dfs(int source, int destination) { if(vis[source] == 1) return true; if(vis[source] == 0) return false; if(g[source].empty()) return source == destination; vis[source] = 0; for(auto x : g[source]) { if(!dfs(x, destination)) { return false; } } return vis[source] = 1; } bool leadsToDestination(int n, vector<vector<int>>& edges, int source, int destination) { vis.resize(n, -1); g.resize(n); for(auto e : edges) { if(e[0] == destination) return false; g[e[0]].push_back(e[1]); } return dfs(source, destination); } };
// Copyright 2021 Tier IV, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef PATH_DISTANCE_CALCULATOR_HPP_ #define PATH_DISTANCE_CALCULATOR_HPP_ #include <rclcpp/rclcpp.hpp> #include <tier4_autoware_utils/ros/self_pose_listener.hpp> #include <autoware_auto_planning_msgs/msg/path.hpp> #include <tier4_debug_msgs/msg/float64_stamped.hpp> class PathDistanceCalculator : public rclcpp::Node { public: explicit PathDistanceCalculator(const rclcpp::NodeOptions & options); private: rclcpp::Subscription<autoware_auto_planning_msgs::msg::Path>::SharedPtr sub_path_; rclcpp::Publisher<tier4_debug_msgs::msg::Float64Stamped>::SharedPtr pub_dist_; rclcpp::TimerBase::SharedPtr timer_; tier4_autoware_utils::SelfPoseListener self_pose_listener_; autoware_auto_planning_msgs::msg::Path::SharedPtr path_; }; #endif // PATH_DISTANCE_CALCULATOR_HPP_
// Copyright (c) 2020 The Picacoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <script/picacoinconsensus.h> #include <script/interpreter.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <cstdint> #include <string> #include <vector> FUZZ_TARGET(script_picacoin_consensus) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const std::vector<uint8_t> random_bytes_1 = ConsumeRandomLengthByteVector(fuzzed_data_provider); const std::vector<uint8_t> random_bytes_2 = ConsumeRandomLengthByteVector(fuzzed_data_provider); const CAmount money = ConsumeMoney(fuzzed_data_provider); picacoinconsensus_error err; picacoinconsensus_error* err_p = fuzzed_data_provider.ConsumeBool() ? &err : nullptr; const unsigned int n_in = fuzzed_data_provider.ConsumeIntegral<unsigned int>(); const unsigned int flags = fuzzed_data_provider.ConsumeIntegral<unsigned int>(); assert(picacoinconsensus_version() == PICACOINCONSENSUS_API_VER); if ((flags & SCRIPT_VERIFY_WITNESS) != 0 && (flags & SCRIPT_VERIFY_P2SH) == 0) { return; } (void)picacoinconsensus_verify_script(random_bytes_1.data(), random_bytes_1.size(), random_bytes_2.data(), random_bytes_2.size(), n_in, flags, err_p); (void)picacoinconsensus_verify_script_with_amount(random_bytes_1.data(), random_bytes_1.size(), money, random_bytes_2.data(), random_bytes_2.size(), n_in, flags, err_p); }
#include <bits/stdc++.h> using namespace std; int main() { cin.tie(0)->sync_with_stdio(0); int n, c, m; cin >> n >> c >> m; bitset<101> b; int x; for (int i = 0; i < c; i++) { cin >> x; b[x] = 1; } for (int i = 0; i < m; i++) { cin >> x; if (b[x]) { b[x] = !b[x]; c--; } } cout << c << '\n'; }
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CommunicationWizardBase.h" #include "ContactBkEngine.h" #include "SmsHandlerFactory.h" #include "WFTextUtil.h" #include "GuiProt/AdditionalInfo.h" #include "GuiProt/Favorite.h" #include "GuiProt/GuiProtMess.h" #include "GuiProt/GuiProtFavoriteMess.h" #include "GuiProt/GuiProtMessageSender.h" #include "nav2util.h" #include <algorithm> using namespace isab; const uint8 CCommunicationWizardBase::SmsStringDelimiter = '}'; // the yen-sign in the GSM-character table. CCommunicationWizardBase::CCommunicationWizardBase(class GuiProtMessageSender& aSender) : iSender(aSender) { iWizardData.iContent = EWfCurRoute; iWizardData.iTransmitAs = EWfSMS; iWizardData.iMessage = NULL; iWizardData.iSmsRecipient.Copy(_L(" ")); iWizardData.iEmailRecipient.Copy(_L(" ")); iContactBkEngine = CContactBkEngine::NewL(this); iSmsHandler = SmsHandlerFactory::CreateL(this); } CCommunicationWizardBase::~CCommunicationWizardBase() { delete iWizardData.iMessage; delete iWizardData.iSignature; delete iContactBkEngine; delete iEventGenerator; delete[] iContentMapArray; delete iSmsHandler; if (iContentArray) { iContentArray->Reset(); delete iContentArray; } for (std::vector<isab::GuiFavorite*>::iterator it = iFavVector.begin(); it != iFavVector.end(); it++) { delete *it; } iPersonalMessageIds.Reset(); } void CCommunicationWizardBase::StartWizardL(TWizContent aPreDefinedContent, Favorite* aFavorite) { if (aFavorite) { if (iFavorite) { delete iFavorite; iFavorite = aFavorite; } iFavorite = aFavorite; } iPreDefinedContent = aPreDefinedContent; if (aPreDefinedContent == EWfNotSpecified) { GenerateEvent(EWhatToSend); } else { iWizardData.iContent = aPreDefinedContent; GenerateEvent(EValidateContentChoice); } } void CCommunicationWizardBase::GenerateEvent(enum TWizardSteps aEvent) { if (!iEventGenerator) { iEventGenerator = CCommunicationWizardGenerator::NewL(*this); } iEventGenerator->SendEventL(aEvent); } void CCommunicationWizardBase::HandleGeneratedEventL(TWizardSteps aEvent) { switch(aEvent) { case EWhatToSend: // Dislplay dialog that lets user decide what to send. ShowWhatToSendDialogL(); break; case EValidateContentChoice: // Validate what the user wants to send, this is needed because // when sending a favorite we need to ask for them from the server, // we don't have them stored here. ValidateContentChoiceL(); break; case EGetSelectedFavorite: // Get information from the server about the selected favorite. GetSelectedFavoriteL(); break; case ESendAs: // Dislplay dialog that lets user decide how to send, email or sms. ShowSendAsDialogL(); break; case EHowToAddRecipient: { TWizTransmitAS transmitAs = TWizTransmitAS(iTransmitAsSelection); // if (transmitAs == EWfEmail) { // // We dont want an email adress as recepient if sms is // // was selected and vice versa. // iWizardData.iEmailRecipient.Copy(_L("")); // } iWizardData.iTransmitAs = transmitAs; // Display dialog that lets user decide how to add the recipient, by // entering the phone nbr manually or by using the phone book. ShowHowToAddRecipientDialogL(); } break; case EAddRecipient: if (iHowToAddRecSelection == EFromPhoneBook) { // User wants to add recipient from the phone book, get // all contacts from the phone book. ShowContactBookDialogL(); } else { // Let user enter nbr/email manually. ShowEnterManuallyDialogL(); } break; case EValidateManualInput: { if (iWizardData.iTransmitAs == EWfSMS) { ValidatePhoneNbrL(); } else { ValidateEmailAdressL(); } } break; case EShowSelectedContact: // Store the contact id the user selected and // show that contacts phone numbers. if (iContactSelection < 0) { iContactBkEngine->ClearSearch(); GenerateEvent(EAddRecipient); } else { iContactBkEngine->SetCurrentContact(iContactSelection); ShowContactDetailsDialogL(); } break; case EStoreContactDetail: // Store the selected contact adress. if (iWizardData.iTransmitAs == EWfEmail) { iWizardData.iEmailRecipient = iContentArray->MdcaPoint(iContactDetailSelection); } else { iWizardData.iSmsRecipient = iContentArray->MdcaPoint(iContactDetailSelection); } GenerateEvent(ESubject); break; case ESubject: // XXX Display the standard message, should the user // be allowed to change this?? ShowGenericInfoDialogL(EFormatMessage, EAddRecipient, ESubjectDialog); break; case EFormatMessage: // Format the message to be sent. FormatMessageL(iWizardData.iMessage); GenerateEvent(ESendMessage); break; case EConfirmation: // Display dialog that notifies the user that a // sms/email will be sent. Send message ShowConfirmationDialogL(); break; case ESendMessage: // Send the formated message. SendMessageL(); break; case EQuit: CleanUp(); } } void CCommunicationWizardBase::ValidateContentChoiceL() { if (iPreDefinedContent == EWfNotSpecified) { iWizardData.iContent = TWizContent(iContentMapArray[iContentSelection]); } iWizardData.iPersonalMessageId = iPersonalMessageIds[iWizardData.iContent]; SetSignatureL(); if(iWizardData.iContent == EWfFavorite && !iFavorite) { // User wants to send a favorite, display all the favorite GenericGuiMess message(GuiProtEnums::GET_FAVORITES, uint16(0), uint16(MAX_UINT16)); iSender.SendMessage(message, this); } else { GenerateEvent(ESendAs); } } void CCommunicationWizardBase::ValidatePhoneNbrL() { iWizardData.iSmsRecipient.TrimLeft(); if (IsValidPhoneNumber(iWizardData.iSmsRecipient)) { GenerateEvent(ESubject); } else { ShowGenericInfoDialogL(EAddRecipient, EQuit, ENonValidPhoneNbrDialog); } } void CCommunicationWizardBase::ValidateEmailAdressL() { if (iWizardData.iEmailRecipient.Find(_L("@")) != KErrNotFound) { GenerateEvent(ESubject); } else { ShowGenericInfoDialogL(EAddRecipient, EQuit, ENonValidEmailDialog); } } void CCommunicationWizardBase::ResetContentArray(TUint aNbrIndex) { if (iContentArray && iContentArray->Count() > 0) { iContentArray->Reset(); delete iContentArray; } iContentArray = new CDesCArrayFlat(aNbrIndex); } void CCommunicationWizardBase::GetSelectedFavoriteL() { if(iFavoriteSelection <= (TInt)iFavVector.size()) { GenericGuiMess message(GuiProtEnums::GET_FAVORITE_INFO, iFavVector[iFavoriteSelection]->getID()); iSender.SendMessage(message, this); } } void CCommunicationWizardBase::FormatMessageL(HBufC*& aMessage) { if (aMessage) { delete aMessage; aMessage = NULL; } char* identifier = new (ELeave) char[1024]; // on heap, so allocate more than enough. identifier[0] = '\0'; const TDesC& name = GetCurrentRouteDestinationName(); char* destname = WFTextUtil::newTDesDupL(name); TPoint originPoint = GetOrigin(); TPoint destinationPoint = GetDestination(); TPoint currentPoint = GetCurrentPosition(); TPoint currentMapPos = GetCoordinate(); isab::GuiProtEnums::ObjectType objecttype = isab::GuiProtEnums::invalidObjectType; TInt checkNumCalc = 0; if (iWizardData.iTransmitAs == EWfSMS) { switch (iWizardData.iContent) { case EWfCurRoute: objecttype = isab::GuiProtEnums::RouteMessage; checkNumCalc = (destinationPoint.iY & 0xFF) ^ (destinationPoint.iX & 0xFF) ^ (TInt)'W'; sprintf(identifier, "//SCKL3F6B //WAYFR%i %i %i %i %i %s%c%s%c%s", destinationPoint.iY, destinationPoint.iX, originPoint.iY, originPoint.iX, checkNumCalc, ""/*origin name*/, SmsStringDelimiter, destname, SmsStringDelimiter, iWizardData.iSignature); break; case EWfCurDestination: objecttype = isab::GuiProtEnums::DestinationMessage; checkNumCalc = (destinationPoint.iY & 0xFF) ^ (destinationPoint.iX & 0xFF) ^ (TInt)'W'; sprintf(identifier, "//SCKL3F6B //WAYFDz%i %i %i %s%c%s", destinationPoint.iY, destinationPoint.iX, checkNumCalc, destname, SmsStringDelimiter, iWizardData.iSignature); break; case EWfMapPosition: objecttype = isab::GuiProtEnums::DestinationMessage; checkNumCalc = (currentMapPos.iY & 0xFF) ^ (currentMapPos.iX & 0xFF) ^ (TInt)'W'; const char* desc = GetMapMoverInfoText(); if (desc) { // If the mapmover could return a valid text sprintf(identifier, "//SCKL3F6B //WAYFDz%i %i %i %s%c%s", currentMapPos.iY, currentMapPos.iX, checkNumCalc, desc, SmsStringDelimiter, iWizardData.iSignature); } else { // No text from the mapmover sprintf(identifier, "//SCKL3F6B //WAYFDz%i %i %i %s", currentMapPos.iY, currentMapPos.iX, checkNumCalc, iWizardData.iSignature); } break; case EWfGpsPosition: objecttype = isab::GuiProtEnums::DestinationMessage; checkNumCalc = (currentPoint.iY & 0xFF) ^ (currentPoint.iX & 0xFF) ^ (TInt)'W'; sprintf(identifier, "//SCKL3F6B //WAYFDz%i %i %i %s", currentPoint.iY, currentPoint.iX, checkNumCalc, iWizardData.iSignature); break; case EWfFavorite: { checkNumCalc = (iFavorite->getLat() & 0xFF) ^ (iFavorite->getLon() & 0xFF) ^ (TInt)'W'; // Make description and limit to 255 chars. char* description = new char[ MAX_that_can(iFavorite->getSize(), 256) ]; strcpy(description, iFavorite->getDescription()); Favorite::InfoVect infos = iFavorite->getInfos(); std::sort(infos.begin(), infos.end(), isab::FavoriteInfoCmp()); for (Favorite::InfoVect::const_iterator it = infos.begin(); it != infos.end(); ++it) { if ((*it)->getType() == GuiProtEnums::dont_show) { continue; } if (description[0] != '\0') { strcat(description, ", "); // Used two bytes of type here. } strcat(description, (*it)->getKey()); strcat(description, ": "); // Null-byte for key and value used here (size wise). strcat(description, (*it)->getValue()); } description[ 255 ] = '\0'; sprintf(identifier, "//SCKL3F6B //WAYFF%li %li %i %s%c%s%c%s%c%s%c%s%c%s", iFavorite->getLat(), iFavorite->getLon(), checkNumCalc, iFavorite->getName(), SmsStringDelimiter, iFavorite->getShortName(), SmsStringDelimiter, description, SmsStringDelimiter, iFavorite->getCategory(), SmsStringDelimiter, iFavorite->getMapIconName(), SmsStringDelimiter, iWizardData.iSignature); delete [] description; } break; case EWfNotSpecified: // This should never happen, quit the wizard GenerateEvent(EQuit); break; }; } else { switch (iWizardData.iContent) { case EWfCurRoute: iWizardData.iObjectType = isab::GuiProtEnums::ItineraryMessage; sprintf(identifier, "0x%08x%x", HIGH(GetRouteId()), LOW(GetRouteId())); break; case EWfGpsPosition: iWizardData.iObjectType = isab::GuiProtEnums::PositionMessage; sprintf(identifier, "%i %i %s", currentPoint.iY, currentPoint.iX, ""); break; case EWfMapPosition: iWizardData.iObjectType = isab::GuiProtEnums::PositionMessage; sprintf(identifier, "%i %i %s", currentMapPos.iY, currentMapPos.iX, ""); break; case EWfCurDestination: iWizardData.iObjectType = isab::GuiProtEnums::PositionMessage; sprintf(identifier, "%i %i %s", destinationPoint.iY, destinationPoint.iX, destname); break; case EWfFavorite: if ((iFavorite->getID() != isab::Favorite::INVALID_FAV_ID) && (iFavorite->isSynced())) { // synchronized favorite iWizardData.iObjectType = isab::GuiProtEnums::DestinationMessage; sprintf(identifier, "%lu", iFavorite->getID()); } else { // unsynchronized favorite iWizardData.iObjectType = isab::GuiProtEnums::PositionMessage; // try to get a name const char* name = iFavorite->getName(); if (!name || (strlen(name) == 0)) { name = iFavorite->getShortName(); } if (!name || (strlen(name) == 0)) { name = iFavorite->getDescription(); } if (!name) { name = ""; // at least a valid pointer to avoid crashing on sprintf. } sprintf(identifier, "%li %li %s", iFavorite->getLat(), iFavorite->getLon(), name); } break; case EWfNotSpecified: // This should never happen, quit the wizard GenerateEvent(EQuit); break; }; } aMessage = WFTextUtil::AllocL(identifier); delete identifier; } void CCommunicationWizardBase::SendMessageL() { if(iWizardData.iTransmitAs == EWfSMS) { SmsAboutToBeSent(); // Send sms #ifdef __WINS__ iSmsHandler->CreateLocalMessageL(*iWizardData.iMessage, iWizardData.iSmsRecipient); #else iSmsHandler->SendSmsL(*iWizardData.iMessage, iWizardData.iSmsRecipient); #endif } else { char* emailSender = isab::strdup_new("please_dont_reply@somemailaddresshereTODO"); isab::SendMessageMess* message = new (ELeave) isab::SendMessageMess(isab::GuiProtEnums::HTML_email, iWizardData.iObjectType, WFTextUtil::newTDesDupL(*iWizardData.iMessage), emailSender, WFTextUtil::newTDesDupL(iWizardData.iEmailRecipient), iWizardData.iSignature); SendMessageL(message); } } void CCommunicationWizardBase::CleanUp() { delete iFavorite; iFavorite = NULL; iContactBkEngine->ClearSearch(); } void CCommunicationWizardBase::ContactBkSearchDone(TInt aError) { ShowContactBookDialogL(); } void CCommunicationWizardBase::ContactBkInUse() { ShowGenericInfoDialogL(EWhatToSend, EQuit, EContactBookBusyDialog); } void CCommunicationWizardBase::SmsSent(TInt aStatus, TInt aCount, TInt aNbrSent) { ShowSmsSentDialogL(aStatus, aCount, aNbrSent); } void CCommunicationWizardBase::SmsReceived(class CSmsParser* aSmsParser, TInt32 aMsvId) { } bool CCommunicationWizardBase::GuiProtReceiveMessage(isab::GuiProtMess* mess) { if (mess->getMessageType() == isab::GuiProtEnums::GET_FAVORITES_REPLY) { ShowFavoriteListL((GetFavoritesReplyMess*)mess); return true; } else if (mess->getMessageType() == isab::GuiProtEnums::GET_FAVORITE_INFO_REPLY) { // Got all info about a favorite, store and use when sending the sms/email if (iFavorite) { delete iFavorite; iFavorite = NULL; } GetFavoriteInfoReplyMess* replyMess = (GetFavoriteInfoReplyMess*)mess; iFavorite = new Favorite(*replyMess->getFavorite()); GenerateEvent(ESendAs); return true; } return false; }
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018 www.open3d.org // // 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 "open3d/visualization/shader/TextureSimpleShader.h" #include "open3d/geometry/TriangleMesh.h" #include "open3d/visualization/shader/Shader.h" #include "open3d/visualization/utility/ColorMap.h" namespace open3d { namespace visualization { namespace glsl { bool TextureSimpleShader::Compile() { if (!CompileShaders(TextureSimpleVertexShader, NULL, TextureSimpleFragmentShader)) { PrintShaderWarning("Compiling shaders failed."); return false; } vertex_position_ = glGetAttribLocation(program_, "vertex_position"); vertex_uv_ = glGetAttribLocation(program_, "vertex_uv"); texture_ = glGetUniformLocation(program_, "diffuse_texture"); MVP_ = glGetUniformLocation(program_, "MVP"); return true; } void TextureSimpleShader::Release() { UnbindGeometry(); ReleaseProgram(); } bool TextureSimpleShader::BindGeometry(const geometry::Geometry &geometry, const RenderOption &option, const ViewControl &view) { // If there is already geometry, we first unbind it. // We use GL_STATIC_DRAW. When geometry changes, we clear buffers and // rebind the geometry. Note that this approach is slow. If the geometry is // changing per frame, consider implementing a new ShaderWrapper using // GL_STREAM_DRAW, and replace InvalidateGeometry() with Buffer Object // Streaming mechanisms. UnbindGeometry(); // Prepare data to be passed to GPU std::vector<Eigen::Vector3f> points; std::vector<Eigen::Vector2f> uvs; if (!PrepareBinding(geometry, option, view, points, uvs)) { PrintShaderWarning("Binding failed when preparing data."); return false; } // Create buffers and bind the geometry for (int mi = 0; mi < num_materials_; ++mi) { glGenBuffers(1, &vertex_position_buffers_[mi]); glBindBuffer(GL_ARRAY_BUFFER, vertex_position_buffers_[mi]); glBufferData(GL_ARRAY_BUFFER, draw_array_sizes_[mi] * sizeof(Eigen::Vector3f), points.data() + array_offsets_[mi], GL_STATIC_DRAW); glGenBuffers(1, &vertex_uv_buffers_[mi]); glBindBuffer(GL_ARRAY_BUFFER, vertex_uv_buffers_[mi]); glBufferData(GL_ARRAY_BUFFER, draw_array_sizes_[mi] * sizeof(Eigen::Vector2f), uvs.data() + array_offsets_[mi], GL_STATIC_DRAW); } bound_ = true; return true; } bool TextureSimpleShader::RenderGeometry(const geometry::Geometry &geometry, const RenderOption &option, const ViewControl &view) { if (!PrepareRendering(geometry, option, view)) { PrintShaderWarning("Rendering failed during preparation."); return false; } glUseProgram(program_); for (int mi = 0; mi < num_materials_; ++mi) { glUniformMatrix4fv(MVP_, 1, GL_FALSE, view.GetMVPMatrix().data()); glUniform1i(texture_, 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture_buffers_[mi]); glEnableVertexAttribArray(vertex_position_); glBindBuffer(GL_ARRAY_BUFFER, vertex_position_buffers_[mi]); glVertexAttribPointer(vertex_position_, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray(vertex_uv_); glBindBuffer(GL_ARRAY_BUFFER, vertex_uv_buffers_[mi]); glVertexAttribPointer(vertex_uv_, 2, GL_FLOAT, GL_FALSE, 0, NULL); glDrawArrays(draw_arrays_mode_, 0, draw_array_sizes_[mi]); glDisableVertexAttribArray(vertex_position_); glDisableVertexAttribArray(vertex_uv_); glBindTexture(GL_TEXTURE_2D, 0); } return true; } void TextureSimpleShader::UnbindGeometry() { if (bound_) { for (auto buf : vertex_position_buffers_) { glDeleteBuffers(1, &buf); } for (auto buf : vertex_uv_buffers_) { glDeleteBuffers(1, &buf); } for (auto buf : texture_buffers_) { glDeleteTextures(1, &buf); } vertex_position_buffers_.clear(); vertex_uv_buffers_.clear(); texture_buffers_.clear(); draw_array_sizes_.clear(); array_offsets_.clear(); num_materials_ = 0; bound_ = false; } } bool TextureSimpleShaderForTriangleMesh::PrepareRendering( const geometry::Geometry &geometry, const RenderOption &option, const ViewControl &view) { if (geometry.GetGeometryType() != geometry::Geometry::GeometryType::TriangleMesh && geometry.GetGeometryType() != geometry::Geometry::GeometryType::HalfEdgeTriangleMesh) { PrintShaderWarning("Rendering type is not geometry::TriangleMesh."); return false; } if (option.mesh_show_back_face_) { glDisable(GL_CULL_FACE); } else { glEnable(GL_CULL_FACE); } glEnable(GL_DEPTH_TEST); glDepthFunc(GLenum(option.GetGLDepthFunc())); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); if (option.mesh_show_wireframe_) { glEnable(GL_POLYGON_OFFSET_FILL); glPolygonOffset(1.0, 1.0); } else { glDisable(GL_POLYGON_OFFSET_FILL); } return true; } bool TextureSimpleShaderForTriangleMesh::PrepareBinding( const geometry::Geometry &geometry, const RenderOption &option, const ViewControl &view, std::vector<Eigen::Vector3f> &points, std::vector<Eigen::Vector2f> &uvs) { if (geometry.GetGeometryType() != geometry::Geometry::GeometryType::TriangleMesh && geometry.GetGeometryType() != geometry::Geometry::GeometryType::HalfEdgeTriangleMesh) { PrintShaderWarning("Rendering type is not geometry::TriangleMesh."); return false; } const geometry::TriangleMesh &mesh = (const geometry::TriangleMesh &)geometry; if (!mesh.HasTriangles()) { PrintShaderWarning("Binding failed with empty triangle mesh."); return false; } std::vector<std::vector<Eigen::Vector3f>> tmp_points; std::vector<std::vector<Eigen::Vector2f>> tmp_uvs; num_materials_ = (int)mesh.textures_.size(); array_offsets_.resize(num_materials_); draw_array_sizes_.resize(num_materials_); vertex_position_buffers_.resize(num_materials_); vertex_uv_buffers_.resize(num_materials_); texture_buffers_.resize(num_materials_); tmp_points.resize(num_materials_); tmp_uvs.resize(num_materials_); // Bind vertices and uvs per material for (size_t i = 0; i < mesh.triangles_.size(); i++) { const auto &triangle = mesh.triangles_[i]; int mi = mesh.triangle_material_ids_[i]; for (size_t j = 0; j < 3; j++) { size_t idx = i * 3 + j; size_t vi = triangle(j); tmp_points[mi].push_back(mesh.vertices_[vi].cast<float>()); tmp_uvs[mi].push_back(mesh.triangle_uvs_[idx].cast<float>()); } } // Bind textures for (int mi = 0; mi < num_materials_; ++mi) { glGenTextures(1, &texture_buffers_[mi]); glBindTexture(GL_TEXTURE_2D, texture_buffers_[mi]); GLenum format, type; auto it = GLHelper::texture_format_map_.find( mesh.textures_[mi].num_of_channels_); if (it == GLHelper::texture_format_map_.end()) { utility::LogWarning("Unknown texture format, abort!"); return false; } format = it->second; it = GLHelper::texture_type_map_.find( mesh.textures_[mi].bytes_per_channel_); if (it == GLHelper::texture_type_map_.end()) { utility::LogWarning("Unknown texture type, abort!"); return false; } type = it->second; glTexImage2D(GL_TEXTURE_2D, 0, format, mesh.textures_[mi].width_, mesh.textures_[mi].height_, 0, format, type, mesh.textures_[mi].data_.data()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } // Point seperations array_offsets_[0] = 0; draw_array_sizes_[0] = static_cast<int>(tmp_points[0].size()); for (int mi = 1; mi < num_materials_; ++mi) { draw_array_sizes_[mi] = static_cast<int>(tmp_points[mi].size()); array_offsets_[mi] = array_offsets_[mi - 1] + draw_array_sizes_[mi - 1]; } // Prepared chunk of points and uvs points.clear(); uvs.clear(); for (int mi = 0; mi < num_materials_; ++mi) { points.insert(points.end(), tmp_points[mi].begin(), tmp_points[mi].end()); uvs.insert(uvs.end(), tmp_uvs[mi].begin(), tmp_uvs[mi].end()); } draw_arrays_mode_ = GL_TRIANGLES; return true; } } // namespace glsl } // namespace visualization } // namespace open3d
// Copyright (c) 2018 The PIVX Core Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "masternode-budget.h" #include "tinyformat.h" #include "utilmoneystr.h" #include "test_concrete.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(budget_tests, TestingSetup) void CheckBudgetValue(int nHeight, std::string strNetwork, CAmount nExpectedValue) { CBudgetManager budget; CAmount nBudget = budget.GetTotalBudget(nHeight); std::string strError = strprintf("Budget is not as expected for %s. Result: %s, Expected: %s", strNetwork, FormatMoney(nBudget), FormatMoney(nExpectedValue)); BOOST_CHECK_MESSAGE(nBudget == nExpectedValue, strError); } BOOST_AUTO_TEST_CASE(budget_value) { SelectParams(CBaseChainParams::TESTNET); int nHeightTest = Params().GetConsensus().height_start_ZC_SerialsV2 + 1; CheckBudgetValue(nHeightTest, "testnet", 7300*COIN); SelectParams(CBaseChainParams::MAIN); nHeightTest = Params().GetConsensus().height_start_ZC_SerialsV2 + 1; CheckBudgetValue(nHeightTest, "mainnet", 43200*COIN); } BOOST_AUTO_TEST_SUITE_END()
#include "../inc/MacierzKw.h" //KONSTRUNKTORY template<class TYP, int ROZMIAR> MacierzKw<TYP,ROZMIAR>::MacierzKw() { for(int i=0;i<ROZMIAR;i++) { this->tab[i]=Wektor<TYP,ROZMIAR>(); } } template<class TYP, int ROZMIAR> MacierzKw<TYP,ROZMIAR>::MacierzKw(Wektor<TYP,ROZMIAR> *w) //dla tablic wektorów mniejszych niz ROZMIAR-elementowych segmentation fault { for(int i=0;i<ROZMIAR;i++) { this->tab[i]=w[i]; } } /* MacierzKw::MacierzKw(double a11,double a12,double a13, double a21,double a22,double a23, double a31,double a32,double a33) { this->tab[0][0]=a11; this->tab[0][1]=a12; this->tab[0][2]=a13; this->tab[1][0]=a21; this->tab[1][1]=a22; this->tab[1][2]=a23; this->tab[2][0]=a31; this->tab[2][1]=a32; this->tab[2][2]=a33; } MacierzKw::MacierzKw(Wektor a1, Wektor a2, Wektor a3) { this->tab[0]=a1; this->tab[1]=a2; this->tab[2]=a3; } */ //OPERATORY template<class TYP, int ROZMIAR> const Wektor<TYP,ROZMIAR> MacierzKw<TYP,ROZMIAR>::operator *(const Wektor<TYP,ROZMIAR> &W)const { Wektor<TYP,ROZMIAR> tmp; TYP tmp2; tmp2=0; for(int i=0;i<ROZMIAR;i++) { for(int j=0;j<ROZMIAR;j++) { tmp2=tmp2+this->tab[i][j]*W[j]; } tmp[i]=tmp2; tmp2=0; //tmp[i]=this->tab[i][0]*W[0]+this->tab[i][1]*W[1]+this->tab[i][2]*W[2]; } return tmp; } template<class TYP, int ROZMIAR> const MacierzKw<TYP,ROZMIAR> MacierzKw<TYP,ROZMIAR>::operator *(const MacierzKw<TYP,ROZMIAR> &W)const { MacierzKw<TYP,ROZMIAR> tmp; TYP tmp2; tmp2 = 0; for(int i=0;i<ROZMIAR;i++) { for(int j=0; j<ROZMIAR;j++) { for(int k=0;k<ROZMIAR;k++) { tmp2=tmp2+this->tab[j][k]*W[k][i]; } tmp[j][i] = tmp2; tmp2 = 0; //tmp[i][j] = this->tab[j][0]*W[0][i]+this->tab[j][1]*W[1][i]+this->tab[j][2]*W[2][i]; } } return tmp; } template<class TYP, int ROZMIAR> const MacierzKw<TYP,ROZMIAR> MacierzKw<TYP,ROZMIAR>::operator +(const MacierzKw<TYP,ROZMIAR> &W)const { MacierzKw<TYP,ROZMIAR> tmp; for(int i=0;i<ROZMIAR;i++) { for(int j=0;j<ROZMIAR;j++) { tmp[i][j]=this->tab[i][j]+W[i][j]; } } return tmp; } template<class TYP, int ROZMIAR> const MacierzKw<TYP,ROZMIAR> MacierzKw<TYP,ROZMIAR>::operator -(const MacierzKw<TYP,ROZMIAR> &W)const { MacierzKw<TYP,ROZMIAR> tmp; for(int i=0;i<ROZMIAR;i++) { for(int j=0;j<ROZMIAR;j++) { tmp[i][j]=this->tab[i][j]-W[i][j]; } } return tmp; } template<class TYP, int ROZMIAR> const MacierzKw<TYP,ROZMIAR> MacierzKw<TYP,ROZMIAR>::operator *(const TYP l)const { MacierzKw<TYP,ROZMIAR> tmp; for(int i=0;i<ROZMIAR;i++) { for(int j=0;j<ROZMIAR;j++) { tmp[i][j]=this->tab[i][j]*l; } } return tmp; } template<class TYP, int ROZMIAR> bool MacierzKw<TYP,ROZMIAR>::operator == (const MacierzKw<TYP,ROZMIAR> &W2) const { bool tmp = true; for(int i=0;i<ROZMIAR;i++) { if(this->tab[i]!=W2[i]) { tmp=false; } } return tmp; } template<class TYP, int ROZMIAR> bool MacierzKw<TYP,ROZMIAR>::operator!=(const MacierzKw<TYP,ROZMIAR> &W2) const { return !(*this==W2); } //SETTERY I GETTERY template<class TYP, int ROZMIAR> const Wektor<TYP,ROZMIAR> & MacierzKw<TYP,ROZMIAR>::operator[](int index) const { return this->tab[index]; } template<class TYP, int ROZMIAR> Wektor<TYP,ROZMIAR> & MacierzKw<TYP,ROZMIAR>::operator[] (int index) { if(index<0||index>=ROZMIAR) { std::cerr<<"Poza zakresem"<<std::endl; exit(4); } return this->tab[index]; } //POZOSTALE FUNKCJE template<class TYP, int ROZMIAR> const MacierzKw<TYP,ROZMIAR> MacierzKw<TYP,ROZMIAR>::transponowane() const { MacierzKw<TYP,ROZMIAR> tmp; for(int i=0;i<ROZMIAR;i++) { for(int j=0;j<ROZMIAR;j++) { tmp[i][j]=this->tab[j][i]; } } return tmp; } template<class TYP, int ROZMIAR> void zamien(Wektor<TYP,ROZMIAR> &w1, Wektor<TYP,ROZMIAR> &w2) { Wektor<TYP,ROZMIAR> tmp=w1; w1=w2; w2=tmp; } template<class TYP, int ROZMIAR> void MacierzKw<TYP,ROZMIAR>::transponuj() { for(int i=0;i<ROZMIAR;i++) { for(int j=i;j<ROZMIAR;j++) { if(i!=j) { std::swap(this->tab[i][j],this->tab[j][i]); } } } } template<class TYP, int ROZMIAR> TYP MacierzKw<TYP,ROZMIAR>::wyznacznik(Metoda met) const { switch(met) { case Laplace: //DO ZROBIENIA REKURENCYJNIE KIEDY BEDZIEMY OBSLUGIWALI ROZNE ROZMIARY MACIERZY KWADRATOWYCH, TERAZ NIE MA SEMSU break; case Gauss: { //nawias sprawia ze zmienne ponizej istnieja tylko w tym przypadku MacierzKw<TYP,ROZMIAR> tmp=*this; //pomocnicza macierz do operacji na wierszach potrzebnych w metodzie Gaussa int iloscZamian=0; //ilosc zmian wierszy sugerujaca jaki znak ma wyznacznik TYP iloraz; //iloraz komorki ktora chcemy wyzerowac przez te ktorej wyzerowac nie chcemy TYP wyzn; wyzn=1; //1 poniewaz to element neutralny mnozenia, a pozniej bedziemy mnozyc przez wartosci na przekatnej for(int i=0;i<ROZMIAR;i++) { if(tmp[i][i]==0) //gdyby pierwszy wiersz zaczynal sie od zera, to niemozliwy jest iloczyn np w2/w1 ,etc. { double nr_wiersza=i; //zmienna istniejaca tylko jezeli pojawil sie powyzszy problem, pomocna przy szukaniu wiersza do zamiany TYP wartosc_pocz; //zmienna przechowujaca wartosc komorki w kolumnie w ktorej szukamy komorek niezerowych ponizej badanego wiersza while(wartosc_pocz==0) //To przyrównanie do 0 będzie problematyczne (przez niedokladnosc double) { if(nr_wiersza+1>=ROZMIAR) //gdy na przekatnej macierzy trojkatnej znajdzie sie zero wyznacznik jest rowny 0 return wyzn*0; //nieeleganckie wartosc_pocz=tmp[++nr_wiersza][i]; } zamien(tmp[i],tmp[nr_wiersza]); iloscZamian++; } for(int j=i+1;j<ROZMIAR;j++) { iloraz=tmp[j][i]/tmp[i][i]; tmp[j]=tmp[j]-tmp[i]*iloraz; } } for(int i=0;i<ROZMIAR;i++) { wyzn=wyzn*tmp[i][i]; //przeliczanie wartosci wyznacznika bez uwzglednienia ilosci zamian } if(iloscZamian%2==0) //uwzglednienie ilosci zamian return wyzn; else return wyzn*(-1); } break; case Sarrus: if(ROZMIAR>3) { std::cout<<"Metoda Sarrusa niemozliwa dla macierzy wiekszej niz 3x3, korzystam z metody Gaussa\n"; wyznacznik(Gauss); } else if(ROZMIAR==0) //nigdy nie powinno sie zdarzyc { TYP a; //nieeleganckie obejscie dla LZesolona a = 0; return a; } else if(ROZMIAR==1) //To też nigdy nie powinno sie zdarzyc { return this->tab[0][0]; } else if(ROZMIAR==2) { return (this->tab[0][0]*this->tab[1][1]-this->tab[1][0]*this->tab[0][1]); } else if(ROZMIAR==3) { return (this->tab[0][0]*this->tab[1][1]*this->tab[2][2]+ this->tab[0][1]*this->tab[1][2]*this->tab[2][0]+ this->tab[0][2]*this->tab[1][0]*this->tab[2][1]- this->tab[0][2]*this->tab[1][1]*this->tab[2][0]- this->tab[1][2]*this->tab[2][1]*this->tab[0][0]- this->tab[2][2]*this->tab[0][1]*this->tab[1][0]); } else { std::cerr<<"Rozmiar macierzy ujemny\n"; exit(5); } break; } } template<class TYP, int ROZMIAR> TYP MacierzKw<TYP,ROZMIAR>::wyznacznik() const { return wyznacznik(Sarrus); } template<class TYP, int ROZMIAR> TYP MacierzKw<TYP,ROZMIAR>::dopelnienieAlgebraiczne(int i, int j) const { MacierzKw<TYP,ROZMIAR-1> macierzTmp; short napotkano_i=0,napotkano_j=0; for(int k=0;k<ROZMIAR-1;k++) { if(k==i) napotkano_i=1; for(int l=0;l<ROZMIAR-1;l++) { if(l==j) napotkano_j=1; macierzTmp[l][k]=this->tab[k+napotkano_i][l+napotkano_j]; } napotkano_j=0; } //std::cout<<"\n\n\n"<<macierzTmp<<"\n\n\n"; if((i+j)%2==0) return macierzTmp.wyznacznik(); else return macierzTmp.wyznacznik()*(-1); } template<class TYP, int ROZMIAR> const MacierzKw<TYP,ROZMIAR> MacierzKw<TYP,ROZMIAR>::macierzDopelnien() const { MacierzKw<TYP,ROZMIAR> tmp; for(int i=0;i<ROZMIAR;i++) { for(int j=0;j<ROZMIAR;j++) { tmp[i][j]=dopelnienieAlgebraiczne(i,j); } } return tmp; } template<class TYP, int ROZMIAR> const MacierzKw<TYP,ROZMIAR> MacierzKw<TYP,ROZMIAR>::odwrotnosc() const { MacierzKw<TYP,ROZMIAR> tmp; tmp=this->macierzDopelnien(); tmp.transponuj(); tmp=tmp*(1/this->wyznacznik()); return tmp; } template<class TYP, int ROZMIAR> void MacierzKw<TYP,ROZMIAR>::odwroc() { //TYP tmp=1/this->wyznacznik(); *this=this->macierzDopelnien(); this->transponuj(); *this=*this*(1/this->wyznacznik()); } template<class TYP, int ROZMIAR> std::ostream & operator <<(std::ostream &strm, const MacierzKw<TYP,ROZMIAR> &W) { for(int i=0;i<ROZMIAR;i++) { strm<<W[i]<<"\n"; } return strm; } template<class TYP, int ROZMIAR> std::istream & operator >>(std::istream &strm, MacierzKw<TYP,ROZMIAR> &W) { for(int i=0;i<ROZMIAR;i++) { strm>>W[i]; } return strm; }
// Copyright 2020 Google LLC // // 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 "perception/linux_syscalls/clone3.h" #include "perception/debug.h" namespace perception { namespace linux_syscalls { long clone3() { perception::DebugPrinterSingleton << "System call clone3 is unimplemented.\n"; return 0; } } }
//! //! @author Yue Wang //! @date 01.12.2014 //! //! Exercise 10.3: //! Use accumulate to sum the elements in a vector<int>. //! //! Exercise 10.4: //! Assuming v is a vector<double>, what, if anything, //! is wrong with calling accumulate(v.cbegin(), v.cend(), 0)? // Check below. //! #include <iostream> #include <string> #include <vector> #include <algorithm> #include <numeric> int main() { //! Exercise 10.3 std::vector<int> v = {1,2,3,4}; std::cout << "ex 10.03: " << std::accumulate(v.cbegin(), v.cend(), 0) << std::endl; //! Exercise 10.4 std::vector<double> vd = {1.1, 0.5, 3.3}; std::cout << "ex 10.04: " << std::accumulate(vd.cbegin(), vd.cend(), 0) << std::endl; //! ^<-- note here. //! @attention //! //! The ouput is 4 rather than 4.9 as expected. //! The reason is std::accumulate is a template function. The third parameter is _Tp __init //! When "0" , an integer, had been specified here, the compiler deduced _Tp as //! interger.As a result ,when the following statments were being excuted : // for (; __first != __last; ++__first) // __init = __init + *__first; // return __init; //! all calculation would be converted to integer. return 0; } //! output //! //ex 10.03: 10 //ex 10.04: 4
#include <cstring> #include <cerrno> #include <iostream> #include <string> #include <csignal> #include <unordered_map> #include <vector> #include <memory> #include <cstdint> #include <sys/time.h> #include <sys/socket.h> #include <fcntl.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <unistd.h> #include <netdb.h> #include "IPAddress.h" #include "TCPConnection.h" #include "ILogger.h" #include "StdioLoggerFactory.h" #include "IMessage.h" #include "MessageBroker.h" #include "ShutdownHandler.h" #include "LoopbackTester.h" #include "TestWorker.h" static void usage(const std::string &self) { std::cerr<<"Usage: "<<self<<" [parameters]"<<std::endl; std::cerr<<" mandatory parameters:"<<std::endl; std::cerr<<" -pc <count> UART port count"<<std::endl; std::cerr<<" -lp{n} <port> TCP ports UARTClient util is listening at"<<std::endl; std::cerr<<" -tsz <bytes> test block size, default: 4096 bytes"<<std::endl; std::cerr<<" -tto <ms> timeout for sending the whole block, and for receiving answer, default: 5000 ms"<<std::endl; std::cerr<<" experimental and optimization parameters:"<<std::endl; std::cerr<<" -pt <time, ms> pause (msec) before starting up tests"<<std::endl; std::cerr<<" -bsz <bytes> size of TCP buffer used for transferring data, default: 64k"<<std::endl; std::cerr<<" -mt <time, ms> management interval used for some internal routines, default: 500"<<std::endl; std::cerr<<" -cf <seconds> timeout for flushing data when closing sockets, -1 to disable, 0 - close without flushing, default: 30"<<std::endl; } static int param_error(const std::string &self, const std::string &message) { std::cerr<<message<<std::endl; usage(self); return 1; } static void TuneSocketBaseParams(std::shared_ptr<ILogger> &logger, int fd, const int lingerTime,const int tcpBuffSize) { //set linger linger cLinger={0,0}; cLinger.l_onoff=lingerTime>=0; cLinger.l_linger=cLinger.l_onoff?lingerTime:0; if (setsockopt(fd, SOL_SOCKET, SO_LINGER, &cLinger, sizeof(linger))!=0) logger->Warning()<<"Failed to set SO_LINGER option to socket: "<<strerror(errno); //set buffer size auto bsz=tcpBuffSize; if(setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &bsz, sizeof(bsz))) logger->Warning()<<"Failed to set SO_SNDBUF option to socket: "<<strerror(errno); bsz=tcpBuffSize; if(setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &bsz, sizeof(bsz))) logger->Warning()<<"Failed to set SO_RCVBUF option to socket: "<<strerror(errno); int tcpNoDelay=1; if(setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &tcpNoDelay, sizeof(tcpNoDelay))) logger->Warning()<<"Failed to set TCP_NODELAY option to socket: "<<strerror(errno); int tcpQuickAck=1; if(setsockopt(fd, IPPROTO_TCP, TCP_QUICKACK, &tcpQuickAck, sizeof(tcpQuickAck))) logger->Warning()<<"Failed to set TCP_QUICKACK option to socket: "<<strerror(errno); } static void SetSocketCustomTimeouts(std::shared_ptr<ILogger> &logger, int fd, const timeval &tv) { timeval rtv=tv; if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &rtv, sizeof(rtv))!=0) logger->Warning()<<"Failed to set SO_RCVTIMEO option to socket: "<<strerror(errno); timeval stv=tv; if (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &stv, sizeof(stv))!=0) logger->Warning()<<"Failed to set SO_SNDTIMEO option to socket: "<<strerror(errno); } int main (int argc, char *argv[]) { //timeout for main thread waiting for external signals const timespec sigTs={2,0}; std::unordered_map<std::string,std::string> args; bool isArgValue=false; for(auto i=1;i<argc;++i) { if(isArgValue) { args[argv[i-1]]=argv[i]; isArgValue=false; continue; } if(std::string(argv[i]).length()<2||std::string(argv[i]).front()!='-') { std::cerr<<"Invalid cmdline argument: "<<argv[i]<<std::endl; usage(argv[0]); return 1; } isArgValue=true; } if(args.empty()) return param_error(argv[0],"Mandatory parameters are missing!"); int pause=1000; if(args.find("-pt")!=args.end()) { auto pt=std::atoi(args["-pt"].c_str()); if(pt<0||pt>60000) return param_error(argv[0],"pause time is invalid"); pause=pt; } size_t portCount=0; if(args.find("-pc")!=args.end()) { auto pc=std::atoi(args["-pc"].c_str()); if(pc<1||pc>32) return param_error(argv[0],"port count value is invalid"); portCount=static_cast<size_t>(pc); } else return param_error(argv[0],"port count must be provided"); std::vector<int> localPorts; std::vector<std::string> localFiles; while(args.find("-lp"+std::to_string(localPorts.size()+1))!=args.end()) { auto sockFile=args["-lp"+std::to_string(localPorts.size()+1)]; auto port=std::atoi(sockFile.c_str()); if(port<1||port>65535) port=0; else sockFile=""; localPorts.push_back(port); localFiles.push_back(sockFile); } if(localPorts.size()<portCount) return param_error(argv[0],"local ports count must be equals to remote ports count"); //tcp buff size int tcpBuffSize=65536; if(args.find("-bsz")!=args.end()) { auto bsz=std::atoi(args["-bsz"].c_str()); if(bsz<128||bsz>524288) return param_error(argv[0],"TCP buffer size is invalid"); tcpBuffSize=bsz; } //management interval int mgInterval=500; if(args.find("-mt")!=args.end()) { int cnt=std::atoi(args["-mt"].c_str()); if(cnt<100 || cnt>10000) return param_error(argv[0],"workers management interval is invalid!"); mgInterval=cnt; } //linger int linger=30; if(args.find("-cf")!=args.end()) { auto time=std::atoi(args["-cf"].c_str()); if(time<-1||time>600) return param_error(argv[0],"Flush timeout value is invalid"); linger=time; } int testBlockSize=4096; if(args.find("-tsz")!=args.end()) { auto bsz=std::atoi(args["-tsz"].c_str()); if(bsz<1||bsz>1000000000) return param_error(argv[0],"Test block size is invalid"); testBlockSize=bsz; } int testTimeout=5000; if(args.find("-tto")!=args.end()) { auto to=std::atoi(args["-tto"].c_str()); if(to<1||to>3600000) return param_error(argv[0],"Test timeout is too big"); testTimeout=to; } StdioLoggerFactory logFactory; auto mainLogger=logFactory.CreateLogger("Main"); auto messageBrokerLogger=logFactory.CreateLogger("MSGBroker"); //configure the most essential stuff MessageBroker messageBroker(messageBrokerLogger); //shutdown handler ShutdownHandler shutdownHandler; messageBroker.AddSubscriber(shutdownHandler); //create sigset_t struct with signals sigset_t sigset; sigemptyset(&sigset); if(sigaddset(&sigset,SIGHUP)!=0||sigaddset(&sigset,SIGTERM)!=0||sigaddset(&sigset,SIGUSR1)!=0||sigaddset(&sigset,SIGUSR2)!=0||sigaddset(&sigset,SIGPIPE)!=0||pthread_sigmask(SIG_BLOCK,&sigset,nullptr)!=0) { mainLogger->Error()<<"Failed to setup signal-handling"<<std::endl; return 1; } std::vector<std::shared_ptr<LoopbackTester>> lbTesters; std::vector<std::shared_ptr<TestWorker>> testWorkers; //create target connections std::vector<std::shared_ptr<Connection>> connections; for(auto const& port: localPorts) { //create socket auto fd=socket(AF_INET,SOCK_STREAM,0); if(fd<0) { mainLogger->Error()<<"Failed to create new socket: "<<strerror(errno); return 1; } TuneSocketBaseParams(mainLogger,fd,linger,tcpBuffSize); auto interval=timeval{mgInterval/1000,(mgInterval-mgInterval/1000*1000)*1000}; SetSocketCustomTimeouts(mainLogger,fd,interval); int cr=-1; sockaddr_in v4sa={}; IPAddress("127.0.0.1").ToSA(&v4sa); v4sa.sin_port=htons(static_cast<uint16_t>(port)); cr=connect(fd,reinterpret_cast<sockaddr*>(&v4sa), sizeof(v4sa)); if(cr<0) { mainLogger->Error()<<"Failed to connect: "<<strerror(errno); if(close(fd)!=0) { mainLogger->Error()<<"Failed to perform proper socket close after connection failure: "<<strerror(errno); return 1; } return 1; } auto target=std::make_shared<TCPConnection>(fd,static_cast<uint16_t>(port)); auto lbLogger=logFactory.CreateLogger("Test:"+std::to_string(port)); auto twLogger=logFactory.CreateLogger("TestWorker:"+std::to_string(port)); auto lbTester=std::make_shared<LoopbackTester>(lbLogger,*(target.get()),testBlockSize,testTimeout,pause); auto tWorker=std::make_shared<TestWorker>(twLogger,*(lbTester.get())); lbTesters.push_back(lbTester); testWorkers.push_back(tWorker); connections.push_back(target); } //startup mainLogger->Info()<<"Test starting-up"<<std::endl; for(auto const& tester:lbTesters) tester->Startup(); for(auto const& worker:testWorkers) worker->Startup(); //main loop, awaiting for signal while(true) { auto signal=sigtimedwait(&sigset,nullptr,&sigTs); auto error=errno; if(signal<0 && error!=EAGAIN && error!=EINTR) { mainLogger->Error()<<"Error while handling incoming signal: "<<strerror(error)<<std::endl; break; } else if(signal>0 && signal!=SIGUSR2 && signal!=SIGINT) //SIGUSR2 triggered by shutdownhandler to unblock sigtimedwait { mainLogger->Info()<< "Pending shutdown by receiving signal: "<<signal<<"->"<<strsignal(signal)<<std::endl; break; } if(shutdownHandler.IsShutdownRequested()) { if(shutdownHandler.GetEC()!=0) mainLogger->Error() << "One of background worker was failed, shuting down" << std::endl; else mainLogger->Info() << "Shuting down gracefully by request from background worker" << std::endl; break; } } //request shutdown of background workers for(auto const& worker:testWorkers) worker->RequestShutdown(); for(auto const& tester:lbTesters) tester->RequestShutdown(); //wait for background workers shutdown complete for(auto const& worker:testWorkers) worker->Shutdown(); for(auto const& tester:lbTesters) tester->Shutdown(); mainLogger->Info()<<"Clean shutdown"<<std::endl; return 0; }
// MIT Licensed (see LICENSE.md). #include "Precompiled.hpp" namespace Zilch { // To simplify our parsing, we work with generic nodes (and only specific nodes // in specific cases) Because of this, we need to ensure that the sizes always // match static_assert(sizeof(GrammarNode<Character>) == sizeof(GrammarNode<Token>), "The sizes of the grammar nodes do not match"); DataDrivenLexerShared::DataDrivenLexerShared() { GrammarRule<Character>& TokenStart = this->mTokenGrammar["Start"]; GrammarRule<Character>& Whitespace = this->mTokenGrammar["Whitespace"]; GrammarRule<Character>& SingleLineComment = this->mTokenGrammar["SingleLineComment"]; GrammarRule<Character>& Identifier = this->mTokenGrammar["Identifier"]; GrammarRule<Character>& TokenLiteral = this->mTokenGrammar["TokenLiteral"]; GrammarRule<Character>& StringLiteral = this->mTokenGrammar["StringLiteral"]; GrammarRule<Character>& IntegerLiteral = this->mTokenGrammar["IntegerLiteral"]; GrammarRule<Character>& OpenBracket = this->mTokenGrammar["OpenBracket"]; GrammarRule<Character>& CloseBracket = this->mTokenGrammar["CloseBracket"]; GrammarRule<Character>& OpenCurley = this->mTokenGrammar["OpenCurley"]; GrammarRule<Character>& CloseCurley = this->mTokenGrammar["CloseCurley"]; GrammarRule<Character>& OpenParenthesis = this->mTokenGrammar["OpenParenthesis"]; GrammarRule<Character>& CloseParenthesis = this->mTokenGrammar["CloseParenthesis"]; GrammarRule<Character>& Comma = this->mTokenGrammar["Comma"]; GrammarRule<Character>& MemberAccess = this->mTokenGrammar["MemberAccess"]; GrammarRule<Character>& Colon = this->mTokenGrammar["Colon"]; GrammarRule<Character>& Semicolon = this->mTokenGrammar["Semicolon"]; GrammarRule<Character>& RewriteAssignment = this->mTokenGrammar["RewriteAssignment"]; GrammarRule<Character>& OrAssignment = this->mTokenGrammar["OrAssignment"]; GrammarRule<Character>& ZeroOrMore = this->mTokenGrammar["ZeroOrMore"]; GrammarRule<Character>& OneOrMore = this->mTokenGrammar["OneOrMore"]; GrammarRule<Character>& Optional = this->mTokenGrammar["Optional"]; GrammarRule<Character>& Or = this->mTokenGrammar["Or"]; GrammarRule<Character>& Capture = this->mTokenGrammar["Capture"]; GrammarRule<Character>& CaptureRule = this->mTokenGrammar["CaptureRule"]; GrammarRule<Character>& Keyword = this->mTokenGrammar["Keyword"]; GrammarRule<Character>& Ignore = this->mTokenGrammar["Ignore"]; GrammarRule<Character>& Tokenizer = this->mTokenGrammar["Tokenizer"]; GrammarRule<Character>& Parser = this->mTokenGrammar["Parser"]; GrammarRule<Character>& Epsilon = this->mTokenGrammar["Epsilon"]; GrammarRule<Character>& Replace = this->mTokenGrammar["Replace"]; GrammarRule<Character>& In = this->mTokenGrammar["In"]; GrammarRule<Character>& With = this->mTokenGrammar["With"]; GrammarRule<Character>& Using = this->mTokenGrammar["Using"]; this->mTokenGrammar.mIgnore.Insert(&Whitespace); this->mTokenGrammar.mIgnore.Insert(&SingleLineComment); this->mTokenGrammar.mKeywords["keyword"] = &Keyword; this->mTokenGrammar.mKeywords["ignore"] = &Ignore; this->mTokenGrammar.mKeywords["tokenizer"] = &Tokenizer; this->mTokenGrammar.mKeywords["parser"] = &Parser; this->mTokenGrammar.mKeywords["e"] = &Epsilon; this->mTokenGrammar.mKeywords["replace"] = &Replace; this->mTokenGrammar.mKeywords["in"] = &In; this->mTokenGrammar.mKeywords["with"] = &With; this->mTokenGrammar.mKeywords["using"] = &Using; this->mTokenStart = &TokenStart; this->mIdentifier = &Identifier; this->mTokenLiteral = &TokenLiteral; this->mStringLiteral = &StringLiteral; this->mIntegerLiteral = &IntegerLiteral; this->mZeroOrMore = &ZeroOrMore; this->mOneOrMore = &OneOrMore; this->mOptional = &Optional; this->mEpsilon = &Epsilon; this->mTokenizer = &Tokenizer; this->mParser = &Parser; TokenStart |= Whitespace | SingleLineComment | Identifier | TokenLiteral | StringLiteral | IntegerLiteral | OpenBracket | CloseBracket | OpenCurley | CloseCurley; TokenStart |= OpenParenthesis | CloseParenthesis | Comma | MemberAccess | Semicolon | Colon | RewriteAssignment | OrAssignment | ZeroOrMore | OneOrMore | Optional | Or | Capture | CaptureRule; Whitespace |= +T(" \t\r\n\v\f"); SingleLineComment |= T("/") << T("/") << *T("^\r\n"); Identifier |= T("a-zA-Z_") << *T("a-zA-Z_0-9"); TokenLiteral |= T("<") << Identifier << T(">"); StringLiteral |= T("\"") << *(T("^\"\\") | T("\\") << T("^")) << T("\"") | T("\'") << *(T("^\'\\") | T("\\") << T("^")) << T("\'"); IntegerLiteral |= +T("0-9"); OpenBracket |= T("["); CloseBracket |= T("]"); OpenCurley |= T("{"); CloseCurley |= T("}"); OpenParenthesis |= T("("); CloseParenthesis |= T(")"); Comma |= T(","); MemberAccess |= T("."); Colon |= T(":"); Semicolon |= T(";"); RewriteAssignment |= T("="); OrAssignment |= Or << T("="); ZeroOrMore |= T("*"); OneOrMore |= T("+"); Optional |= T("~"); Or |= T("|"); Capture |= T("$"); CaptureRule |= T("%"); GrammarRule<Token>& ParserStart = this->mParserGrammar["Start"]; GrammarRule<Token>& Scope = this->mParserGrammar["Scope"]; GrammarRule<Token>& Statement = this->mParserGrammar["Statement"]; GrammarRule<Token>& IgnoreStatement = this->mParserGrammar["IgnoreStatement"]; GrammarRule<Token>& KeywordStatement = this->mParserGrammar["KeywordStatement"]; GrammarRule<Token>& RuleStatement = this->mParserGrammar["RuleStatement"]; GrammarRule<Token>& GrammarExpression = this->mParserGrammar["GrammarExpression"]; GrammarRule<Token>& GrammarExpressionGrouped = this->mParserGrammar["GrammarExpressionGrouped"]; GrammarRule<Token>& GrammarExpressionCapture = this->mParserGrammar["GrammarExpressionCapture"]; GrammarRule<Token>& GrammarExpressionCaptureRule = this->mParserGrammar["GrammarExpressionCaptureRule"]; GrammarRule<Token>& GrammarExpressionOr = this->mParserGrammar["GrammarExpressionOr"]; GrammarRule<Token>& GrammarExpressionConcatenate = this->mParserGrammar["GrammarExpressionConcatenate"]; GrammarRule<Token>& GrammarExpressionUnary = this->mParserGrammar["GrammarExpressionUnary"]; GrammarRule<Token>& GrammarExpressionValue = this->mParserGrammar["GrammarExpressionValue"]; GrammarRule<Token>& ReplacementStatement = this->mParserGrammar["ReplacementStatement"]; GrammarRule<Token>& ReplacementWith = this->mParserGrammar["ReplacementWith"]; GrammarRule<Token>& ReplacementUsing = this->mParserGrammar["ReplacementUsing"]; GrammarRule<Token>& ReplacementExpression = this->mParserGrammar["ReplacementExpression"]; GrammarRule<Token>& ReplacementExpressionConcatenate = this->mParserGrammar["ReplacementExpressionConcatenate"]; GrammarRule<Token>& ReplacementExpressionPost = this->mParserGrammar["ReplacementExpressionPost"]; GrammarRule<Token>& ReplacementExpressionText = this->mParserGrammar["ReplacementExpressionText"]; GrammarRule<Token>& ReplacementExpressionJoin = this->mParserGrammar["ReplacementExpressionJoin"]; GrammarRule<Token>& ReplacementExpressionForeach = this->mParserGrammar["ReplacementExpressionForeach"]; GrammarRule<Token>& CaptureExpression = this->mParserGrammar["CaptureExpression"]; GrammarRule<Token>& CaptureExpressionName = this->mParserGrammar["CaptureExpressionName"]; GrammarRule<Token>& CaptureExpressionNestedIndex = this->mParserGrammar["CaptureExpressionNestedIndex"]; // Text, CaptureJoin, CaptureIteration, Concatenate ParserStart |= *Scope; Scope |= (P(Tokenizer) | P(Parser)) << P(OpenCurley) << *Statement << P(CloseCurley); Statement |= IgnoreStatement | KeywordStatement | RuleStatement | ReplacementStatement; IgnoreStatement |= P(Ignore) << P("RuleName", P(Identifier)) << P(Semicolon); KeywordStatement |= P(Keyword) << P("RuleName", P(Identifier)) << P(Colon) << P("Keyword", P(StringLiteral)) << P(Semicolon); RuleStatement |= P("RuleName", P(Identifier)) << P("Assignment", P(OrAssignment) | P(RewriteAssignment)) << GrammarExpression << P(Semicolon); GrammarExpressionGrouped |= P(OpenParenthesis) << GrammarExpression << P(CloseParenthesis); GrammarExpressionCapture |= P(Capture) << P("CaptureName", P(Identifier)) << GrammarExpressionGrouped; GrammarExpressionCaptureRule |= P(CaptureRule) << P("CaptureName", P(Identifier)); GrammarExpression |= GrammarExpressionOr; GrammarExpressionOr |= GrammarExpressionConcatenate << *(P(Or) << GrammarExpressionConcatenate); GrammarExpressionConcatenate |= +GrammarExpressionUnary; GrammarExpressionUnary |= P("UnaryOperator", P(ZeroOrMore) | P(OneOrMore) | P(Optional)) << GrammarExpressionUnary | GrammarExpressionValue; GrammarExpressionValue |= P("Value", P(Identifier) | P(StringLiteral) | P(TokenLiteral) | P(Epsilon)) | GrammarExpressionGrouped | GrammarExpressionCapture | GrammarExpressionCaptureRule; ReplacementStatement |= P(Replace) << GrammarExpression << P(In) << P("RuleName", P(Identifier)) << (ReplacementWith | ReplacementUsing); ReplacementWith |= P(With) << ReplacementExpression << P(Semicolon); ReplacementUsing |= P("Member", P(Identifier) << ~(P(MemberAccess) << P(Identifier))); ReplacementExpression |= ReplacementExpressionConcatenate; ReplacementExpressionConcatenate |= +ReplacementExpressionPost; ReplacementExpressionPost |= ReplacementExpressionText | CaptureExpression << ~(ReplacementExpressionJoin | ReplacementExpressionForeach); ReplacementExpressionText |= P("ReplacementText", P(StringLiteral)); ReplacementExpressionJoin |= P(OpenParenthesis) << ReplacementExpression << P(CloseParenthesis); ReplacementExpressionForeach |= P(OpenCurley) << ReplacementExpression << P(CloseCurley); CaptureExpression |= CaptureExpressionName << *CaptureExpressionNestedIndex; CaptureExpressionName |= P("CaptureName", P(Identifier)); CaptureExpressionNestedIndex |= P(OpenBracket) << (P("StartIndex", P(IntegerLiteral)) << ~(P(Comma) << P("EndIndex", P(IntegerLiteral))) | P("NestedCaptureName", P(Identifier))); this->mParserStart = &ParserStart; this->mIgnoreStatement = &IgnoreStatement; this->mKeywordStatement = &KeywordStatement; this->mRuleStatement = &RuleStatement; this->mGrammarExpressionCapture = &GrammarExpressionCapture; this->mGrammarExpressionCaptureRule = &GrammarExpressionCaptureRule; this->mGrammarExpressionOr = &GrammarExpressionOr; this->mGrammarExpressionConcatenate = &GrammarExpressionConcatenate; this->mGrammarExpressionUnary = &GrammarExpressionUnary; this->mGrammarExpressionValue = &GrammarExpressionValue; this->mReplacementStatement = &ReplacementStatement; this->mReplacementExpressionConcatenate = &ReplacementExpressionConcatenate; this->mReplacementExpressionPost = &ReplacementExpressionPost; this->mReplacementExpressionText = &ReplacementExpressionText; this->mReplacementExpressionJoin = &ReplacementExpressionJoin; this->mReplacementExpressionForeach = &ReplacementExpressionForeach; this->mCaptureExpression = &CaptureExpression; this->mCaptureExpressionName = &CaptureExpressionName; this->mCaptureExpressionNestedIndex = &CaptureExpressionNestedIndex; } DataDrivenLexerShared& DataDrivenLexerShared::GetInstance() { static DataDrivenLexerShared instance; return instance; } void DataDrivenLexer::Parse(StringParam input, GrammarSet<Character>& userTokenGrammar, GrammarSet<Token>& userParserGrammar) { this->mMode = DataDrivenLexerMode::Tokenizer; this->mUserTokenGrammar = &userTokenGrammar; this->mUserParserGrammar = &userParserGrammar; DataDrivenLexerShared& shared = DataDrivenLexerShared::GetInstance(); TokenStream<> stream; stream.mRange = TokenRange<>(shared.mTokenGrammar, *shared.mTokenStart, input); // ParseTreeBuilder<Token> parserTreeBuilder; RecursiveDescentParser<Token, TokenStream<>, DataDrivenLexer> parser; parser.mParseHandler = this; parser.mStartRule = shared.mParserStart; parser.mStream = &stream; parser.Parse(); // String diffParserTreeOutput = // parserTreeBuilder.mTree->GetDebugRepresentation(); // // String graph = parserTreeBuilder.mTree->GetGraphRepresentation(); // Zero::WriteToFile("C:\\Sandbox\\Graph.gv", (const byte*)graph.c_str(), // graph.size()); system("C:\\Progra~2\\Graphviz2.38\\bin\\dot.exe -Tpng // \"C:\\Sandbox\\Graph.gv\" > \"C:\\Sandbox\\Graph.png\""); // system("C:\\Sandbox\\Graph.png"); } void DataDrivenLexer::StartRule(GrammarRule<Token>* rule) { if (this->mMode == DataDrivenLexerMode::Tokenizer) this->StartRule<Character>(rule, *this->mUserTokenGrammar, this->mTokenNodes); else this->StartRule<Token>(rule, *this->mUserParserGrammar, this->mParserNodes); } void DataDrivenLexer::EndRule(ParseNodeInfo<Token>* info) { if (this->mMode == DataDrivenLexerMode::Tokenizer) this->EndRule<Character>(info, *this->mUserTokenGrammar, this->mTokenNodes); else this->EndRule<Token>(info, *this->mUserParserGrammar, this->mParserNodes); } void DataDrivenLexer::TokenParsed(ParseNodeInfo<Token>* info) { GrammarRule<Character>* rule = info->mToken.mRule; DataDrivenLexerShared& shared = DataDrivenLexerShared::GetInstance(); if (rule == shared.mTokenizer) this->mMode = DataDrivenLexerMode::Tokenizer; else if (rule == shared.mParser) this->mMode = DataDrivenLexerMode::Parser; } void DataDrivenLexer::StartParsing() { } void DataDrivenLexer::EndParsing() { } template <> void DataDrivenLexer::AddStringLiteralNode<Character>(StringParam string, Array<GrammarNode<Character>*>& nodes) { String literal = ReplaceStringEscapesAndStripQuotes(string); GrammarNode<Character>& node = T(literal); nodes.PushBack(&node); } template <> void DataDrivenLexer::AddStringLiteralNode<Token>(StringParam string, Array<GrammarNode<Token>*>& nodes) { Error("Cannot add ranges/sets in a parser (you can only use token literals)"); nodes.PushBack(&P()); } template <> void DataDrivenLexer::AddTokenLiteralNode<Character>(StringParam string, Array<GrammarNode<Character>*>& nodes) { Error("Cannot add token literals in a tokenizer (the tokens must come from " "the tokenizer, and be used in the parser)"); nodes.PushBack(&T()); } template <> void DataDrivenLexer::AddTokenLiteralNode<Token>(StringParam string, Array<GrammarNode<Token>*>& nodes) { StringRange tokenLiteral = string; tokenLiteral.PopFront(); tokenLiteral.PopBack(); tokenLiteral.PopBack(); GrammarRule<Character>& rule = (*this->mUserTokenGrammar)[tokenLiteral]; nodes.PushBack(&P(rule)); } } // namespace Zilch
// Copyright 2018 The Beam Team // // 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 "aissue_tx_builder.h" #include "core/block_crypt.h" #include "utility/logger.h" #include "wallet/core/strings_resources.h" #include <numeric> namespace beam::wallet { void GenerateRandom(void* p, uint32_t n) { for (uint32_t i = 0; i < n; i++) ((uint8_t*) p)[i] = (uint8_t) rand(); } void SetRandom(ECC::uintBig& x) { GenerateRandom(x.m_pData, x.nBytes); } void SetRandom(ECC::Scalar::Native& x) { ECC::Scalar s; while (true) { SetRandom(s.m_Value); if (!x.Import(s)) break; } } using namespace ECC; using namespace std; AssetIssueTxBuilder::AssetIssueTxBuilder(bool issue, BaseTransaction& tx, SubTxID subTxID, IPrivateKeyKeeper::Ptr keyKeeper) : m_Tx{tx} , m_keyKeeper(std::move(keyKeeper)) , m_SubTxID(subTxID) , m_assetId(0) , m_assetOwnerIdx(0) , m_assetOwnerId(Zero) , m_issue(issue) , m_AmountList{0} , m_Fee(0) , m_ChangeBeam(0) , m_ChangeAsset(0) , m_MinHeight(0) , m_MaxHeight(MaxHeight) , m_Offset(Zero) { if (!m_keyKeeper.get()) { throw TransactionFailedException(!m_Tx.IsInitiator(), TxFailureReason::NoKeyKeeper); } m_Fee = m_Tx.GetMandatoryParameter<Amount>(TxParameterID::Fee, m_SubTxID); if (!m_Tx.GetParameter(TxParameterID::AmountList, m_AmountList, m_SubTxID)) { m_AmountList = AmountList{m_Tx.GetMandatoryParameter<Amount>(TxParameterID::Amount, m_SubTxID)}; } m_assetOwnerIdx = m_Tx.GetMandatoryParameter<Key::Index>(TxParameterID::AssetOwnerIdx); m_assetOwnerId = m_keyKeeper->GetAssetOwnerID(m_assetOwnerIdx); m_assetId = m_Tx.GetMandatoryParameter<AssetID>(TxParameterID::AssetID, m_SubTxID); if (m_assetOwnerIdx == 0 || m_assetId == 0) { throw TransactionFailedException(!m_Tx.IsInitiator(), TxFailureReason::NoAssetId); } } bool AssetIssueTxBuilder::CreateInputs() { if (GetInputs() || GetInputCoins().empty()) { return false; } const auto& [commitments, commitmentsOffset] = m_Tx.GetKeyKeeper()->GeneratePublicKeysSyncEx(m_InputCoins, true, m_assetId); m_Offset += commitmentsOffset; m_Inputs.reserve(commitments.size()); for (const auto& commitment : commitments) { auto& input = m_Inputs.emplace_back(make_unique<Input>()); input->m_Commitment = commitment; } m_Tx.SetParameter(TxParameterID::Inputs, m_Inputs, false, m_SubTxID); return false; // true if async operation has run } bool AssetIssueTxBuilder::GetInitialTxParams() { m_Tx.GetParameter(TxParameterID::ChangeAsset,m_ChangeAsset, m_SubTxID); m_Tx.GetParameter(TxParameterID::Inputs, m_Inputs, m_SubTxID); m_Tx.GetParameter(TxParameterID::Outputs, m_Outputs, m_SubTxID); m_Tx.GetParameter(TxParameterID::InputCoins, m_InputCoins, m_SubTxID); m_Tx.GetParameter(TxParameterID::OutputCoins,m_OutputCoins, m_SubTxID); if (!m_Tx.GetParameter(TxParameterID::MinHeight, m_MinHeight, m_SubTxID)) { m_MinHeight = m_Tx.GetWalletDB()->getCurrentHeight(); m_Tx.SetParameter(TxParameterID::MinHeight, m_MinHeight, m_SubTxID); } if (!m_Tx.GetParameter(TxParameterID::MaxHeight, m_MaxHeight, m_SubTxID)) { Height lifetime = kDefaultTxLifetime; m_Tx.GetParameter(TxParameterID::Lifetime, lifetime,m_SubTxID); m_MaxHeight = m_MinHeight + lifetime; m_Tx.SetParameter(TxParameterID::MaxHeight, m_MaxHeight, m_SubTxID); } return m_Tx.GetParameter(TxParameterID::Offset, m_Offset, m_SubTxID); } bool AssetIssueTxBuilder::LoadKernel() { if (m_Tx.GetParameter(TxParameterID::Kernel, m_Kernel, m_SubTxID)) { GetInitialTxParams(); return true; } return false; } Transaction::Ptr AssetIssueTxBuilder::CreateTransaction() { // Don't display in log infinite max height if (m_Kernel->m_Height.m_Max == MaxHeight) { LOG_INFO() << m_Tx.GetTxID() << "[" << m_SubTxID << "]" << " Transaction created. Kernel: " << GetKernelIDString() << ", min height: " << m_Kernel->m_Height.m_Min; } else { LOG_INFO() << m_Tx.GetTxID() << "[" << m_SubTxID << "]" << " Transaction created. Kernel: " << GetKernelIDString() << ", min height: " << m_Kernel->m_Height.m_Min << ", max height: " << m_Kernel->m_Height.m_Max; } auto tx = make_shared<Transaction>(); tx->m_vInputs = std::move(m_Inputs); tx->m_vOutputs = std::move(m_Outputs); tx->m_vKernels.push_back(std::move(m_Kernel)); m_Tx.SetParameter(TxParameterID::Offset, m_Offset, false, m_SubTxID); tx->m_Offset = m_Offset; tx->Normalize(); #ifdef DEBUG beam::Transaction::Context::Params pars; beam::Transaction::Context ctx(pars); ctx.m_Height.m_Min = m_MinHeight; assert(tx->IsValid(ctx)); #endif return tx; } Amount AssetIssueTxBuilder::GetAmountBeam() const { return m_issue ? std::accumulate(m_AmountList.begin(), m_AmountList.end(), 0ULL) : 0; } Amount AssetIssueTxBuilder::GetAmountAsset() const { return m_issue ? 0 : std::accumulate(m_AmountList.begin(), m_AmountList.end(), 0ULL); } const AmountList& AssetIssueTxBuilder::GetAmountList() const { return m_AmountList; } Height AssetIssueTxBuilder::GetMinHeight() const { return m_MinHeight; } const std::vector<Coin::ID>& AssetIssueTxBuilder::GetInputCoins() const { return m_InputCoins; } const std::vector<Coin::ID>& AssetIssueTxBuilder::GetOutputCoins() const { return m_OutputCoins; } void AssetIssueTxBuilder::AddChange() { if (m_ChangeBeam) { GenerateBeamCoin(m_ChangeBeam, true); } if (m_ChangeAsset) { GenerateAssetCoin(m_ChangeAsset, true); } m_Tx.SetParameter(TxParameterID::OutputCoins, m_OutputCoins, false, m_SubTxID); } Amount AssetIssueTxBuilder::GetFee() const { return m_Fee; } Key::Index AssetIssueTxBuilder::GetAssetOwnerIdx() const { return m_assetOwnerIdx; } PeerID AssetIssueTxBuilder::GetAssetOwnerId() const { return m_assetOwnerId; } AssetID AssetIssueTxBuilder::GetAssetId() const { return m_assetId; } string AssetIssueTxBuilder::GetKernelIDString() const { Merkle::Hash kernelID; m_Tx.GetParameter(TxParameterID::KernelID, kernelID, m_SubTxID); char sz[Merkle::Hash::nTxtLen + 1]; kernelID.Print(sz); return string(sz); } bool AssetIssueTxBuilder::GetInputs() { return m_Tx.GetParameter(TxParameterID::Inputs, m_Inputs, m_SubTxID); } bool AssetIssueTxBuilder::GetOutputs() { return m_Tx.GetParameter(TxParameterID::Outputs, m_Outputs, m_SubTxID); } void AssetIssueTxBuilder::SelectInputs() { CoinIDList preselIDs; vector<Coin> coins; Amount preselAmountBeam = 0; Amount preselAmountAsset = 0; auto isAssetCoin = [](const Coin& coin) { return coin.m_ID.m_Type == Key::Type::Asset || coin.m_ID.m_Type == Key::Type::AssetChange; }; if (m_Tx.GetParameter(TxParameterID::PreselectedCoins, preselIDs, m_SubTxID)) { if (!preselIDs.empty()) { coins = m_Tx.GetWalletDB()->getCoinsByID(preselIDs); for (auto &coin : coins) { isAssetCoin(coin) ? preselAmountAsset += coin.getAmount() : preselAmountBeam += coin.getAmount(); coin.m_spentTxId = m_Tx.GetTxID(); } m_Tx.GetWalletDB()->saveCoins(coins); } } Amount amountBeamWithFee = GetAmountBeam() + m_Fee; if (preselAmountBeam < amountBeamWithFee) { auto selectedCoins = m_Tx.GetWalletDB()->selectCoins(amountBeamWithFee - preselAmountBeam, Zero); if (selectedCoins.empty()) { storage::Totals totals(*m_Tx.GetWalletDB()); const auto& beamTotals = totals.GetTotals(Zero); LOG_ERROR() << m_Tx.GetTxID() << "[" << m_SubTxID << "]" << " You only have " << PrintableAmount(beamTotals.Avail); throw TransactionFailedException(!m_Tx.IsInitiator(), TxFailureReason::NoInputs); } copy(selectedCoins.begin(), selectedCoins.end(), back_inserter(coins)); } Amount amountAsset = GetAmountAsset(); if (preselAmountAsset < amountAsset) { auto selectedCoins = m_Tx.GetWalletDB()->selectCoins(amountAsset - preselAmountAsset, m_assetId); if (selectedCoins.empty()) { storage::Totals totals(*m_Tx.GetWalletDB()); const auto& assetTotals(totals.GetTotals(m_assetId)); LOG_ERROR() << m_Tx.GetTxID() << "[" << m_SubTxID << "]" << " You only have " << PrintableAmount(assetTotals.Avail, false, kAmountASSET, kAmountAGROTH); throw TransactionFailedException(!m_Tx.IsInitiator(), TxFailureReason::NoInputs); } copy(selectedCoins.begin(), selectedCoins.end(), back_inserter(coins)); } m_InputCoins.reserve(coins.size()); Amount totalBeam = 0; Amount totalAsset = 0; for (auto& coin : coins) { coin.m_spentTxId = m_Tx.GetTxID(); isAssetCoin(coin) ? totalAsset += coin.m_ID.m_Value : totalBeam += coin.m_ID.m_Value; m_InputCoins.push_back(coin.m_ID); } m_ChangeBeam = totalBeam - amountBeamWithFee; m_ChangeAsset = totalAsset - amountAsset; m_Tx.SetParameter(TxParameterID::ChangeBeam, m_ChangeBeam, false, m_SubTxID); m_Tx.SetParameter(TxParameterID::ChangeAsset, m_ChangeAsset, false, m_SubTxID); m_Tx.SetParameter(TxParameterID::InputCoins, m_InputCoins, false, m_SubTxID); m_Tx.GetWalletDB()->saveCoins(coins); } void AssetIssueTxBuilder::GenerateAssetCoin(Amount amount, bool change) { Coin newUtxo(amount, change ? Key::Type::AssetChange : Key::Type::Asset, m_assetId); newUtxo.m_createTxId = m_Tx.GetTxID(); m_Tx.GetWalletDB()->storeCoin(newUtxo); m_OutputCoins.push_back(newUtxo.m_ID); m_Tx.SetParameter(TxParameterID::OutputCoins, m_OutputCoins, false, m_SubTxID); LOG_INFO() << m_Tx.GetTxID() << " Creating ASSET coin" << (change ? " (change):" : ":") << PrintableAmount(amount, false, kAmountASSET, kAmountAGROTH) << ", asset id " << m_assetId << ", id " << newUtxo.toStringID(); } void AssetIssueTxBuilder::GenerateBeamCoin(Amount amount, bool change) { Coin newUtxo(amount, change ? Key::Type::Change : Key::Type::Regular); newUtxo.m_createTxId = m_Tx.GetTxID(); m_Tx.GetWalletDB()->storeCoin(newUtxo); m_OutputCoins.push_back(newUtxo.m_ID); m_Tx.SetParameter(TxParameterID::OutputCoins, m_OutputCoins, false, m_SubTxID); LOG_INFO() << m_Tx.GetTxID() << " Creating BEAM coin" << (change ? " (change):" : ":") << PrintableAmount(amount) << ", id " << newUtxo.toStringID(); } bool AssetIssueTxBuilder::CreateOutputs() { if (GetOutputs()) { // if we already have outputs, nothing to do here return false; } if (GetOutputCoins().empty()) { // Output coins should be generated already return false; } auto thisHolder = shared_from_this(); auto txHolder = m_Tx.shared_from_this(); // increment use counter of tx object. We use it to avoid tx object desctruction during Update call. m_Tx.GetAsyncAcontext().OnAsyncStarted(); m_Tx.GetKeyKeeper()->GenerateOutputsEx(m_MinHeight, m_OutputCoins, m_assetId, [thisHolder, this, txHolder](IPrivateKeyKeeper::Outputs&& resOutputs, auto&& resOffset) { m_Outputs = std::move(resOutputs); m_Offset += resOffset; m_Tx.SetParameter(TxParameterID::Outputs, m_Outputs, false, m_SubTxID); m_Tx.Update(); // may complete transaction m_Tx.GetAsyncAcontext().OnAsyncFinished(); }, [thisHolder, this, txHolder](const exception&) { m_Tx.GetAsyncAcontext().OnAsyncFinished(); }); return true; // true if async } const Merkle::Hash& AssetIssueTxBuilder::GetKernelID() const { if (!m_KernelID) { Merkle::Hash kernelID; if (m_Tx.GetParameter(TxParameterID::KernelID, kernelID, m_SubTxID)) { m_KernelID = kernelID; } else { assert(false && "KernelID is not stored"); } } return *m_KernelID; } void AssetIssueTxBuilder::CreateKernel() { static_assert(std::is_same<decltype(m_Kernel->m_Value), int64_t>::value, "If this fails please update value in the ConsumeAmountTooBig's message and typecheck in this assert"); assert(!m_Kernel); if (!m_issue) { // Note, m_Kernel is still nullptr, do not don't anything except typecheks here // This should never happen, nobody would ever have so much asset/beams, but just in case if (GetAmountAsset() > (Amount)std::numeric_limits<decltype(m_Kernel->m_Value)>::max()) { throw TransactionFailedException(!m_Tx.IsInitiator(), ConsumeAmountTooBig); } } m_Kernel = make_unique<TxKernelAssetEmit>(); m_Kernel->m_Fee = m_Fee; m_Kernel->m_Height.m_Min = GetMinHeight(); m_Kernel->m_Height.m_Max = m_MaxHeight; m_Kernel->m_Commitment = Zero; m_Kernel->m_AssetID = m_assetId; m_Kernel->m_Value = m_issue ? GetAmountBeam() : -static_cast<AmountSigned>(GetAmountAsset()); } void AssetIssueTxBuilder::SignKernel() { m_Offset += m_keyKeeper->SignEmissionKernel(*m_Kernel, m_assetOwnerIdx); const Merkle::Hash& kernelID = m_Kernel->m_Internal.m_ID; m_Tx.SetParameter(TxParameterID::KernelID, kernelID, m_SubTxID); m_Tx.SetParameter(TxParameterID::Kernel, m_Kernel, m_SubTxID); } }
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "mojo/edk/system/handle.h" #include <utility> #include "mojo/edk/system/dispatcher.h" using mojo::util::RefPtr; namespace mojo { namespace system { Handle::Handle() : rights(MOJO_HANDLE_RIGHT_NONE) {} Handle::Handle(const Handle&) = default; Handle::Handle(Handle&&) = default; Handle::Handle(RefPtr<Dispatcher>&& dispatcher, MojoHandleRights rights) : dispatcher(std::move(dispatcher)), rights(rights) {} Handle::~Handle() {} Handle& Handle::operator=(const Handle&) = default; Handle& Handle::operator=(Handle&&) = default; } // namespace system } // namespace mojo
#include <boost/test/unit_test.hpp> #include <eosio/testing/tester.hpp> #include <eosio/chain/contracts/abi_serializer.hpp> #include <eosio/chain/wasm_eosio_constraints.hpp> #include <eosio/chain/exceptions.hpp> #include <asserter/asserter.wast.hpp> #include <asserter/asserter.abi.hpp> #include <stltest/stltest.wast.hpp> #include <stltest/stltest.abi.hpp> #include <noop/noop.wast.hpp> #include <noop/noop.abi.hpp> #include <eosio.system/eosio.system.wast.hpp> #include <eosio.system/eosio.system.abi.hpp> #include <Runtime/Runtime.h> #include <fc/variant_object.hpp> #include <fc/io/json.hpp> #include "test_wasts.hpp" #include <array> #include <utility> using namespace eosio; using namespace eosio::chain; using namespace eosio::chain::contracts; using namespace eosio::testing; using namespace fc; struct assertdef { int8_t condition; string message; static account_name get_account() { return N(asserter); } static action_name get_name() { return N(procassert); } }; FC_REFLECT(assertdef, (condition)(message)); struct provereset { static account_name get_account() { return N(asserter); } static action_name get_name() { return N(provereset); } }; FC_REFLECT_EMPTY(provereset); BOOST_AUTO_TEST_SUITE(wasm_tests) /** * Prove that action reading and assertions are working */ BOOST_FIXTURE_TEST_CASE( basic_test, tester ) try { produce_blocks(2); create_accounts( {N(asserter)} ); produce_block(); set_code(N(asserter), asserter_wast); produce_blocks(1); transaction_id_type no_assert_id; { signed_transaction trx; trx.actions.emplace_back( vector<permission_level>{{N(asserter),config::active_name}}, assertdef {1, "Should Not Assert!"} ); set_tapos( trx ); trx.sign( get_private_key( N(asserter), "active" ), chain_id_type() ); auto result = push_transaction( trx ); BOOST_CHECK_EQUAL(result.status, transaction_receipt::executed); BOOST_CHECK_EQUAL(result.action_traces.size(), 1); BOOST_CHECK_EQUAL(result.action_traces.at(0).receiver.to_string(), name(N(asserter)).to_string() ); BOOST_CHECK_EQUAL(result.action_traces.at(0).act.account.to_string(), name(N(asserter)).to_string() ); BOOST_CHECK_EQUAL(result.action_traces.at(0).act.name.to_string(), name(N(procassert)).to_string() ); BOOST_CHECK_EQUAL(result.action_traces.at(0).act.authorization.size(), 1 ); BOOST_CHECK_EQUAL(result.action_traces.at(0).act.authorization.at(0).actor.to_string(), name(N(asserter)).to_string() ); BOOST_CHECK_EQUAL(result.action_traces.at(0).act.authorization.at(0).permission.to_string(), name(config::active_name).to_string() ); no_assert_id = trx.id(); } produce_blocks(1); BOOST_REQUIRE_EQUAL(true, chain_has_transaction(no_assert_id)); const auto& receipt = get_transaction_receipt(no_assert_id); BOOST_CHECK_EQUAL(transaction_receipt::executed, receipt.status); transaction_id_type yes_assert_id; { signed_transaction trx; trx.actions.emplace_back( vector<permission_level>{{N(asserter),config::active_name}}, assertdef {0, "Should Assert!"} ); set_tapos( trx ); trx.sign( get_private_key( N(asserter), "active" ), chain_id_type() ); yes_assert_id = trx.id(); BOOST_CHECK_THROW(push_transaction( trx ), fc::assert_exception); } produce_blocks(1); auto has_tx = chain_has_transaction(yes_assert_id); BOOST_REQUIRE_EQUAL(false, has_tx); } FC_LOG_AND_RETHROW() /// basic_test /** * Prove the modifications to global variables are wiped between runs */ BOOST_FIXTURE_TEST_CASE( prove_mem_reset, tester ) try { produce_blocks(2); create_accounts( {N(asserter)} ); produce_block(); set_code(N(asserter), asserter_wast); produce_blocks(1); // repeat the action multiple times, each time the action handler checks for the expected // default value then modifies the value which should not survive until the next invoction for (int i = 0; i < 5; i++) { signed_transaction trx; trx.actions.emplace_back( vector<permission_level>{{N(asserter),config::active_name}}, provereset {} ); set_tapos( trx ); trx.sign( get_private_key( N(asserter), "active" ), chain_id_type() ); push_transaction( trx ); produce_blocks(1); BOOST_REQUIRE_EQUAL(true, chain_has_transaction(trx.id())); const auto& receipt = get_transaction_receipt(trx.id()); BOOST_CHECK_EQUAL(transaction_receipt::executed, receipt.status); } } FC_LOG_AND_RETHROW() /// prove_mem_reset /** * Prove the modifications to global variables are wiped between runs */ BOOST_FIXTURE_TEST_CASE( abi_from_variant, tester ) try { produce_blocks(2); create_accounts( {N(asserter)} ); produce_block(); set_code(N(asserter), asserter_wast); set_abi(N(asserter), asserter_abi); produce_blocks(1); auto resolver = [&,this]( const account_name& name ) -> optional<abi_serializer> { try { const auto& accnt = this->control->get_database().get<account_object,by_name>( name ); abi_def abi; if (abi_serializer::to_abi(accnt.abi, abi)) { return abi_serializer(abi); } return optional<abi_serializer>(); } FC_RETHROW_EXCEPTIONS(error, "Failed to find or parse ABI for ${name}", ("name", name)) }; variant pretty_trx = mutable_variant_object() ("actions", variants({ mutable_variant_object() ("account", "asserter") ("name", "procassert") ("authorization", variants({ mutable_variant_object() ("actor", "asserter") ("permission", name(config::active_name).to_string()) })) ("data", mutable_variant_object() ("condition", 1) ("message", "Should Not Assert!") ) }) ); signed_transaction trx; abi_serializer::from_variant(pretty_trx, trx, resolver); set_tapos( trx ); trx.sign( get_private_key( N(asserter), "active" ), chain_id_type() ); push_transaction( trx ); produce_blocks(1); BOOST_REQUIRE_EQUAL(true, chain_has_transaction(trx.id())); const auto& receipt = get_transaction_receipt(trx.id()); BOOST_CHECK_EQUAL(transaction_receipt::executed, receipt.status); } FC_LOG_AND_RETHROW() /// prove_mem_reset /** * Make sure WASM "start" method is used correctly */ BOOST_FIXTURE_TEST_CASE( check_entry_behavior, tester ) try { produce_blocks(2); create_accounts( {N(entrycheck)} ); produce_block(); set_code(N(entrycheck), entry_wast); produce_blocks(10); signed_transaction trx; action act; act.account = N(entrycheck); act.name = N(); act.authorization = vector<permission_level>{{N(entrycheck),config::active_name}}; trx.actions.push_back(act); set_tapos(trx); trx.sign(get_private_key( N(entrycheck), "active" ), chain_id_type()); push_transaction(trx); produce_blocks(1); BOOST_REQUIRE_EQUAL(true, chain_has_transaction(trx.id())); const auto& receipt = get_transaction_receipt(trx.id()); BOOST_CHECK_EQUAL(transaction_receipt::executed, receipt.status); } FC_LOG_AND_RETHROW() /** * Ensure we can load a wasm w/o memory */ BOOST_FIXTURE_TEST_CASE( simple_no_memory_check, tester ) try { produce_blocks(2); create_accounts( {N(nomem)} ); produce_block(); set_code(N(nomem), simple_no_memory_wast); produce_blocks(1); //the apply func of simple_no_memory_wast tries to call a native func with linear memory pointer signed_transaction trx; action act; act.account = N(nomem); act.name = N(); act.authorization = vector<permission_level>{{N(nomem),config::active_name}}; trx.actions.push_back(act); trx.sign(get_private_key( N(nomem), "active" ), chain_id_type()); BOOST_CHECK_THROW(push_transaction( trx ), wasm_execution_error); } FC_LOG_AND_RETHROW() //Make sure globals are all reset to their inital values BOOST_FIXTURE_TEST_CASE( check_global_reset, tester ) try { produce_blocks(2); create_accounts( {N(globalreset)} ); produce_block(); set_code(N(globalreset), mutable_global_wast); produce_blocks(1); signed_transaction trx; { action act; act.account = N(globalreset); act.name = name(0ULL); act.authorization = vector<permission_level>{{N(globalreset),config::active_name}}; trx.actions.push_back(act); } { action act; act.account = N(globalreset); act.name = 1ULL; act.authorization = vector<permission_level>{{N(globalreset),config::active_name}}; trx.actions.push_back(act); } set_tapos(trx); trx.sign(get_private_key( N(globalreset), "active" ), chain_id_type()); push_transaction(trx); produce_blocks(1); BOOST_REQUIRE_EQUAL(true, chain_has_transaction(trx.id())); const auto& receipt = get_transaction_receipt(trx.id()); BOOST_CHECK_EQUAL(transaction_receipt::executed, receipt.status); } FC_LOG_AND_RETHROW() BOOST_FIXTURE_TEST_CASE( stl_test, tester ) try { produce_blocks(2); create_accounts( {N(stltest), N(alice), N(bob)} ); produce_block(); set_code(N(stltest), stltest_wast); set_abi(N(stltest), stltest_abi); produce_blocks(1); const auto& accnt = control->get_database().get<account_object,by_name>( N(stltest) ); abi_def abi; BOOST_REQUIRE_EQUAL(abi_serializer::to_abi(accnt.abi, abi), true); abi_serializer abi_ser(abi); //send message { signed_transaction trx; action msg_act; msg_act.account = N(stltest); msg_act.name = N(message); msg_act.authorization = vector<permission_level>{{N(bob), config::active_name}}; msg_act.data = abi_ser.variant_to_binary("message", mutable_variant_object() ("from", "bob") ("to", "alice") ("message","Hi Alice!") ); trx.actions.push_back(std::move(msg_act)); set_tapos(trx); trx.sign(get_private_key(N(bob), "active"), chain_id_type()); push_transaction(trx); produce_block(); BOOST_REQUIRE_EQUAL(true, chain_has_transaction(trx.id())); } } FC_LOG_AND_RETHROW() /// stltest //Make sure current_memory/grow_memory is not allowed BOOST_FIXTURE_TEST_CASE( memory_operators, tester ) try { produce_blocks(2); create_accounts( {N(current_memory)} ); produce_block(); BOOST_CHECK_THROW(set_code(N(current_memory), current_memory_wast), eosio::chain::wasm_execution_error); produce_blocks(1); BOOST_CHECK_THROW(set_code(N(current_memory), grow_memory_wast), eosio::chain::wasm_execution_error); produce_blocks(1); } FC_LOG_AND_RETHROW() //Make sure we can create a wasm with maximum pages, but not grow it any BOOST_FIXTURE_TEST_CASE( big_memory, tester ) try { produce_blocks(2); create_accounts( {N(bigmem)} ); produce_block(); string biggest_memory_wast_f = fc::format_string(biggest_memory_wast, fc::mutable_variant_object( "MAX_WASM_PAGES", eosio::chain::wasm_constraints::maximum_linear_memory/(64*1024))); set_code(N(bigmem), biggest_memory_wast_f.c_str()); produce_blocks(1); signed_transaction trx; action act; act.account = N(bigmem); act.name = N(); act.authorization = vector<permission_level>{{N(bigmem),config::active_name}}; trx.actions.push_back(act); set_tapos(trx); trx.sign(get_private_key( N(bigmem), "active" ), chain_id_type()); //but should not be able to grow beyond largest page push_transaction(trx); produce_blocks(1); string too_big_memory_wast_f = fc::format_string(too_big_memory_wast, fc::mutable_variant_object( "MAX_WASM_PAGES_PLUS_ONE", eosio::chain::wasm_constraints::maximum_linear_memory/(64*1024)+1)); BOOST_CHECK_THROW(set_code(N(bigmem), too_big_memory_wast_f.c_str()), eosio::chain::wasm_execution_error); } FC_LOG_AND_RETHROW() BOOST_FIXTURE_TEST_CASE( table_init_tests, tester ) try { produce_blocks(2); create_accounts( {N(tableinit)} ); produce_block(); set_code(N(tableinit), valid_sparse_table); produce_blocks(1); BOOST_CHECK_THROW(set_code(N(tableinit), too_big_table), eosio::chain::wasm_execution_error); } FC_LOG_AND_RETHROW() BOOST_FIXTURE_TEST_CASE( memory_init_border, tester ) try { produce_blocks(2); create_accounts( {N(memoryborder)} ); produce_block(); set_code(N(memoryborder), memory_init_borderline); produce_blocks(1); BOOST_CHECK_THROW(set_code(N(memoryborder), memory_init_toolong), eosio::chain::wasm_execution_error); BOOST_CHECK_THROW(set_code(N(memoryborder), memory_init_negative), eosio::chain::wasm_execution_error); } FC_LOG_AND_RETHROW() BOOST_FIXTURE_TEST_CASE( imports, tester ) try { try { produce_blocks(2); create_accounts( {N(imports)} ); produce_block(); //this will fail to link but that's okay; mainly looking to make sure that the constraint // system doesn't choke when memories and tables exist only as imports BOOST_CHECK_THROW(set_code(N(imports), memory_table_import), fc::exception); } catch ( const fc::exception& e ) { edump((e.to_detail_string())); throw; } } FC_LOG_AND_RETHROW() BOOST_FIXTURE_TEST_CASE( lotso_globals, tester ) try { produce_blocks(2); create_accounts( {N(globals)} ); produce_block(); std::stringstream ss; ss << "(module "; for(unsigned int i = 0; i < 85; ++i) ss << "(global $g" << i << " (mut i32) (i32.const 0))" << "(global $g" << i+100 << " (mut i64) (i64.const 0))"; //that gives us 1020 bytes of mutable globals //add a few immutable ones for good measure for(unsigned int i = 0; i < 10; ++i) ss << "(global $g" << i+200 << " i32 (i32.const 0))"; set_code(N(globals), string(ss.str() + ")") .c_str()); //1024 should pass set_code(N(globals), string(ss.str() + "(global $z (mut i32) (i32.const -12)))") .c_str()); //1028 should fail BOOST_CHECK_THROW(set_code(N(globals), string(ss.str() + "(global $z (mut i64) (i64.const -12)))") .c_str()), eosio::chain::wasm_execution_error);; } FC_LOG_AND_RETHROW() BOOST_FIXTURE_TEST_CASE( offset_check, tester ) try { produce_blocks(2); create_accounts( {N(offsets)} ); produce_block(); //floats not tested since they are blocked in the serializer before eosio_constraints vector<string> loadops = { "i32.load", "i64.load", /* "f32.load", "f64.load",*/ "i32.load8_s", "i32.load8_u", "i32.load16_s", "i32.load16_u", "i64.load8_s", "i64.load8_u", "i64.load16_s", "i64.load16_u", "i64.load32_s", "i64.load32_u" }; vector<vector<string>> storeops = { {"i32.store", "i32"}, {"i64.store", "i64"}, /*{"f32.store", "f32"}, {"f64.store", "f64"},*/ {"i32.store8", "i32"}, {"i32.store16", "i32"}, {"i64.store8", "i64"}, {"i64.store16", "i64"}, {"i64.store32", "i64"}, }; for(const string& s : loadops) { std::stringstream ss; ss << "(module (memory $0 " << eosio::chain::wasm_constraints::maximum_linear_memory/(64*1024) << ") (func $apply (param $0 i64) (param $1 i64) "; ss << "(drop (" << s << " offset=" << eosio::chain::wasm_constraints::maximum_linear_memory-2 << " (i32.const 0)))"; ss << "))"; set_code(N(offsets), ss.str().c_str()); produce_block(); } for(const vector<string>& o : storeops) { std::stringstream ss; ss << "(module (memory $0 " << eosio::chain::wasm_constraints::maximum_linear_memory/(64*1024) << ") (func $apply (param $0 i64) (param $1 i64) "; ss << "(" << o[0] << " offset=" << eosio::chain::wasm_constraints::maximum_linear_memory-2 << " (i32.const 0) (" << o[1] << ".const 0))"; ss << "))"; set_code(N(offsets), ss.str().c_str()); produce_block(); } for(const string& s : loadops) { std::stringstream ss; ss << "(module (memory $0 " << eosio::chain::wasm_constraints::maximum_linear_memory/(64*1024) << ") (func $apply (param $0 i64) (param $1 i64) "; ss << "(drop (" << s << " offset=" << eosio::chain::wasm_constraints::maximum_linear_memory+4 << " (i32.const 0)))"; ss << "))"; BOOST_CHECK_THROW(set_code(N(offsets), ss.str().c_str()), eosio::chain::wasm_execution_error); produce_block(); } for(const vector<string>& o : storeops) { std::stringstream ss; ss << "(module (memory $0 " << eosio::chain::wasm_constraints::maximum_linear_memory/(64*1024) << ") (func $apply (param $0 i64) (param $1 i64) "; ss << "(" << o[0] << " offset=" << eosio::chain::wasm_constraints::maximum_linear_memory+4 << " (i32.const 0) (" << o[1] << ".const 0))"; ss << "))"; BOOST_CHECK_THROW(set_code(N(offsets), ss.str().c_str()), eosio::chain::wasm_execution_error); produce_block(); } } FC_LOG_AND_RETHROW() BOOST_FIXTURE_TEST_CASE(noop, tester) try { produce_blocks(2); create_accounts( {N(noop), N(alice)} ); produce_block(); set_code(N(noop), noop_wast); set_abi(N(noop), noop_abi); const auto& accnt = control->get_database().get<account_object,by_name>(N(noop)); abi_def abi; BOOST_REQUIRE_EQUAL(abi_serializer::to_abi(accnt.abi, abi), true); abi_serializer abi_ser(abi); { produce_blocks(5); signed_transaction trx; action act; act.account = N(noop); act.name = N(anyaction); act.authorization = vector<permission_level>{{N(noop), config::active_name}}; act.data = abi_ser.variant_to_binary("anyaction", mutable_variant_object() ("from", "noop") ("type", "some type") ("data", "some data goes here") ); trx.actions.emplace_back(std::move(act)); set_tapos(trx); trx.sign(get_private_key(N(noop), "active"), chain_id_type()); push_transaction(trx); produce_block(); BOOST_REQUIRE_EQUAL(true, chain_has_transaction(trx.id())); } { produce_blocks(5); signed_transaction trx; action act; act.account = N(noop); act.name = N(anyaction); act.authorization = vector<permission_level>{{N(alice), config::active_name}}; act.data = abi_ser.variant_to_binary("anyaction", mutable_variant_object() ("from", "alice") ("type", "some type") ("data", "some data goes here") ); trx.actions.emplace_back(std::move(act)); set_tapos(trx); trx.sign(get_private_key(N(alice), "active"), chain_id_type()); push_transaction(trx); produce_block(); BOOST_REQUIRE_EQUAL(true, chain_has_transaction(trx.id())); } } FC_LOG_AND_RETHROW() // abi_serializer::to_variant failed because eosio_system_abi modified via set_abi. // This test also verifies that chain_initializer::eos_contract_abi() does not conflict // with eosio_system_abi as they are not allowed to contain duplicates. BOOST_FIXTURE_TEST_CASE(eosio_abi, tester) try { produce_blocks(2); set_code(config::system_account_name, eosio_system_wast); set_abi(config::system_account_name, eosio_system_abi); produce_block(); const auto& accnt = control->get_database().get<account_object,by_name>(config::system_account_name); abi_def abi; BOOST_REQUIRE_EQUAL(abi_serializer::to_abi(accnt.abi, abi), true); abi_serializer abi_ser(abi); abi_ser.validate(); signed_transaction trx; name a = N(alice); authority owner_auth = authority( get_public_key( a, "owner" ) ); trx.actions.emplace_back( vector<permission_level>{{config::system_account_name,config::active_name}}, contracts::newaccount{ .creator = config::system_account_name, .name = a, .owner = owner_auth, .active = authority( get_public_key( a, "active" ) ), .recovery = authority( get_public_key( a, "recovery" ) ), }); set_tapos(trx); trx.sign( get_private_key( config::system_account_name, "active" ), chain_id_type() ); auto result = push_transaction( trx ); fc::variant pretty_output; // verify to_variant works on eos native contract type: newaccount // see abi_serializer::to_abi() abi_serializer::to_variant(result, pretty_output, get_resolver()); BOOST_TEST(fc::json::to_string(pretty_output).find("newaccount") != std::string::npos); produce_block(); } FC_LOG_AND_RETHROW() BOOST_FIXTURE_TEST_CASE( test_table_key_validation, tester ) try { } FC_LOG_AND_RETHROW() //busted because of checktime, disable for now #if 0 BOOST_FIXTURE_TEST_CASE( check_table_maximum, tester ) try { produce_blocks(2); create_accounts( {N(tbl)} ); produce_block(); set_code(N(tbl), table_checker_wast); produce_blocks(1); { signed_transaction trx; action act; act.name = 555ULL<<32 | 0ULL; //top 32 is what we assert against, bottom 32 is indirect call index act.account = N(tbl); act.authorization = vector<permission_level>{{N(tbl),config::active_name}}; trx.actions.push_back(act); set_tapos(trx); trx.sign(get_private_key( N(tbl), "active" ), chain_id_type()); push_transaction(trx); } produce_blocks(1); { signed_transaction trx; action act; act.name = 555ULL<<32 | 1022ULL; //top 32 is what we assert against, bottom 32 is indirect call index act.account = N(tbl); act.authorization = vector<permission_level>{{N(tbl),config::active_name}}; trx.actions.push_back(act); set_tapos(trx); trx.sign(get_private_key( N(tbl), "active" ), chain_id_type()); push_transaction(trx); } produce_blocks(1); { signed_transaction trx; action act; act.name = 7777ULL<<32 | 1023ULL; //top 32 is what we assert against, bottom 32 is indirect call index act.account = N(tbl); act.authorization = vector<permission_level>{{N(tbl),config::active_name}}; trx.actions.push_back(act); set_tapos(trx); trx.sign(get_private_key( N(tbl), "active" ), chain_id_type()); push_transaction(trx); } produce_blocks(1); { signed_transaction trx; action act; act.name = 7778ULL<<32 | 1023ULL; //top 32 is what we assert against, bottom 32 is indirect call index act.account = N(tbl); act.authorization = vector<permission_level>{{N(tbl),config::active_name}}; trx.actions.push_back(act); set_tapos(trx); trx.sign(get_private_key( N(tbl), "active" ), chain_id_type()); //should fail, a check to make sure assert() in wasm is being evaluated correctly BOOST_CHECK_THROW(push_transaction(trx), fc::assert_exception); } produce_blocks(1); { signed_transaction trx; action act; act.name = 133ULL<<32 | 5ULL; //top 32 is what we assert against, bottom 32 is indirect call index act.account = N(tbl); act.authorization = vector<permission_level>{{N(tbl),config::active_name}}; trx.actions.push_back(act); set_tapos(trx); trx.sign(get_private_key( N(tbl), "active" ), chain_id_type()); //should fail, this element index (5) does not exist BOOST_CHECK_THROW(push_transaction(trx), eosio::chain::wasm_execution_error); } produce_blocks(1); { signed_transaction trx; action act; act.name = eosio::chain::wasm_constraints::maximum_table_elements+54334; act.account = N(tbl); act.authorization = vector<permission_level>{{N(tbl),config::active_name}}; trx.actions.push_back(act); set_tapos(trx); trx.sign(get_private_key( N(tbl), "active" ), chain_id_type()); //should fail, this element index is out of range BOOST_CHECK_THROW(push_transaction(trx), eosio::chain::wasm_execution_error); } produce_blocks(1); //run a few tests with new, proper syntax, call_indirect set_code(N(tbl), table_checker_proper_syntax_wast); produce_blocks(1); { signed_transaction trx; action act; act.name = 555ULL<<32 | 1022ULL; //top 32 is what we assert against, bottom 32 is indirect call index act.account = N(tbl); act.authorization = vector<permission_level>{{N(tbl),config::active_name}}; trx.actions.push_back(act); set_tapos(trx); trx.sign(get_private_key( N(tbl), "active" ), chain_id_type()); push_transaction(trx); } produce_blocks(1); { signed_transaction trx; action act; act.name = 7777ULL<<32 | 1023ULL; //top 32 is what we assert against, bottom 32 is indirect call index act.account = N(tbl); act.authorization = vector<permission_level>{{N(tbl),config::active_name}}; trx.actions.push_back(act); set_tapos(trx); trx.sign(get_private_key( N(tbl), "active" ), chain_id_type()); push_transaction(trx); } set_code(N(tbl), table_checker_small_wast); produce_blocks(1); { signed_transaction trx; action act; act.name = 888ULL; act.account = N(tbl); act.authorization = vector<permission_level>{{N(tbl),config::active_name}}; trx.actions.push_back(act); set_tapos(trx); trx.sign(get_private_key( N(tbl), "active" ), chain_id_type()); //an element that is out of range and has no mmap access permission either (should be a trapped segv) BOOST_CHECK_THROW(push_transaction(trx), eosio::chain::wasm_execution_error); } } FC_LOG_AND_RETHROW() #endif BOOST_AUTO_TEST_SUITE_END()
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2016. // // This software is released under a three-clause BSD license: // * 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 any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- // OpenMS includes #include <OpenMS/VISUAL/DIALOGS/SpectrumAlignmentDialog.h> #include <OpenMS/VISUAL/Spectrum1DWidget.h> // QT includes #include <QtGui/QButtonGroup> #include <vector> namespace OpenMS { SpectrumAlignmentDialog::SpectrumAlignmentDialog(Spectrum1DWidget * parent) : layer_indices_1_(), layer_indices_2_() { setupUi(this); QButtonGroup * button_group = new QButtonGroup(this); button_group->addButton(ppm); button_group->addButton(da); da->setChecked(true); Spectrum1DCanvas * cc = parent->canvas(); for (UInt i = 0; i < cc->getLayerCount(); ++i) { const LayerData & layer = cc->getLayer(i); if (layer.flipped) { layer_list_2->addItem(layer.name.toQString()); layer_indices_2_.push_back(i); } else { layer_list_1->addItem(layer.name.toQString()); layer_indices_1_.push_back(i); } } // select first item of each list if (layer_list_1->count() > 0) { layer_list_1->setCurrentRow(0); } if (layer_list_2->count() > 0) { layer_list_2->setCurrentRow(0); } } Int SpectrumAlignmentDialog::get1stLayerIndex() { if (layer_list_1->count() == 0 || layer_list_1->currentRow() == -1) { return -1; } if (layer_indices_1_.size() > (Size)(layer_list_1->currentRow())) { return layer_indices_1_[(Size)(layer_list_1->currentRow())]; } return -1; } Int SpectrumAlignmentDialog::get2ndLayerIndex() { if (layer_list_2->count() == 0 || layer_list_2->currentRow() == -1) { return -1; } if (layer_indices_2_.size() > (Size)(layer_list_2->currentRow())) { return layer_indices_2_[(Size)(layer_list_2->currentRow())]; } return -1; } } // namespace
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> START_ATF_NAMESPACE namespace vc_attributes { template<> struct licensedAttribute { }; }; // end namespace vc_attributes END_ATF_NAMESPACE
#pragma once #include "z_net_header.h" class ZLWSAInitializer { public: ZLWSAInitializer() { ::WSAStartup(MAKEWORD(2,2), &m_wsadata); } ~ZLWSAInitializer() { ::WSACleanup(); } private: WSADATA m_wsadata; };
/* Copyright 2017 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/tf2xla/xla_compiler.h" #include <numeric> #include <vector> #include "tensorflow/compiler/tf2xla/dump_graph.h" #include "tensorflow/compiler/tf2xla/functionalize_control_flow.h" #include "tensorflow/compiler/tf2xla/graph_compiler.h" #include "tensorflow/compiler/tf2xla/shape_util.h" #include "tensorflow/compiler/tf2xla/sharding_util.h" #include "tensorflow/compiler/tf2xla/tf2xla_util.h" #include "tensorflow/compiler/tf2xla/type_util.h" #include "tensorflow/compiler/tf2xla/xla_compilation_device.h" #include "tensorflow/compiler/tf2xla/xla_context.h" #include "tensorflow/compiler/xla/client/client_library.h" #include "tensorflow/core/common_runtime/device.h" #include "tensorflow/core/common_runtime/executor.h" #include "tensorflow/core/common_runtime/function.h" #include "tensorflow/core/common_runtime/graph_optimizer.h" #include "tensorflow/core/framework/attr_value_util.h" #include "tensorflow/core/graph/algorithm.h" #include "tensorflow/core/graph/graph_constructor.h" #include "tensorflow/core/graph/node_builder.h" #include "tensorflow/core/lib/hash/hash.h" #include "tensorflow/core/platform/logging.h" namespace tensorflow { namespace { // Checks that arguments `args` match types `types`. Status CheckSignature(const DataTypeVector& types, const std::vector<XlaCompiler::Argument>& args) { if (args.size() != types.size()) { return errors::Internal("Compilation arguments have ", args.size(), " elements while function has ", types.size()); } for (int i = 0; i < types.size(); ++i) { if (types[i] != args[i].type && types[i] != DT_RESOURCE) { return errors::Internal( "Argument ", i, " has declared type ", DataTypeString(args[i].type), " but function parameter has type ", DataTypeString(types[i])); } } return Status::OK(); } } // namespace bool XlaCompiler::Argument::operator==( const XlaCompiler::Argument& other) const { if (std::tie(kind, resource_kind, type, name, initialized, tensor_array_size, tensor_array_gradients) != std::tie(other.kind, other.resource_kind, other.type, other.name, other.initialized, other.tensor_array_size, other.tensor_array_gradients)) { return false; } if (shape != other.shape) { return false; } if (constant_value.shape() != other.constant_value.shape()) { return false; } return constant_value.tensor_data() == other.constant_value.tensor_data(); } XlaCompiler::XlaCompiler(XlaCompiler::Options options) : options_(options), initialization_status_(Status::OK()), next_step_id_(1), device_( new XlaCompilationDevice(SessionOptions(), *options_.device_type)), device_mgr_({device_}) { // We no longer need the device_type. options_.device_type = nullptr; if (options_.populate_resource_manager) { initialization_status_ = (*options_.populate_resource_manager)(device_->resource_manager()); } local_flib_def_.reset(new FunctionLibraryDefinition(OpRegistry::Global(), FunctionDefLibrary{})); local_pflr_.reset(new ProcessFunctionLibraryRuntime( &device_mgr_, Env::Default(), options.graph_def_version, local_flib_def_.get(), OptimizerOptions(), nullptr /* custom_kernel_creator */)); pflr_.reset(new ProcessFunctionLibraryRuntime( &device_mgr_, Env::Default(), options.graph_def_version, options.flib_def, OptimizerOptions(), nullptr /* custom_kernel_creator */)); local_flib_runtime_ = local_pflr_->GetFLR(device_->name()); flib_runtime_ = pflr_->GetFLR(device_->name()); // The default shape representation function is the identity. if (!options_.shape_representation_fn) { options_.shape_representation_fn = [](const TensorShape& shape, DataType type) { return shape; }; } } XlaCompiler::~XlaCompiler() = default; int64 XlaCompiler::NextStepId() { return next_step_id_++; } uint64 XlaCompiler::SignatureHash::operator()( const std::pair<string, std::vector<Argument>>& signature) const { return std::hash<string>()(signature.first); } static Status GetFunctionBody(const NameAttrList& function, FunctionLibraryRuntime* flib_runtime, const FunctionBody** fbody) { FunctionLibraryRuntime::Handle handle; TF_RETURN_IF_ERROR(flib_runtime->Instantiate( function.name(), AttrSlice(&function.attr()), &handle)); *fbody = flib_runtime->GetFunctionBody(handle); TF_RET_CHECK(*fbody); return Status::OK(); } Status XlaCompiler::FindFunctionBody(const NameAttrList& function, const FunctionBody** fbody) { // The function may be in either the local_flib_runtime_ or flib_runtime_. // Look up the function in local first and if it is not found then look up the // function in flib_runtime_. auto status = GetFunctionBody(function, local_flib_runtime_, fbody); if (!status.ok()) { if (!errors::IsNotFound(status)) { return status; } TF_RETURN_WITH_CONTEXT_IF_ERROR( GetFunctionBody(function, flib_runtime_, fbody), "Local lookup failed with: ", status.error_message()); } return Status::OK(); } std::unique_ptr<Graph> XlaCompiler::GetGraph(const FunctionBody* fbody) { std::unique_ptr<Graph> graph(new Graph(options_.flib_def)); CopyGraph(*fbody->graph, graph.get()); OptimizerOptions opts; opts.set_opt_level(OptimizerOptions::L0); opts.set_do_common_subexpression_elimination(false); opts.set_do_function_inlining(true); opts.set_do_constant_folding(true); GraphOptimizer optimizer(opts); optimizer.Optimize(flib_runtime_, flib_runtime_->env(), /*device=*/nullptr, &graph, /*shape_map=*/nullptr); return graph; } Status XlaCompiler::CompileFunction(const XlaCompiler::CompileOptions& options, const NameAttrList& function, std::vector<XlaCompiler::Argument> args, XlaCompiler::CompilationResult* result) { const string function_id = Canonicalize(function.name(), AttrSlice(&function.attr())); VLOG(1) << "XlaCompiler::CompileFunction " << function_id; auto it = cache_.find({function_id, args}); if (it != cache_.end()) { *result = it->second; return Status::OK(); } const FunctionBody* fbody; TF_RETURN_IF_ERROR(FindFunctionBody(function, &fbody)); TF_RETURN_WITH_CONTEXT_IF_ERROR( CheckSignature(fbody->arg_types, args), "Signature check failure while compiling: ", function.name()); std::unique_ptr<Graph> graph = GetGraph(fbody); // _Arg and _Retval nodes don't exist in the stored subgraph for the function; // they are added by the function body looked up. Therefore, they don't have // core assignments here. // Attempt to assign a core to each _Retval and _Arg. Chooses the // lowest-numbered core that consumes the argument. We choose the // lowest-numbered core so the assignment is deterministic. for (Node* n : graph->nodes()) { if (StringPiece(n->type_string()) == "_Arg") { TF_RETURN_IF_ERROR(SetNodeShardingFromNeighbors(n, /*out_edges=*/true)); } } // Do _Retval as a second loop, in case the retval's input is an _Arg (which // may have gotten a device assignment from the first loop). for (Node* n : graph->nodes()) { if (StringPiece(n->type_string()) == "_Retval") { TF_RETURN_IF_ERROR(SetNodeShardingFromNeighbors(n, /*out_edges=*/false)); } } if (VLOG_IS_ON(2)) { VLOG(2) << "XlaCompiler::CompileFunction: " << dump_graph::DumpGraphToFile( strings::StrCat("xla_compile_function_", function_id), *graph); } VLOG(1) << "===================================================="; TF_RETURN_IF_ERROR( CompileGraph(options, function_id, std::move(graph), args, result)); VLOG(1) << "===================================================="; cache_[{function_id, args}] = *result; return Status::OK(); } // Computes the XLA shape for argument 'arg'. Status XlaCompiler::XLAShapeForArgument(const XlaCompiler::Argument& arg, bool is_entry_computation, xla::Shape* xla_shape) { switch (arg.kind) { case XlaCompiler::Argument::kConstant: LOG(FATAL) << "Unreachable case"; case XlaCompiler::Argument::kParameter: { TensorShape shape = is_entry_computation ? options_.shape_representation_fn(arg.shape, arg.type) : arg.shape; return TensorShapeToXLAShape(arg.type, shape, xla_shape); } case XlaCompiler::Argument::kResource: { TF_RET_CHECK(arg.initialized); switch (arg.resource_kind) { case XlaResource::kVariable: { TensorShape representation_shape = options_.shape_representation_fn(arg.shape, arg.type); return TensorShapeToXLAShape(arg.type, representation_shape, xla_shape); } case XlaResource::kTensorArray: { if (arg.tensor_array_size < 0) { return errors::InvalidArgument( "Negative tensor_array_size in XLAShapeForArgument"); } TensorShape shape; shape.AddDim(arg.tensor_array_size); shape.AppendShape(arg.shape); TF_RETURN_IF_ERROR(TensorShapeToXLAShape(arg.type, shape, xla_shape)); if (!arg.tensor_array_gradients.empty()) { std::vector<xla::Shape> tuple_shape( arg.tensor_array_gradients.size() + 1, *xla_shape); *xla_shape = xla::ShapeUtil::MakeTupleShape(tuple_shape); } return Status::OK(); } case XlaResource::kStack: { if (arg.tensor_array_size < 0) { return errors::InvalidArgument( "Negative tensor_array_size in XLAShapeForArgument"); } TensorShape shape; shape.AddDim(arg.tensor_array_size); shape.AppendShape(arg.shape); xla::Shape buffer_shape; TF_RETURN_IF_ERROR( TensorShapeToXLAShape(arg.type, shape, &buffer_shape)); *xla_shape = xla::ShapeUtil::MakeTupleShape( {buffer_shape, xla::ShapeUtil::MakeShape(xla::S32, {})}); return Status::OK(); } case XlaResource::kInvalid: return errors::Internal( "Invalid resource type in XLAShapeForArgument()"); } } case XlaCompiler::Argument::kInvalid: return errors::Internal("Invalid argument type in XLAShapeForArgument()"); } } namespace { Status ExecuteGraph(XlaContext* xla_context, std::unique_ptr<Graph> graph, XlaCompilationDevice* device, FunctionLibraryRuntime* flib, int64 step_id) { // Resource cleanup is a bit messy. XlaContext is a ref-countd resource; the // resource manager takes ownership via Create, and unrefs via Cleanup. We // explicitly add a reference to ensure the refcount at entry is maintained at // all exit points; Create and Cleanup are always called in this function. // // The Executor requires us to use ScopedStepContainer. We wrap it in a // unique_ptr so we can capture the cleanup status in the end. xla_context->Ref(); Status status; auto step_container = xla::MakeUnique<ScopedStepContainer>( step_id, [&status, device](const string& name) { status = device->resource_manager()->Cleanup(name); }); TF_RETURN_IF_ERROR(device->resource_manager()->Create( step_container->name(), XlaContext::kXlaContextResourceName, xla_context)); GraphCompiler graph_compiler(xla_context, device, graph.get(), flib, step_container.get()); TF_RETURN_IF_ERROR(graph_compiler.Compile()); // Explicitly clean up the step container, to capture the cleanup status. step_container.reset(); return Status::OK(); } // Builds the XLA computation. // // `retvals` is the list of retvals produced by _Retval operators, in index // order. `variable_map` is a map from variable ID numbers to XlaOpContext // variable states, generated by the symbolic evaluation. // If `return_updated_values_for_all_resources` is true, all resources will be // included in `resource_updates`, regardless of whether their value changed. // Sets `*num_nonconst_outputs` to the number of outputs of the `computation`. // Sets `*resource_updates` to a description of resources whose values are // written by the computation; the variable writes are the last // `resource_updates.size()` return values from the computation. Each entry in // `resource_updates` is a (input_index, type) pair, where `input_index` is the // index of a resource variable argument to the computation, and `type` is the // type of the final output. Status BuildComputation( const std::vector<XlaCompiler::Argument>& args, const std::vector<int>& arg_cores, const std::vector<XlaContext::Retval>& retvals, const std::vector<std::unique_ptr<XlaResource>>& resources, bool return_updated_values_for_all_resources, xla::XlaBuilder* builder, xla::XlaComputation* computation, int* num_computation_outputs, int* num_nonconst_outputs, std::vector<XlaCompiler::OutputDescription>* outputs, std::vector<XlaCompiler::ResourceUpdate>* resource_updates) { std::vector<xla::XlaOp> elems; elems.reserve(retvals.size()); for (int i = 0; i < retvals.size(); ++i) { XlaCompiler::OutputDescription& output = (*outputs)[i]; output.type = retvals[i].type; output.shape = retvals[i].shape; const XlaExpression& retval = retvals[i].expression; if (retval.has_constant_value()) { output.is_constant = true; output.constant_value = retval.constant_value(); } else { output.is_constant = false; elems.push_back(retval.handle()); } } *num_nonconst_outputs = elems.size(); // Add return values for resources whose values have changed. std::vector<const XlaResource*> arg_resources; arg_resources.reserve(resources.size()); for (const auto& resource : resources) { if (resource->arg_num() >= 0) { arg_resources.push_back(resource.get()); } } std::sort(arg_resources.begin(), arg_resources.end(), [](const XlaResource* a, const XlaResource* b) { return a->arg_num() < b->arg_num(); }); // Attach a common operator name as metadata. This has no semantic effect — it // merely makes the HLO graph more readable when visualized via TensorBoard, // since TensorBoard forms groups out of operators with similar names. xla::OpMetadata retval_metadata; retval_metadata.set_op_name("XLA_Retvals"); builder->SetOpMetadata(retval_metadata); for (const XlaResource* resource : arg_resources) { const XlaCompiler::Argument& arg = args[resource->arg_num()]; const int core = arg_cores[resource->arg_num()]; DCHECK_LT(resource->arg_num(), arg_cores.size()); bool modified = resource->value() != resource->initial_value(); // TensorArray gradients were modified if their values changed or there are // any newly created gradients. for (const auto& grad : resource->tensor_array_gradients()) { modified = modified || grad.second->value() != grad.second->initial_value() || arg.tensor_array_gradients.count(grad.first) == 0; } if (return_updated_values_for_all_resources || modified) { resource_updates->emplace_back(); XlaCompiler::ResourceUpdate& update = resource_updates->back(); update.input_index = resource->arg_num(); update.type = resource->type(); update.shape = resource->shape(); update.modified = modified; for (const auto& grad : resource->tensor_array_gradients()) { update.tensor_array_gradients_accessed.insert(grad.first); } // Request that the value be returned on a specific core. xla::XlaScopedShardingAssignment assign_sharding( builder, core == -1 ? tensorflow::gtl::optional<xla::OpSharding>() : xla::sharding_builder::AssignDevice(core)); xla::XlaOp handle; TF_RETURN_IF_ERROR(resource->Pack(&handle, builder)); // Since we can't change the sharding metadata of <value> as this point, // create a tuple/get-tuple-element combination so that sharding // assignment will be placed on this value, which will cause the resource // update to be returned from the same device that provided the resource. handle = builder->GetTupleElement(builder->Tuple({handle}), 0); elems.push_back(handle); } } *num_computation_outputs = elems.size(); // Builds the XLA computation. builder->Tuple(elems); builder->ClearOpMetadata(); xla::StatusOr<xla::XlaComputation> computation_status = builder->Build(); if (!computation_status.ok()) { return computation_status.status(); } *computation = computation_status.ConsumeValueOrDie(); return Status::OK(); } } // namespace // Builds XLA computations for each of the arguments to the computation. // `args` are the arguments to the computation. Status XlaCompiler::BuildArguments( const Graph& graph, const std::vector<XlaCompiler::Argument>& args, bool use_tuple_arg, xla::XlaBuilder* builder, XlaContext* context, std::vector<int>* arg_cores, std::vector<XlaExpression>* arg_expressions, std::vector<int>* input_mapping, std::vector<xla::Shape>* input_shapes, bool is_entry_computation) { arg_expressions->resize(args.size()); *arg_cores = std::vector<int>(args.size(), -1); // Argument numbers of arguments and resources that are to be passed to the // XLA computation as runtime parameters. input_mapping->clear(); input_mapping->reserve(args.size()); std::vector<int> resources; resources.reserve(args.size()); // Fills in constant arguments, and computes non-constant argument order. for (std::vector<XlaCompiler::Argument>::size_type i = 0; i < args.size(); ++i) { const XlaCompiler::Argument& arg = args[i]; XlaExpression& arg_expression = (*arg_expressions)[i]; switch (arg.kind) { case XlaCompiler::Argument::kResource: TF_RET_CHECK(arg.resource_kind != XlaResource::kInvalid); // TODO(phawkins): this code assumes that resource arguments do not // alias. XlaResource* resource; TF_RETURN_IF_ERROR(context->CreateResource( arg.resource_kind, i, arg.name, arg.type, arg.shape, xla::XlaOp(), /*tensor_array_size=*/arg.tensor_array_size, /*tensor_array_gradients=*/arg.tensor_array_gradients, &resource)); arg_expression.set_resource(resource); if (arg.initialized) { resources.push_back(i); } break; case XlaCompiler::Argument::kParameter: { input_mapping->push_back(i); break; } case XlaCompiler::Argument::kConstant: arg_expression.set_constant_value(arg.constant_value); break; case XlaCompiler::Argument::kInvalid: return errors::Internal("Unreachable case in BuildArguments()"); } } // Append parameters containing variable values after the other runtime // parameters. input_mapping->insert(input_mapping->end(), resources.begin(), resources.end()); if (input_mapping->empty()) { return Status::OK(); } std::vector<xla::Shape> arg_shapes(input_mapping->size()); for (std::vector<int>::size_type i = 0; i < input_mapping->size(); ++i) { // Computes the shapes of non-constant arguments. TF_RETURN_IF_ERROR(XLAShapeForArgument( args[(*input_mapping)[i]], is_entry_computation, &arg_shapes[i])); } if (use_tuple_arg) { input_shapes->push_back(xla::ShapeUtil::MakeTupleShape(arg_shapes)); } else { *input_shapes = arg_shapes; } // Use the _Arg nodes in the graph to resolve core assignments. for (const Node* n : graph.nodes()) { if (StringPiece(n->type_string()) != "_Arg") continue; int index; TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), "index", &index)); TF_RET_CHECK(index >= 0 && index < args.size()) << "_Arg out of bounds: " << index << " vs " << args.size(); TF_ASSIGN_OR_RETURN( auto sharding, ParseShardingFromDevice(*n, std::numeric_limits<int32>::max())); if (sharding.has_value()) { TF_RET_CHECK(sharding.value().type() == xla::OpSharding::Type::OpSharding_Type_MAXIMAL); const int core = sharding.value().tile_assignment_devices(0); if ((*arg_cores)[index] == -1 || core < (*arg_cores)[index]) { (*arg_cores)[index] = core; } } } // Attach a common operator name as metadata. This has no semantic effect — it // merely makes the HLO graph more readable when visualized via TensorBoard, // since TensorBoard forms groups out of operators with similar names. xla::OpMetadata arg_metadata; arg_metadata.set_op_name("XLA_Args"); builder->SetOpMetadata(arg_metadata); // Build parameter handles for non-constant arguments. std::vector<xla::XlaOp> arg_handles(input_mapping->size()); if (use_tuple_arg) { xla::XlaOp tuple; if (is_entry_computation) { xla::OpSharding tuple_sharding; tuple_sharding.set_type(xla::OpSharding::Type::OpSharding_Type_TUPLE); for (int64 parameter : *input_mapping) { const int core = (*arg_cores)[parameter]; const int root_device = 0; *tuple_sharding.add_tuple_shardings() = core == -1 ? xla::sharding_builder::AssignDevice(root_device) : xla::sharding_builder::AssignDevice(core); } xla::XlaScopedShardingAssignment assign_tuple_sharding(builder, tuple_sharding); tuple = builder->Parameter(0, (*input_shapes)[0], "arg_tuple"); } else { tuple = builder->Parameter(0, (*input_shapes)[0], "arg_tuple"); } for (std::vector<int>::size_type i = 0; i < input_mapping->size(); ++i) { const int core = (*arg_cores)[input_mapping->at(i)]; xla::XlaScopedShardingAssignment assign_sharding( builder, core == -1 ? tensorflow::gtl::optional<xla::OpSharding>() : xla::sharding_builder::AssignDevice(core)); arg_handles[i] = builder->GetTupleElement(tuple, i); } } else { for (std::vector<int>::size_type i = 0; i < input_mapping->size(); ++i) { const int core = (*arg_cores)[input_mapping->at(i)]; xla::XlaScopedShardingAssignment assign_sharding( builder, core == -1 ? tensorflow::gtl::optional<xla::OpSharding>() : xla::sharding_builder::AssignDevice(core)); arg_handles[i] = builder->Parameter(i, (*input_shapes)[i], strings::StrCat("arg", i)); } } builder->ClearOpMetadata(); // Fill in the handles in non-constant arguments, and reshape parameters // back to their correct shapes. VLOG(2) << "XLA computation inputs:"; for (std::vector<int>::size_type i = 0; i < input_mapping->size(); ++i) { const XlaCompiler::Argument& arg = args[input_mapping->at(i)]; VLOG(2) << " XLA arg " << i << " shape: " << xla::ShapeUtil::HumanString(arg_shapes[i]) << " name: " << arg.name << " TF arg " << input_mapping->at(i); XlaExpression& arg_expression = (*arg_expressions)[input_mapping->at(i)]; switch (arg.kind) { case XlaCompiler::Argument::kResource: { TF_RET_CHECK(arg.initialized); XlaResource* resource = arg_expression.resource(); TF_RETURN_IF_ERROR(resource->SetFromPack(arg.tensor_array_gradients, arg_handles[i], builder)); VLOG(2) << " resource: num_gradients: " << arg.tensor_array_gradients.size(); break; } case XlaCompiler::Argument::kParameter: // Reshape parameters back to their correct shapes. // TODO(b/76097077): propagate device assignments onto arguments and // return values of functions, and then reshape unconditionally. if (is_entry_computation) { arg_expression.set_handle( builder->Reshape(arg_handles[i], arg.shape.dim_sizes())); } else { arg_expression.set_handle(arg_handles[i]); } break; case XlaCompiler::Argument::kConstant: case XlaCompiler::Argument::kInvalid: return errors::Internal("Unreachable case in BuildArguments()"); } } return Status::OK(); } Status XlaCompiler::CompileSingleOp( const XlaCompiler::CompileOptions& options, string const& name, OpKernelContext* ctx, const std::vector<XlaCompiler::Argument>& args, CompilationResult* result) { // TODO(b/74182462): We implement this by creating a new dummy Graph including // _Arg nodes, and let CompileGraph walk it. This could be optimized. std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); Status status; // First create the actual node we care about computing. Node* main_node = graph->AddNode(ctx->op_kernel().def(), &status); TF_RETURN_IF_ERROR(status); // Create dummy _Arg nodes. Link these to `node` and also via a control // dependency edge to the _SOURCE node. for (int64 i = 0; i < ctx->num_inputs(); ++i) { Node* node; string name = strings::StrCat(ctx->op_kernel().name(), "_", i, "_arg"); Status status = NodeBuilder(name, "_Arg") .ControlInput(graph->source_node()) .Attr("T", ctx->input_dtype(i)) .Attr("index", i) .Finalize(graph.get(), &node); TF_RETURN_IF_ERROR(status); graph->AddEdge(node, 0, main_node, i); } // Similarly with return values, create dummy _Retval nodes fed by `node`. for (int64 i = 0; i < ctx->num_outputs(); ++i) { Node* node; string name = strings::StrCat(ctx->op_kernel().name(), "_", i, "_retval"); Status status = NodeBuilder(name, "_Retval") .Input(main_node, i) .Attr("T", ctx->expected_output_dtype(i)) .Attr("index", i) .Finalize(graph.get(), &node); TF_RETURN_IF_ERROR(status); } return CompileGraph(options, name, std::move(graph), args, result); } Status XlaCompiler::CompileGraph(const XlaCompiler::CompileOptions& options, string const& name, std::unique_ptr<Graph> graph, const std::vector<XlaCompiler::Argument>& args, CompilationResult* result) { VLOG(1) << "Executing graph symbolically to populate XlaBuilder."; if (VLOG_IS_ON(2)) { VLOG(2) << "XlaCompiler::CompileGraph: " << dump_graph::DumpGraphToFile( strings::StrCat("xla_compile_graph_", name), *graph); } // Report the error here if initialization failed. TF_RETURN_IF_ERROR(initialization_status_); // Converts Tensorflow's graph control-flow constructs into functional // control-flow that can be compiled into XLA code. TF_RETURN_IF_ERROR( FunctionalizeControlFlow(flib_runtime_->GetFunctionLibraryDefinition(), graph.get(), local_flib_def_.get())); xla::XlaBuilder builder(name); XlaContext* context = new XlaContext( this, &builder, options_.allow_cpu_custom_calls, options.resolve_compile_time_constants, options.is_entry_computation, &options_.shape_representation_fn); core::ScopedUnref context_unref(context); std::vector<XlaExpression> arg_expressions; std::vector<int> arg_cores; TF_RETURN_IF_ERROR( BuildArguments(*graph, args, options.use_tuple_arg, &builder, context, &arg_cores, &arg_expressions, &result->input_mapping, &result->xla_input_shapes, options.is_entry_computation)); context->set_args(std::move(arg_expressions)); TF_RETURN_IF_ERROR(ExecuteGraph(context, std::move(graph), device_, flib_runtime_, NextStepId())); int num_nonconst_outputs; int num_computation_outputs; result->computation = std::make_shared<xla::XlaComputation>(); result->outputs.resize(context->retvals().size()); TF_RETURN_IF_ERROR(BuildComputation( args, arg_cores, context->retvals(), context->resources(), options.return_updated_values_for_all_resources, &builder, result->computation.get(), &num_computation_outputs, &num_nonconst_outputs, &result->outputs, &result->resource_updates)); VLOG(2) << "Outputs: total: " << context->retvals().size() << " nonconstant: " << num_nonconst_outputs; // Compute the XLA output shape, if there is a computation with non-constant // outputs. TF_ASSIGN_OR_RETURN(std::unique_ptr<xla::ProgramShape> computation_shape, client()->GetComputationShape(*result->computation)); result->xla_output_shape.Swap(computation_shape->mutable_result()); VLOG(2) << "XLA output shape: " << xla::ShapeUtil::HumanString(result->xla_output_shape); // Copy the host transfer metadata to the result. for (const auto& send : host_compute_sends_) { *result->host_compute_metadata.add_device_to_host() = send.second; } for (const auto& recv : host_compute_recvs_) { *result->host_compute_metadata.add_host_to_device() = recv.second; } // Tensorflow expects a major-to-minor order of results. xla::LayoutUtil::SetToDefaultLayout(&result->xla_output_shape); return Status::OK(); } Status XlaCompiler::GetChannelHandle(const string& key, xla::ChannelHandle* channel) { auto result = channels_.emplace(key, xla::ChannelHandle()); if (result.second) { TF_ASSIGN_OR_RETURN(result.first->second, client()->CreateChannelHandle()); } *channel = result.first->second; VLOG(1) << "Channel: " << key << " " << channel->DebugString(); return Status::OK(); } namespace { void SetTransfer(const string& key, gtl::ArraySlice<DataType> types, gtl::ArraySlice<TensorShape> shapes, tf2xla::HostTransferMetadata* transfer) { transfer->set_key(key); CHECK(types.size() == shapes.size()); for (int i = 0; i < types.size(); ++i) { tf2xla::TensorMetadata* metadata = transfer->add_metadata(); metadata->set_type(types[i]); shapes[i].AsProto(metadata->mutable_shape()); } } } // namespace Status XlaCompiler::SetDeviceToHostMetadata( const string& key, gtl::ArraySlice<DataType> types, gtl::ArraySlice<TensorShape> shapes) { if (host_compute_sends_.find(key) != host_compute_sends_.end()) { return errors::InvalidArgument( "Duplicate calls to SetDeviceToHostMetadata with key ", key); } tf2xla::HostTransferMetadata& transfer = host_compute_sends_[key]; SetTransfer(key, types, shapes, &transfer); return Status::OK(); } Status XlaCompiler::GetDeviceToHostShapes( const string& key, std::vector<TensorShape>* shapes) const { const auto iter = host_compute_sends_.find(key); if (iter == host_compute_sends_.end()) { return errors::InvalidArgument( "No host compute send shapes registered for key ", key); } shapes->clear(); for (int i = 0; i < iter->second.metadata_size(); ++i) { TensorShape shape(iter->second.metadata(i).shape()); shapes->push_back(shape); } return Status::OK(); } Status XlaCompiler::SetHostToDeviceMetadata( const string& key, gtl::ArraySlice<DataType> types, gtl::ArraySlice<TensorShape> shapes) { if (host_compute_recvs_.find(key) != host_compute_sends_.end()) { return errors::InvalidArgument( "Duplicate calls to SetHostToDeviceMetadata with key ", key); } tf2xla::HostTransferMetadata& transfer = host_compute_recvs_[key]; SetTransfer(key, types, shapes, &transfer); return Status::OK(); } Status XlaCompiler::GetHostComputeControlDependency( const string& host_compute_name, xla::XlaOp* handle) { const auto iter = host_compute_control_output_.find(host_compute_name); if (iter == host_compute_control_output_.end()) { return errors::InvalidArgument( "No registered control handle for host compute Op '", host_compute_name, "'"); } else { *handle = iter->second; } return Status::OK(); } Status XlaCompiler::SetHostComputeControlDependency( const string& host_compute_name, const xla::XlaOp& handle) { if (host_compute_control_output_.find(host_compute_name) != host_compute_control_output_.end()) { return errors::InvalidArgument( "Duplicate control handles registered for for host compute Op ", host_compute_name); } host_compute_control_output_[host_compute_name] = handle; return Status::OK(); } } // namespace tensorflow
#include <iostream> #include <vector> #include <algorithm> #include <functional> using namespace std; class Rectangle { double w; double h; public: Rectangle(double w, double h) : w(w), h(h) {} Rectangle(double s = 1.0) : w(s), h(s) {} bool IsSquare(){ return w == h; } }; struct P2 { double x; double y; P2(double x, double y) : x(x), y(y) {} P2() : x(0.0), y(0.0) {} }; int main(){ Rectangle rects[] = { Rectangle(10), Rectangle(10, 20), Rectangle(20), Rectangle(20, 40), Rectangle(40) }; vector<Rectangle> vrects(&rects[0], &rects[0] + sizeof(rects) / sizeof(rects[0])); cout << count_if(vrects.begin(), vrects.end(), mem_fn(&Rectangle::IsSquare)) << endl; // P2 pts[] = { // P2(), P2(10.0, 10.0), P2(60.0, 10.0), P2(50.0, 0.0) // }; static const int arr[] = { 16, 2, 77, 29 }; vector<int> vec(arr, arr + sizeof(arr) / sizeof(arr[0])); return 0; }
/* This file is part of: NoahFrame https://github.com/ketoo/NoahGameFrame Copyright 2009 - 2019 NoahFrame(NoahGameFrame) File creator: lvsheng.huang NoahFrame is open-source software and you can redistribute it and/or modify it under the terms of the License; besides, anyone who use this file/software must include this copyright announcement. 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 "NFItemModule.h" bool NFItemModule::Init() { m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>(); m_pLogModule = pPluginManager->FindModule<NFILogModule>(); m_pNetModule = pPluginManager->FindModule<NFINetModule>(); m_pPackModule = pPluginManager->FindModule<NFIPackModule>(); m_pElementModule = pPluginManager->FindModule<NFIElementModule>(); m_pLogicClassModule = pPluginManager->FindModule<NFIClassModule>(); m_pPropertyModule = pPluginManager->FindModule<NFIPropertyModule>(); m_pHeroModule = pPluginManager->FindModule<NFIHeroModule>(); m_pCommonConfigModule = pPluginManager->FindModule<NFICommonConfigModule>(); m_pGameServerNet_ServerModule = pPluginManager->FindModule<NFIGameServerNet_ServerModule>(); m_pEventModule = pPluginManager->FindModule<NFIEventModule>(); m_pItemConsumeManagerModule = pPluginManager->FindModule<NFIItemConsumeManagerModule>(); return true; } bool NFItemModule::Shut() { return true; } bool NFItemModule::Execute() { return true; } bool NFItemModule::AfterInit() { m_pKernelModule->AddClassCallBack(NFrame::Player::ThisName(), this, &NFItemModule::OnClassObjectEvent); CheckConfig(); ////////////////////////////////////////////////////////////////////////// // add msg handler if (!m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_ITEM_OBJECT, this, &NFItemModule::OnClientUseItem)) { return false; } if (!m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_PICK_ITEM, this, &NFItemModule::OnClientPickItem)) { return false; } return true; } bool NFItemModule::UseItem(const NFGUID & self, const std::string & strItemID, const NFGUID & xTargetID, const NFVector3& vector) { int nCount = 1; if (!m_pElementModule->ExistElement(strItemID) || !m_pKernelModule->GetObject(xTargetID)) { return false; } if (!ConsumeDataItemProperty(self, strItemID)) { return false; } if (!m_pPackModule->DeleteItem(self, strItemID, nCount)) { return false; } NFMsg::EItemType eItemType = (NFMsg::EItemType)m_pElementModule->GetPropertyInt(strItemID, NFrame::Item::ItemType()); NF_SHARE_PTR<NFIItemConsumeocessModule> pConsumeProcessModule = m_pItemConsumeManagerModule->GetConsumeModule(eItemType); if (!pConsumeProcessModule) { return false; } switch (eItemType) { case NFMsg::EItemType::EIT_EQUIP: case NFMsg::EItemType::EIT_GEM: case NFMsg::EItemType::EIT_SCROLL: { if (pConsumeProcessModule->ConsumeLegal(self, strItemID, NFDataList(), vector) == 0) { pConsumeProcessModule->ConsumeProcess(self, strItemID, NFDataList(), vector); } } break; case NFMsg::EItemType::EIT_SUPPLY: { NFDataList xTarget; xTarget.AddObject(xTargetID); xTarget.AddString(strItemID); //this is Item Config ID xTarget.AddInt(nCount); //this is Item Count to Consume if (pConsumeProcessModule->ConsumeLegal(self, strItemID, xTarget, vector) == 0) { pConsumeProcessModule->ConsumeProcess(self, strItemID, xTarget, vector); } } break; break; default: break; } return false; } int NFItemModule::OnClassObjectEvent(const NFGUID& self, const std::string& strClassNames, const CLASS_OBJECT_EVENT eClassEvent, const NFDataList& var) { if (CLASS_OBJECT_EVENT::COE_DESTROY == eClassEvent) { } else if (CLASS_OBJECT_EVENT::COE_CREATE_FINISH == eClassEvent) { m_pEventModule->AddEventCallBack(self, NFED_ON_CLIENT_REQUIRE_USE_ITEM_POS, this, &NFItemModule::OnRequireUseItemPosEvent); } return 0; } int NFItemModule::OnRequireUseItemPosEvent(const NFGUID& self, const NFEventDefine nEventID, const NFDataList& var) { return 0; } bool NFItemModule::CheckConfig() { NF_SHARE_PTR<NFIClass> pLogicCLass = m_pLogicClassModule->GetElement(NFrame::Item::ThisName()); if (nullptr == pLogicCLass) { assert(0); } const std::vector<std::string>& strIdList = pLogicCLass->GetIDList(); for (int i = 0; i < strIdList.size(); ++i) { const std::string& strConfigID = strIdList[i]; NF_SHARE_PTR<NFIPropertyManager> pPropertyManager = m_pElementModule->GetPropertyManager(strConfigID); if (!pPropertyManager) { assert(0); } int nType = m_pElementModule->GetPropertyInt32(strConfigID, NFrame::Item::ItemType()); if (nType < 0) { assert(0); } int nSubType = m_pElementModule->GetPropertyInt32(strConfigID, NFrame::Item::ItemSubType()); if (nSubType < 0) { assert(0); } int nLevel = m_pElementModule->GetPropertyInt32(strConfigID, NFrame::Item::Level()); if (nLevel < 0) { assert(0); } int nQuality = m_pElementModule->GetPropertyInt32(strConfigID, NFrame::Item::Quality()); if (nQuality < 0) { assert(0); } //int nCoolDown = m_pElementModule->GetPropertyInt32(strConfigID, NFrame::Item::CoolDownTime()); //if (nCoolDown <= 0) //{ // assert(0); //} int nOverlayCount = m_pElementModule->GetPropertyInt32(strConfigID, NFrame::Item::OverlayCount()); if (nOverlayCount <= 0) { assert(0); } int nBuyPrice = m_pElementModule->GetPropertyInt32(strConfigID, NFrame::Item::BuyPrice()); int nSalePrice = m_pElementModule->GetPropertyInt32(strConfigID, NFrame::Item::SalePrice()); //if (nSalePrice <= 0 || nBuyPrice <= 0) if (nSalePrice < 0 || nBuyPrice < 0) { assert(0); } } return true; } int NFItemModule::AddItemEffectDataProperty(const NFGUID& self, const NFGUID& xTarget, const std::string& strItemID) { if (strItemID.empty()) { return 1; } ////////////////////////////////////////////////////////////////////////// NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject(xTarget); if (NULL == pObject) { //m_pLogModule->LogObject(NFILogModule::NLL_ERROR_NORMAL, self, "There is no object", __FUNCTION__, __LINE__); return 1; } ////////////////////////////////////////////////////////////////////////// NF_SHARE_PTR<NFIPropertyManager> pPropertyManager = m_pElementModule->GetPropertyManager(strItemID); if (!pPropertyManager) { return 1; } NF_SHARE_PTR<NFIProperty> pEffectDataProperty = pPropertyManager->GetElement(NFrame::Item::EffectData()); if (!pEffectDataProperty) { return 1; } NF_SHARE_PTR<NFIPropertyManager> pEffectDataPropertyManager = m_pElementModule->GetPropertyManager(pEffectDataProperty->GetString()); if (!pEffectDataPropertyManager) { return 1; } NF_SHARE_PTR<NFIProperty> pProperty = pEffectDataPropertyManager->First(); while (pProperty) { if (pProperty->GetInt() != 0) { m_pPropertyModule->CalculatePropertyValue(xTarget, pProperty->GetKey(), NFIPropertyModule::NPG_EQUIP, pProperty->GetInt()); } pProperty = pEffectDataPropertyManager->Next(); } return 0; } bool NFItemModule::ConsumeDataItemProperty(const NFGUID& self, const std::string& strID) { if (strID.empty()) { return false; } //const int nVIPEXP = m_pElementModule->GetPropertyInt32(strID, NFrame::ConsumeData::VIPEXP()); //const int64_t nEXP = m_pElementModule->GetPropertyInt(strID, NFrame::ConsumeData::EXP()); const int nHP = m_pElementModule->GetPropertyInt32(strID, NFrame::ConsumeData::HP()); const int nSP = m_pElementModule->GetPropertyInt32(strID, NFrame::ConsumeData::SP()); const int nMP = m_pElementModule->GetPropertyInt32(strID, NFrame::ConsumeData::MP()); const int64_t nGold = m_pElementModule->GetPropertyInt(strID, NFrame::ConsumeData::Gold()); const int nDiamond = m_pElementModule->GetPropertyInt32(strID, NFrame::ConsumeData::Diamond()); if (nGold > 0 && !m_pPropertyModule->EnoughGold(self, nGold)) { return false; } if (nHP > 0 && !m_pPropertyModule->EnoughHP(self, nHP)) { return false; } if (nDiamond > 0 && !m_pPropertyModule->EnoughDiamond(self, nDiamond)) { return false; } if (nMP > 0 && !m_pPropertyModule->EnoughMP(self, nMP)) { return false; } if (nSP > 0 && !m_pPropertyModule->EnoughSP(self, nSP)) { return false; } ////// if (nGold > 0 && !m_pPropertyModule->ConsumeGold(self, nGold)) { return false; } if (nHP > 0 && !m_pPropertyModule->ConsumeHP(self, nHP)) { return false; } if (nDiamond > 0 && !m_pPropertyModule->ConsumeDiamond(self, nDiamond)) { return false; } if (nMP > 0 && !m_pPropertyModule->ConsumeMP(self, nMP)) { return false; } if (nSP > 0 && !m_pPropertyModule->ConsumeSP(self, nSP)) { return false; } return true; } void NFItemModule::OnClientUseItem(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen) { CLIENT_MSG_PROCESS( nMsgID, msg, nLen, NFMsg::ReqAckUseItem); const NFGUID& self = NFINetModule::PBToNF(xMsg.user()); const std::string& strItemID = xMsg.item().item_id(); const NFGUID xTargetID = NFINetModule::PBToNF(xMsg.targetid()); const NFVector3 vector = NFINetModule::PBToNF(xMsg.position()); //const int nCount = xMsg.item().item_count(); UseItem(nPlayerID, strItemID, xTargetID, vector); } void NFItemModule::OnClientPickItem(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen) { CLIENT_MSG_PROCESS( nMsgID, msg, nLen, NFMsg::ReqPickDropItem); NF_SHARE_PTR<NFIRecord> xDropItemList = m_pKernelModule->FindRecord(nPlayerID, NFrame::Player::DropItemList::ThisName()); if (xDropItemList) { const NFGUID& xItemID = NFINetModule::PBToNF(xMsg.item_guid()); const int nRow = xDropItemList->FindObject(NFrame::Player::DropItemList::GUID, xItemID); if (nRow >= 0) { const std::string& strItemID = xDropItemList->GetString(nRow, NFrame::Player::DropItemList::ConfigID); const int nCount = xDropItemList->GetInt(nRow, NFrame::Player::DropItemList::ItemCount); xDropItemList->Remove(nRow); m_pPackModule->CreateItem(nPlayerID, strItemID, nCount); } } }
/* * Copyright (C) 2015 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 "GLUtils.h" #include <utils/trap.h> #include "private/backend/Driver.h" namespace filament { using namespace backend; using namespace utils; namespace GLUtils { GLenum glGetErrorPassthrough() { return glGetError(); } void checkGLError(io::ostream& out, const char* function, size_t line) noexcept { GLenum err = glGetError(); const char* error = "unknown"; switch (err) { case GL_NO_ERROR: return; case GL_INVALID_ENUM: error = "GL_INVALID_ENUM"; break; case GL_INVALID_VALUE: error = "GL_INVALID_VALUE"; break; case GL_INVALID_OPERATION: error = "GL_INVALID_OPERATION"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: error = "GL_INVALID_FRAMEBUFFER_OPERATION"; break; case GL_OUT_OF_MEMORY: error = "GL_OUT_OF_MEMORY"; break; default: break; } out << "OpenGL error " << io::hex << err << " (" << error << ") in \"" << function << "\" at line " << io::dec << line << io::endl; debug_trap(); } void checkFramebufferStatus(io::ostream& out, const char* function, size_t line) noexcept { GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); const char* error = "unknown"; switch (status) { case GL_FRAMEBUFFER_COMPLETE: // success! return; case GL_FRAMEBUFFER_UNDEFINED: error = "GL_FRAMEBUFFER_UNDEFINED"; break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: error = "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"; break; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: error = "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"; break; case GL_FRAMEBUFFER_UNSUPPORTED: error = "GL_FRAMEBUFFER_UNSUPPORTED"; break; case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: error = "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"; break; default: break; } out << "OpenGL framebuffer error " << io::hex << status << " (" << error << ") in \"" << function << "\" at line " << io::dec << line << io::endl; debug_trap(); } } // namespace GLUtils } // namespace filament
/*! * @section LICENSE * * @copyright * Copyright (c) 2015-2017 Intel Corporation * * @copyright * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * 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. * * @section DESCRIPTION * */ #include "agent-framework/module/constants/network.hpp" #include "agent-framework/module/network_components.hpp" #include "agent-framework/command-ref/network_commands.hpp" #include "gtest/gtest.h" #include "gmock/gmock.h" using namespace agent_framework::model; using namespace agent_framework::command_ref; static constexpr char TEST_UUID[] = "8d2c1ac0-2f82-11e5-8333-0002a5d5c51b"; class MyDeletePortVlan { private: std::string m_port_vlan{}; public: MyDeletePortVlan( std::string port_vlan) { m_port_vlan = port_vlan; } void execute(const DeletePortVlan::Request& request, DeletePortVlan::Response& response) { auto port_vlan = request.get_port_vlan(); if (port_vlan != m_port_vlan) { throw std::runtime_error("Not Found"); } response.set_oem(attribute::Oem()); } virtual ~MyDeletePortVlan(); }; MyDeletePortVlan::~MyDeletePortVlan() { } TEST(DeletePortVlanTest, PositiveExecute) { MyDeletePortVlan command{TEST_UUID}; DeletePortVlan::Request request{""}; DeletePortVlan::Response response{}; Json::Value params; Json::Value result; params[literals::EthernetSwitchPortVlan::PORT_VLAN] = TEST_UUID; EXPECT_NO_THROW(request = DeletePortVlan::Request::from_json(params)); EXPECT_NO_THROW(command.execute(request, response)); EXPECT_NO_THROW(result = response.to_json()); ASSERT_TRUE(result.isObject()); ASSERT_TRUE(result[literals::EthernetSwitchPortVlan::OEM].isObject()); } TEST(DeletePortVlanTest, NegativeVlanPortNotFound) { MyDeletePortVlan command{TEST_UUID}; DeletePortVlan::Request request{""}; DeletePortVlan::Response response{}; Json::Value params; Json::Value result; params[literals::EthernetSwitchPortVlan::PORT_VLAN] = "8d2c1ac0-2f82-11e5-8333-0002a5d5c51c"; EXPECT_NO_THROW(request = DeletePortVlan::Request::from_json(params)); EXPECT_ANY_THROW(command.execute(request, response)); EXPECT_NO_THROW(result = response.to_json()); } TEST(DeletePortVlanTest, NegativeInvalidUUIDFormat) { MyDeletePortVlan command{TEST_UUID}; DeletePortVlan::Request request{""}; DeletePortVlan::Response response{}; Json::Value params; Json::Value result; params[literals::EthernetSwitchPortVlan::PORT_VLAN] = "TestUUID"; EXPECT_NO_THROW(request = DeletePortVlan::Request::from_json(params)); EXPECT_ANY_THROW(command.execute(request, response)); EXPECT_NO_THROW(result = response.to_json()); }
// Copyright 2013 The Flutter 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 "flutter/shell/platform/android/surface/android_surface_mock.h" namespace flutter { std::unique_ptr<GLContextResult> AndroidSurfaceMock::GLContextMakeCurrent() { return std::make_unique<GLContextDefaultResult>(/*static_result=*/true); } bool AndroidSurfaceMock::GLContextClearCurrent() { return true; } bool AndroidSurfaceMock::GLContextPresent() { return true; } intptr_t AndroidSurfaceMock::GLContextFBO(GLFrameInfo frame_info) const { return 0; } ExternalViewEmbedder* AndroidSurfaceMock::GetExternalViewEmbedder() { return nullptr; } } // namespace flutter
/* ******************************************************************************* * Copyright (C) 2013-2015, International Business Machines * Corporation and others. All Rights Reserved. ******************************************************************************* * collationdatareader.cpp * * created on: 2013feb07 * created by: Markus W. Scherer */ #include "unicode/utypes.h" #if !UCONFIG_NO_COLLATION #include "unicode/ucol.h" #include "unicode/udata.h" #include "unicode/uscript.h" #include "cmemory.h" #include "collation.h" #include "collationdata.h" #include "collationdatareader.h" #include "collationfastlatin.h" #include "collationkeys.h" #include "collationrootelements.h" #include "collationsettings.h" #include "collationtailoring.h" #include "collunsafe.h" #include "normalizer2impl.h" #include "uassert.h" #include "ucmndata.h" #include "utrie2.h" U_NAMESPACE_BEGIN namespace { int32_t getIndex(const int32_t *indexes, int32_t length, int32_t i) { return (i < length) ? indexes[i] : -1; } } // namespace void CollationDataReader::read(const CollationTailoring *base, const uint8_t *inBytes, int32_t inLength, CollationTailoring &tailoring, UErrorCode &errorCode) { if(U_FAILURE(errorCode)) { return; } if(base != NULL) { if(inBytes == NULL || (0 <= inLength && inLength < 24)) { errorCode = U_ILLEGAL_ARGUMENT_ERROR; return; } const DataHeader *header = reinterpret_cast<const DataHeader *>(inBytes); if(!(header->dataHeader.magic1 == 0xda && header->dataHeader.magic2 == 0x27 && isAcceptable(tailoring.version, NULL, NULL, &header->info))) { errorCode = U_INVALID_FORMAT_ERROR; return; } if(base->getUCAVersion() != tailoring.getUCAVersion()) { errorCode = U_COLLATOR_VERSION_MISMATCH; return; } int32_t headerLength = header->dataHeader.headerSize; inBytes += headerLength; if(inLength >= 0) { inLength -= headerLength; } } if(inBytes == NULL || (0 <= inLength && inLength < 8)) { errorCode = U_ILLEGAL_ARGUMENT_ERROR; return; } const int32_t *inIndexes = reinterpret_cast<const int32_t *>(inBytes); int32_t indexesLength = inIndexes[IX_INDEXES_LENGTH]; if(indexesLength < 2 || (0 <= inLength && inLength < indexesLength * 4)) { errorCode = U_INVALID_FORMAT_ERROR; // Not enough indexes. return; } // Assume that the tailoring data is in initial state, // with NULL pointers and 0 lengths. // Set pointers to non-empty data parts. // Do this in order of their byte offsets. (Should help porting to Java.) int32_t index; // one of the indexes[] slots int32_t offset; // byte offset for the index part int32_t length; // number of bytes in the index part if(indexesLength > IX_TOTAL_SIZE) { length = inIndexes[IX_TOTAL_SIZE]; } else if(indexesLength > IX_REORDER_CODES_OFFSET) { length = inIndexes[indexesLength - 1]; } else { length = 0; // only indexes, and inLength was already checked for them } if(0 <= inLength && inLength < length) { errorCode = U_INVALID_FORMAT_ERROR; return; } const CollationData *baseData = base == NULL ? NULL : base->data; const int32_t *reorderCodes = NULL; int32_t reorderCodesLength = 0; const uint32_t *reorderRanges = NULL; int32_t reorderRangesLength = 0; index = IX_REORDER_CODES_OFFSET; offset = getIndex(inIndexes, indexesLength, index); length = getIndex(inIndexes, indexesLength, index + 1) - offset; if(length >= 4) { if(baseData == NULL) { // We assume for collation settings that // the base data does not have a reordering. errorCode = U_INVALID_FORMAT_ERROR; return; } reorderCodes = reinterpret_cast<const int32_t *>(inBytes + offset); reorderCodesLength = length / 4; // The reorderRanges (if any) are the trailing reorderCodes entries. // Split the array at the boundary. // Script or reorder codes do not exceed 16-bit values. // Range limits are stored in the upper 16 bits, and are never 0. while(reorderRangesLength < reorderCodesLength && (reorderCodes[reorderCodesLength - reorderRangesLength - 1] & 0xffff0000) != 0) { ++reorderRangesLength; } U_ASSERT(reorderRangesLength < reorderCodesLength); if(reorderRangesLength != 0) { reorderCodesLength -= reorderRangesLength; reorderRanges = reinterpret_cast<const uint32_t *>(reorderCodes + reorderCodesLength); } } // There should be a reorder table only if there are reorder codes. // However, when there are reorder codes the reorder table may be omitted to reduce // the data size. const uint8_t *reorderTable = NULL; index = IX_REORDER_TABLE_OFFSET; offset = getIndex(inIndexes, indexesLength, index); length = getIndex(inIndexes, indexesLength, index + 1) - offset; if(length >= 256) { if(reorderCodesLength == 0) { errorCode = U_INVALID_FORMAT_ERROR; // Reordering table without reordering codes. return; } reorderTable = inBytes + offset; } else { // If we have reorder codes, then build the reorderTable at the end, // when the CollationData is otherwise complete. } if(baseData != NULL && baseData->numericPrimary != (inIndexes[IX_OPTIONS] & 0xff000000)) { errorCode = U_INVALID_FORMAT_ERROR; return; } CollationData *data = NULL; // Remains NULL if there are no mappings. index = IX_TRIE_OFFSET; offset = getIndex(inIndexes, indexesLength, index); length = getIndex(inIndexes, indexesLength, index + 1) - offset; if(length >= 8) { if(!tailoring.ensureOwnedData(errorCode)) { return; } data = tailoring.ownedData; data->base = baseData; data->numericPrimary = inIndexes[IX_OPTIONS] & 0xff000000; data->trie = tailoring.trie = utrie2_openFromSerialized( UTRIE2_32_VALUE_BITS, inBytes + offset, length, NULL, &errorCode); if(U_FAILURE(errorCode)) { return; } } else if(baseData != NULL) { // Use the base data. Only the settings are tailored. tailoring.data = baseData; } else { errorCode = U_INVALID_FORMAT_ERROR; // No mappings. return; } index = IX_CES_OFFSET; offset = getIndex(inIndexes, indexesLength, index); length = getIndex(inIndexes, indexesLength, index + 1) - offset; if(length >= 8) { if(data == NULL) { errorCode = U_INVALID_FORMAT_ERROR; // Tailored ces without tailored trie. return; } data->ces = reinterpret_cast<const int64_t *>(inBytes + offset); data->cesLength = length / 8; } index = IX_CE32S_OFFSET; offset = getIndex(inIndexes, indexesLength, index); length = getIndex(inIndexes, indexesLength, index + 1) - offset; if(length >= 4) { if(data == NULL) { errorCode = U_INVALID_FORMAT_ERROR; // Tailored ce32s without tailored trie. return; } data->ce32s = reinterpret_cast<const uint32_t *>(inBytes + offset); data->ce32sLength = length / 4; } int32_t jamoCE32sStart = getIndex(inIndexes, indexesLength, IX_JAMO_CE32S_START); if(jamoCE32sStart >= 0) { if(data == NULL || data->ce32s == NULL) { errorCode = U_INVALID_FORMAT_ERROR; // Index into non-existent ce32s[]. return; } data->jamoCE32s = data->ce32s + jamoCE32sStart; } else if(data == NULL) { // Nothing to do. } else if(baseData != NULL) { data->jamoCE32s = baseData->jamoCE32s; } else { errorCode = U_INVALID_FORMAT_ERROR; // No Jamo CE32s for Hangul processing. return; } index = IX_ROOT_ELEMENTS_OFFSET; offset = getIndex(inIndexes, indexesLength, index); length = getIndex(inIndexes, indexesLength, index + 1) - offset; if(length >= 4) { length /= 4; if(data == NULL || length <= CollationRootElements::IX_SEC_TER_BOUNDARIES) { errorCode = U_INVALID_FORMAT_ERROR; return; } data->rootElements = reinterpret_cast<const uint32_t *>(inBytes + offset); data->rootElementsLength = length; uint32_t commonSecTer = data->rootElements[CollationRootElements::IX_COMMON_SEC_AND_TER_CE]; if(commonSecTer != Collation::COMMON_SEC_AND_TER_CE) { errorCode = U_INVALID_FORMAT_ERROR; return; } uint32_t secTerBoundaries = data->rootElements[CollationRootElements::IX_SEC_TER_BOUNDARIES]; if((secTerBoundaries >> 24) < CollationKeys::SEC_COMMON_HIGH) { // [fixed last secondary common byte] is too low, // and secondary weights would collide with compressed common secondaries. errorCode = U_INVALID_FORMAT_ERROR; return; } } index = IX_CONTEXTS_OFFSET; offset = getIndex(inIndexes, indexesLength, index); length = getIndex(inIndexes, indexesLength, index + 1) - offset; if(length >= 2) { if(data == NULL) { errorCode = U_INVALID_FORMAT_ERROR; // Tailored contexts without tailored trie. return; } data->contexts = reinterpret_cast<const UChar *>(inBytes + offset); data->contextsLength = length / 2; } index = IX_UNSAFE_BWD_OFFSET; offset = getIndex(inIndexes, indexesLength, index); length = getIndex(inIndexes, indexesLength, index + 1) - offset; if(length >= 2) { if(data == NULL) { errorCode = U_INVALID_FORMAT_ERROR; return; } if(baseData == NULL) { #if defined(COLLUNSAFE_COLL_VERSION) && defined (COLLUNSAFE_SERIALIZE) tailoring.unsafeBackwardSet = new UnicodeSet(unsafe_serializedData, unsafe_serializedCount, UnicodeSet::kSerialized, errorCode); if(tailoring.unsafeBackwardSet == NULL) { errorCode = U_MEMORY_ALLOCATION_ERROR; return; } else if (U_FAILURE(errorCode)) { return; } #else // Create the unsafe-backward set for the root collator. // Include all non-zero combining marks and trail surrogates. // We do this at load time, rather than at build time, // to simplify Unicode version bootstrapping: // The root data builder only needs the new FractionalUCA.txt data, // but it need not be built with a version of ICU already updated to // the corresponding new Unicode Character Database. // // The following is an optimized version of // new UnicodeSet("[[:^lccc=0:][\\udc00-\\udfff]]"). // It is faster and requires fewer code dependencies. tailoring.unsafeBackwardSet = new UnicodeSet(0xdc00, 0xdfff); // trail surrogates if(tailoring.unsafeBackwardSet == NULL) { errorCode = U_MEMORY_ALLOCATION_ERROR; return; } data->nfcImpl.addLcccChars(*tailoring.unsafeBackwardSet); #endif // !COLLUNSAFE_SERIALIZE || !COLLUNSAFE_COLL_VERSION } else { // Clone the root collator's set contents. tailoring.unsafeBackwardSet = static_cast<UnicodeSet *>( baseData->unsafeBackwardSet->cloneAsThawed()); if(tailoring.unsafeBackwardSet == NULL) { errorCode = U_MEMORY_ALLOCATION_ERROR; return; } } // Add the ranges from the data file to the unsafe-backward set. USerializedSet sset; const uint16_t *unsafeData = reinterpret_cast<const uint16_t *>(inBytes + offset); if(!uset_getSerializedSet(&sset, unsafeData, length / 2)) { errorCode = U_INVALID_FORMAT_ERROR; return; } int32_t count = uset_getSerializedRangeCount(&sset); for(int32_t i = 0; i < count; ++i) { UChar32 start, end; uset_getSerializedRange(&sset, i, &start, &end); tailoring.unsafeBackwardSet->add(start, end); } // Mark each lead surrogate as "unsafe" // if any of its 1024 associated supplementary code points is "unsafe". UChar32 c = 0x10000; for(UChar lead = 0xd800; lead < 0xdc00; ++lead, c += 0x400) { if(!tailoring.unsafeBackwardSet->containsNone(c, c + 0x3ff)) { tailoring.unsafeBackwardSet->add(lead); } } tailoring.unsafeBackwardSet->freeze(); data->unsafeBackwardSet = tailoring.unsafeBackwardSet; } else if(data == NULL) { // Nothing to do. } else if(baseData != NULL) { // No tailoring-specific data: Alias the root collator's set. data->unsafeBackwardSet = baseData->unsafeBackwardSet; } else { errorCode = U_INVALID_FORMAT_ERROR; // No unsafeBackwardSet. return; } // If the fast Latin format version is different, // or the version is set to 0 for "no fast Latin table", // then just always use the normal string comparison path. if(data != NULL) { data->fastLatinTable = NULL; data->fastLatinTableLength = 0; if(((inIndexes[IX_OPTIONS] >> 16) & 0xff) == CollationFastLatin::VERSION) { index = IX_FAST_LATIN_TABLE_OFFSET; offset = getIndex(inIndexes, indexesLength, index); length = getIndex(inIndexes, indexesLength, index + 1) - offset; if(length >= 2) { data->fastLatinTable = reinterpret_cast<const uint16_t *>(inBytes + offset); data->fastLatinTableLength = length / 2; if((*data->fastLatinTable >> 8) != CollationFastLatin::VERSION) { errorCode = U_INVALID_FORMAT_ERROR; // header vs. table version mismatch return; } } else if(baseData != NULL) { data->fastLatinTable = baseData->fastLatinTable; data->fastLatinTableLength = baseData->fastLatinTableLength; } } } index = IX_SCRIPTS_OFFSET; offset = getIndex(inIndexes, indexesLength, index); length = getIndex(inIndexes, indexesLength, index + 1) - offset; if(length >= 2) { if(data == NULL) { errorCode = U_INVALID_FORMAT_ERROR; return; } const uint16_t *scripts = reinterpret_cast<const uint16_t *>(inBytes + offset); int32_t scriptsLength = length / 2; data->numScripts = scripts[0]; // There must be enough entries for both arrays, including more than two range starts. data->scriptStartsLength = scriptsLength - (1 + data->numScripts + 16); if(data->scriptStartsLength <= 2 || CollationData::MAX_NUM_SCRIPT_RANGES < data->scriptStartsLength) { errorCode = U_INVALID_FORMAT_ERROR; return; } data->scriptsIndex = scripts + 1; data->scriptStarts = scripts + 1 + data->numScripts + 16; if(!(data->scriptStarts[0] == 0 && data->scriptStarts[1] == ((Collation::MERGE_SEPARATOR_BYTE + 1) << 8) && data->scriptStarts[data->scriptStartsLength - 1] == (Collation::TRAIL_WEIGHT_BYTE << 8))) { errorCode = U_INVALID_FORMAT_ERROR; return; } } else if(data == NULL) { // Nothing to do. } else if(baseData != NULL) { data->numScripts = baseData->numScripts; data->scriptsIndex = baseData->scriptsIndex; data->scriptStarts = baseData->scriptStarts; data->scriptStartsLength = baseData->scriptStartsLength; } index = IX_COMPRESSIBLE_BYTES_OFFSET; offset = getIndex(inIndexes, indexesLength, index); length = getIndex(inIndexes, indexesLength, index + 1) - offset; if(length >= 256) { if(data == NULL) { errorCode = U_INVALID_FORMAT_ERROR; return; } data->compressibleBytes = reinterpret_cast<const UBool *>(inBytes + offset); } else if(data == NULL) { // Nothing to do. } else if(baseData != NULL) { data->compressibleBytes = baseData->compressibleBytes; } else { errorCode = U_INVALID_FORMAT_ERROR; // No compressibleBytes[]. return; } const CollationSettings &ts = *tailoring.settings; int32_t options = inIndexes[IX_OPTIONS] & 0xffff; uint16_t fastLatinPrimaries[CollationFastLatin::LATIN_LIMIT]; int32_t fastLatinOptions = CollationFastLatin::getOptions( tailoring.data, ts, fastLatinPrimaries, UPRV_LENGTHOF(fastLatinPrimaries)); if(options == ts.options && ts.variableTop != 0 && reorderCodesLength == ts.reorderCodesLength && uprv_memcmp(reorderCodes, ts.reorderCodes, reorderCodesLength * 4) == 0 && fastLatinOptions == ts.fastLatinOptions && (fastLatinOptions < 0 || uprv_memcmp(fastLatinPrimaries, ts.fastLatinPrimaries, sizeof(fastLatinPrimaries)) == 0)) { return; } CollationSettings *settings = SharedObject::copyOnWrite(tailoring.settings); if(settings == NULL) { errorCode = U_MEMORY_ALLOCATION_ERROR; return; } settings->options = options; // Set variableTop from options and scripts data. settings->variableTop = tailoring.data->getLastPrimaryForGroup( UCOL_REORDER_CODE_FIRST + settings->getMaxVariable()); if(settings->variableTop == 0) { errorCode = U_INVALID_FORMAT_ERROR; return; } if(reorderCodesLength != 0) { settings->aliasReordering(*baseData, reorderCodes, reorderCodesLength, reorderRanges, reorderRangesLength, reorderTable, errorCode); } settings->fastLatinOptions = CollationFastLatin::getOptions( tailoring.data, *settings, settings->fastLatinPrimaries, UPRV_LENGTHOF(settings->fastLatinPrimaries)); } UBool U_CALLCONV CollationDataReader::isAcceptable(void *context, const char * /* type */, const char * /*name*/, const UDataInfo *pInfo) { if( pInfo->size >= 20 && pInfo->isBigEndian == U_IS_BIG_ENDIAN && pInfo->charsetFamily == U_CHARSET_FAMILY && pInfo->dataFormat[0] == 0x55 && // dataFormat="UCol" pInfo->dataFormat[1] == 0x43 && pInfo->dataFormat[2] == 0x6f && pInfo->dataFormat[3] == 0x6c && pInfo->formatVersion[0] == 5 ) { UVersionInfo *version = static_cast<UVersionInfo *>(context); if(version != NULL) { uprv_memcpy(version, pInfo->dataVersion, 4); } return TRUE; } else { return FALSE; } } U_NAMESPACE_END #endif // !UCONFIG_NO_COLLATION
#if defined(LOCAL) const double _max_double_error = 1e-9; #include "testutils.h" #define L(x...) (debug(x, #x)) #define I(x, ...) (x) #define C(x...) CHECK(x) #else #define L(x, ...) (x) #define I(x, ...) (x) #define C(x, ...) ; #endif #include <math.h> #include <algorithm> #include <bitset> #include <chrono> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <memory> #include <numeric> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; using vi = vector<int>; using vvi = vector<vi>; using vvvi = vector<vvi>; using ii = pair<int, int>; using lu = unsigned long long; using l = long long; using vs = vector<string>; using vii = vector<ii>; using vl = vector<l>; using vvl = vector<vl>; using vvvl = vector<vvl>; using vlu = vector<lu>; using ll = pair<l, l>; using vll = vector<ll>; using vvll = vector<vll>; using vb = vector<bool>; using vvb = vector<vb>; using vvvb = vector<vvb>; using vd = vector<double>; using vvd = vector<vd>; using mll = unordered_map<l, l>; using sl = unordered_set<l>; const l INF = numeric_limits<l>::max(); const double EPS = 1e-10; const double PI = 3.14159265358979323846; const l e0 = 1, e3 = 1000, e5 = 100000, e6 = 10 * e5, e7 = 10 * e6, e8 = 10 * e7, e9 = 10 * e8, l0 = 0, l1 = 1, l2 = 2; const char lf = '\n'; #define all(x) begin(x), end(x) #define F(a, b, c) for (l a = l(b); a < l(c); a++) #define B(a, b, c) for (l a = l(c) - 1; a >= l(b); a--) void solve(istream &in, ostream &out); void solve_brute(istream &, ostream &); bool interactive_judge(istream &, istream &, ostream &); bool generate_random(l, ostream &); bool solution_checker(istream &, istream &, istream &, ostream &); int main(int argc, char **argv) { ios_base::sync_with_stdio(false); cin.tie(0); cout << fixed << setprecision(15); #if defined(LOCAL) tst::test_init(argc, argv); // _generate_random_test = generate_random; // _solve_brute = solve_brute; // _judge = interactive_judge; // _custom_solution_checker = solution_checker; tst::maybe_run_tests(cin, cout); #else solve(cin, cout); #endif } const l MOD = e9 + 7; // end of template const l MAX_PRIME = 50000; // returns v[i] = smallest prime divisor of i or 1 vl sieve_primes(vl &primes) { vl next_div(MAX_PRIME, 1); for (l i = 2; i < MAX_PRIME; i++) { if (next_div[i] != 1) continue; primes.emplace_back(i); for (l j = i; j < MAX_PRIME; j += i) if (next_div[j] == 1) next_div[j] = i; } return next_div; } bool is_prime(l n, vl const &primes) { auto p = primes.begin(); while (p != primes.end() and ((*p) * (*p)) <= n) { if (n % *p == 0) return n == *p; p++; } return true; } // in asc order vl factorize_to_primes(l n, vl &primes, vl &next_div) { auto p = primes.begin(); vl result; while (n >= MAX_PRIME and p != primes.end()) { while (n % *p == 0) { result.emplace_back(*p); n /= *p; } p++; } if (n >= MAX_PRIME) { result.emplace_back(n); n = 1; } while (n != 1) { result.emplace_back(next_div[n]); n /= next_div[n]; } return result; } void solve(istream &in, ostream &out) { l n, m; in >> n >> m; sl s; vll v(m); auto enc = [&](l a, l b) { a = (a - 1) % n; b = (b - 1) % n; if (a > b) swap(a, b); return a + b * n; }; F(i, 0, m) { in >> v[i].first >> v[i].second; s.emplace(enc(v[i].first, v[i].second)); } F(i, 1, n) { if (n % i) continue; bool ok = true; F(j, 0, m) { l x = enc(v[j].first + i, v[j].second + i); if (s.count(x) == 0) { ok = false; break; } } if (ok) { out << "Yes" << lf; return; } } out << "No" << lf; }
/** * Copyright (C) 2015 MongoDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #include "mongo/platform/basic.h" #include "mongo/base/status.h" #include "mongo/client/dbclientinterface.h" #include "mongo/db/commands.h" namespace mongo { namespace { class AvailableQueryOptions : public BasicCommand { public: AvailableQueryOptions() : BasicCommand("availableQueryOptions", "availablequeryoptions") {} AllowedOnSecondary secondaryAllowed() const override { return AllowedOnSecondary::kAlways; } bool supportsWriteConcern(const BSONObj& cmd) const override { return false; } Status checkAuthForCommand(Client* client, const std::string& dbname, const BSONObj& cmdObj) const override { return Status::OK(); } bool run(OperationContext* opCtx, const std::string& dbname, const BSONObj& cmdObj, BSONObjBuilder& result) override { result << "options" << QueryOption_AllSupportedForSharding; return true; } } clusterAvailableQueryOptionsCmd; } // namespace } // namespace mongo
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/bigtable/admin/bigtable_instance_admin_client.h" #include "google/cloud/bigtable/iam_binding.h" #include "google/cloud/bigtable/iam_policy.h" #include "google/cloud/bigtable/resource_names.h" #include "google/cloud/common_options.h" #include "google/cloud/grpc_options.h" #include "google/cloud/internal/algorithm.h" #include "google/cloud/internal/background_threads_impl.h" #include "google/cloud/internal/getenv.h" #include "google/cloud/internal/random.h" #include "google/cloud/project.h" #include "google/cloud/status_or.h" #include "google/cloud/testing_util/contains_once.h" #include "google/cloud/testing_util/integration_test.h" #include "google/cloud/testing_util/scoped_environment.h" #include "google/cloud/testing_util/scoped_log.h" #include "google/cloud/testing_util/status_matchers.h" #include "absl/memory/memory.h" #include <google/protobuf/text_format.h> #include <gmock/gmock.h> // TODO(#5929) - remove once deprecated functions are removed #include "google/cloud/internal/disable_deprecation_warnings.inc" namespace google { namespace cloud { namespace bigtable_admin { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN namespace { using ::google::cloud::internal::GetEnv; using ::google::cloud::testing_util::ContainsOnce; using ::google::cloud::testing_util::IsOk; using ::testing::Contains; using ::testing::HasSubstr; using ::testing::IsEmpty; using ::testing::Not; namespace btadmin = ::google::bigtable::admin::v2; class InstanceAdminIntegrationTest : public ::google::cloud::testing_util::IntegrationTest { protected: void SetUp() override { auto emulator_present = GetEnv("BIGTABLE_INSTANCE_ADMIN_EMULATOR_HOST").has_value(); auto run_prod_tests = GetEnv("ENABLE_BIGTABLE_ADMIN_INTEGRATION_TESTS").value_or("") == "yes"; if (!emulator_present && !run_prod_tests) { GTEST_SKIP(); } project_id_ = GetEnv("GOOGLE_CLOUD_PROJECT").value_or(""); ASSERT_FALSE(project_id_.empty()); zone_a_ = GetEnv("GOOGLE_CLOUD_CPP_BIGTABLE_TEST_ZONE_A").value_or(""); ASSERT_FALSE(zone_a_.empty()); zone_b_ = GetEnv("GOOGLE_CLOUD_CPP_BIGTABLE_TEST_ZONE_B").value_or(""); ASSERT_FALSE(zone_b_.empty()); service_account_ = GetEnv("GOOGLE_CLOUD_CPP_BIGTABLE_TEST_SERVICE_ACCOUNT").value_or(""); ASSERT_FALSE(service_account_.empty()); } StatusOr<std::vector<std::string>> ListInstances( BigtableInstanceAdminClient& client) { auto const project_name = Project(project_id_).FullName(); auto sor = client.ListInstances(project_name); if (!sor) return std::move(sor).status(); auto resp = std::move(sor).value(); std::vector<std::string> names; names.reserve(resp.instances_size()); auto& instances = *resp.mutable_instances(); EXPECT_EQ(0, resp.failed_locations_size()); std::transform(instances.begin(), instances.end(), std::back_inserter(names), [](btadmin::Instance const& i) { return i.name(); }); return names; } StatusOr<std::vector<std::string>> ListClusters( std::string const& instance_id) { auto const instance_name = bigtable::InstanceName(project_id_, instance_id); auto sor = client_.ListClusters(instance_name); if (!sor) return std::move(sor).status(); auto resp = std::move(sor).value(); std::vector<std::string> names; names.reserve(resp.clusters_size()); auto& clusters = *resp.mutable_clusters(); std::transform(clusters.begin(), clusters.end(), std::back_inserter(names), [](btadmin::Cluster const& c) { return c.name(); }); return names; } std::string project_id_; std::string zone_a_; std::string zone_b_; std::string service_account_; BigtableInstanceAdminClient client_ = BigtableInstanceAdminClient(MakeBigtableInstanceAdminConnection()); google::cloud::internal::DefaultPRNG generator_ = google::cloud::internal::MakeDefaultPRNG(); }; btadmin::CreateInstanceRequest IntegrationTestConfig( std::string const& project, std::string const& instance_id, std::string const& location, btadmin::Instance::Type type = btadmin::Instance::DEVELOPMENT, int32_t serve_nodes = 0) { // The description cannot exceed 30 characters auto const display_name = ("IT " + instance_id).substr(0, 30); auto const project_name = Project(project).FullName(); btadmin::Cluster c; c.set_location(project_name + "/locations/" + location); c.set_serve_nodes(serve_nodes); c.set_default_storage_type(btadmin::StorageType::HDD); btadmin::CreateInstanceRequest r; r.set_parent(std::move(project_name)); r.set_instance_id(instance_id); r.mutable_instance()->set_type(type); r.mutable_instance()->set_display_name(std::move(display_name)); (*r.mutable_clusters())[instance_id + "-c1"] = std::move(c); return r; } protobuf::FieldMask Mask(std::string const& path) { protobuf::FieldMask mask; mask.add_paths(path); return mask; } /// @test Verify that default InstanceAdmin::ListClusters works as expected. TEST_F(InstanceAdminIntegrationTest, ListAllClustersTest) { auto const id_1 = "it-" + google::cloud::internal::Sample( generator_, 8, "abcdefghijklmnopqrstuvwxyz0123456789"); auto const id_2 = "it-" + google::cloud::internal::Sample( generator_, 8, "abcdefghijklmnopqrstuvwxyz0123456789"); auto const project_name = Project(project_id_).FullName(); auto const name_1 = bigtable::InstanceName(project_id_, id_1); auto const name_2 = bigtable::InstanceName(project_id_, id_2); auto config_1 = IntegrationTestConfig(project_id_, id_1, zone_a_, btadmin::Instance::PRODUCTION, 3); auto config_2 = IntegrationTestConfig(project_id_, id_2, zone_b_, btadmin::Instance::PRODUCTION, 3); auto instance_1_fut = client_.CreateInstance(config_1); auto instance_2_fut = client_.CreateInstance(config_2); // Wait for instance creation auto instance_1 = instance_1_fut.get(); auto instance_2 = instance_2_fut.get(); EXPECT_STATUS_OK(instance_1); EXPECT_STATUS_OK(instance_2); EXPECT_EQ(instance_1->name(), name_1); EXPECT_EQ(instance_2->name(), name_2); auto clusters = ListClusters("-"); ASSERT_STATUS_OK(clusters); for (auto const& cluster : *clusters) { EXPECT_THAT(cluster, HasSubstr(project_name)); } EXPECT_THAT(*clusters, Not(IsEmpty())); EXPECT_STATUS_OK(client_.DeleteInstance(name_1)); EXPECT_STATUS_OK(client_.DeleteInstance(name_2)); } /// @test Verify that AppProfile CRUD operations work as expected. TEST_F(InstanceAdminIntegrationTest, CreateListGetDeleteAppProfile) { auto const instance_id = "it-" + google::cloud::internal::Sample( generator_, 8, "abcdefghijklmnopqrstuvwxyz0123456789"); auto const instance_name = bigtable::InstanceName(project_id_, instance_id); auto config = IntegrationTestConfig(project_id_, instance_id, zone_a_, btadmin::Instance::PRODUCTION, 3); auto instance_fut = client_.CreateInstance(config); // Wait for instance creation auto instance = instance_fut.get(); ASSERT_STATUS_OK(instance); ASSERT_EQ(instance->name(), instance_name); auto const id_1 = "profile-" + google::cloud::internal::Sample( generator_, 8, "abcdefghijklmnopqrstuvwxyz0123456789"); auto const id_2 = "profile-" + google::cloud::internal::Sample( generator_, 8, "abcdefghijklmnopqrstuvwxyz0123456789"); auto const name_1 = bigtable::AppProfileName(project_id_, instance_id, id_1); auto const name_2 = bigtable::AppProfileName(project_id_, instance_id, id_2); // Simplify writing the rest of the test. auto profile_names = [](StreamRange<btadmin::AppProfile> list) -> StatusOr<std::vector<std::string>> { std::vector<std::string> names; for (auto const& profile : list) { if (!profile) return profile.status(); names.push_back(profile->name()); } return names; }; auto profiles = profile_names(client_.ListAppProfiles(instance_name)); ASSERT_STATUS_OK(profiles); EXPECT_THAT(*profiles, Not(Contains(name_1))); EXPECT_THAT(*profiles, Not(Contains(name_2))); auto profile_1 = client_.CreateAppProfile(instance_name, id_1, {}); ASSERT_STATUS_OK(profile_1); EXPECT_EQ(profile_1->name(), name_1); auto profile_2 = client_.CreateAppProfile(instance_name, id_2, {}); ASSERT_STATUS_OK(profile_2); EXPECT_EQ(profile_2->name(), name_2); profiles = profile_names(client_.ListAppProfiles(instance_name)); ASSERT_STATUS_OK(profiles); EXPECT_THAT(*profiles, ContainsOnce(name_1)); EXPECT_THAT(*profiles, ContainsOnce(name_2)); profile_1 = client_.GetAppProfile(name_1); ASSERT_STATUS_OK(profile_1); EXPECT_EQ(profile_1->name(), name_1); profile_2 = client_.GetAppProfile(name_2); ASSERT_STATUS_OK(profile_2); EXPECT_EQ(profile_2->name(), name_2); profile_2->set_description("new description"); profile_2 = client_.UpdateAppProfile(*std::move(profile_2), Mask("description")) .get(); ASSERT_STATUS_OK(profile_2); EXPECT_EQ("new description", profile_2->description()); profile_2 = client_.GetAppProfile(name_2); ASSERT_STATUS_OK(profile_2); EXPECT_EQ("new description", profile_2->description()); btadmin::DeleteAppProfileRequest req_1; req_1.set_ignore_warnings(true); req_1.set_name(name_1); ASSERT_STATUS_OK(client_.DeleteAppProfile(std::move(req_1))); profiles = profile_names(client_.ListAppProfiles(instance_name)); ASSERT_STATUS_OK(profiles); EXPECT_THAT(*profiles, Not(Contains(name_1))); EXPECT_THAT(*profiles, ContainsOnce(name_2)); btadmin::DeleteAppProfileRequest req_2; req_2.set_ignore_warnings(true); req_2.set_name(name_2); ASSERT_STATUS_OK(client_.DeleteAppProfile(std::move(req_2))); profiles = profile_names(client_.ListAppProfiles(instance_name)); ASSERT_STATUS_OK(profiles); EXPECT_THAT(*profiles, Not(Contains(name_1))); EXPECT_THAT(*profiles, Not(Contains(name_2))); ASSERT_STATUS_OK(client_.DeleteInstance(std::move(instance_name))); } /// @test Verify that Instance CRUD operations work as expected. TEST_F(InstanceAdminIntegrationTest, CreateListGetDeleteInstanceTest) { auto const instance_id = "it-" + google::cloud::internal::Sample( generator_, 8, "abcdefghijklmnopqrstuvwxyz0123456789"); auto const instance_name = bigtable::InstanceName(project_id_, instance_id); // Create instance auto config = IntegrationTestConfig(project_id_, instance_id, zone_a_); auto instance = client_.CreateInstance(config).get(); ASSERT_STATUS_OK(instance); // List instances auto instances = ListInstances(client_); ASSERT_STATUS_OK(instances); EXPECT_THAT(*instances, Contains(instance_name)); // Get instance instance = client_.GetInstance(instance_name); ASSERT_STATUS_OK(instance); EXPECT_EQ(instance->name(), instance_name); // Update instance auto const updated_display_name = instance_id + " updated"; instance->set_display_name(updated_display_name); instance = client_.PartialUpdateInstance(*std::move(instance), Mask("display_name")) .get(); ASSERT_STATUS_OK(instance); // Verify update instance = client_.GetInstance(instance_name); ASSERT_STATUS_OK(instance); EXPECT_EQ(updated_display_name, instance->display_name()); // Delete instance ASSERT_STATUS_OK(client_.DeleteInstance(instance_name)); // Verify delete instances = ListInstances(client_); ASSERT_STATUS_OK(instances); EXPECT_THAT(*instances, Not(Contains(instance_name))); } /// @test Verify that cluster CRUD operations work as expected. TEST_F(InstanceAdminIntegrationTest, CreateListGetDeleteClusterTest) { auto const instance_id = "it-" + google::cloud::internal::Sample( generator_, 8, "abcdefghijklmnopqrstuvwxyz0123456789"); auto const cluster_id = instance_id + "-cl2"; auto const project_name = Project(project_id_).FullName(); auto const instance_name = bigtable::InstanceName(project_id_, instance_id); auto const cluster_name = bigtable::ClusterName(project_id_, instance_id, cluster_id); // Create instance prerequisites for cluster operations auto config = IntegrationTestConfig(project_id_, instance_id, zone_a_, btadmin::Instance::PRODUCTION, 3); auto instance = client_.CreateInstance(config).get(); ASSERT_STATUS_OK(instance); // Create cluster btadmin::Cluster c; c.set_location(project_name + "/locations/" + zone_b_); c.set_serve_nodes(3); c.set_default_storage_type(btadmin::StorageType::HDD); auto cluster = client_.CreateCluster(instance_name, cluster_id, c).get(); ASSERT_STATUS_OK(cluster); EXPECT_EQ(3, cluster->serve_nodes()); // Verify create auto clusters = ListClusters(instance_id); ASSERT_STATUS_OK(clusters); EXPECT_THAT(*clusters, Contains(cluster_name)); // Get cluster cluster = client_.GetCluster(cluster_name); ASSERT_STATUS_OK(cluster); EXPECT_EQ(cluster_name, cluster->name()); // Update cluster cluster->set_serve_nodes(4); cluster->clear_state(); cluster = client_.UpdateCluster(*std::move(cluster)).get(); ASSERT_STATUS_OK(cluster); // Verify update cluster = client_.GetCluster(cluster_name); ASSERT_STATUS_OK(cluster); EXPECT_EQ(4, cluster->serve_nodes()); // Delete cluster ASSERT_STATUS_OK(client_.DeleteCluster(cluster_name)); // Verify delete clusters = ListClusters(instance_id); ASSERT_STATUS_OK(clusters); EXPECT_THAT(*clusters, Not(Contains(cluster_name))); // Delete instance ASSERT_STATUS_OK(client_.DeleteInstance(instance_name)); } /// @test Verify that IAM Policy APIs work as expected. TEST_F(InstanceAdminIntegrationTest, SetGetTestIamAPIsTest) { auto const instance_id = "it-" + google::cloud::internal::Sample( generator_, 8, "abcdefghijklmnopqrstuvwxyz0123456789"); auto const instance_name = bigtable::InstanceName(project_id_, instance_id); // Create instance auto config = IntegrationTestConfig(project_id_, instance_id, zone_a_); ASSERT_STATUS_OK(client_.CreateInstance(config).get()); auto iam_policy = bigtable::IamPolicy({bigtable::IamBinding( "roles/bigtable.reader", {"serviceAccount:" + service_account_})}); auto initial_policy = client_.SetIamPolicy(instance_id, iam_policy); ASSERT_STATUS_OK(initial_policy); auto fetched_policy = client_.GetIamPolicy(instance_id); ASSERT_STATUS_OK(fetched_policy); EXPECT_EQ(initial_policy->version(), fetched_policy->version()); EXPECT_EQ(initial_policy->etag(), fetched_policy->etag()); auto permission_set = client_.TestIamPermissions( instance_name, {"bigtable.tables.list", "bigtable.tables.delete"}); ASSERT_STATUS_OK(permission_set); EXPECT_EQ(2, permission_set->permissions_size()); EXPECT_STATUS_OK(client_.DeleteInstance(instance_name)); } /// @test Verify that Instance CRUD operations with logging work as expected. TEST_F(InstanceAdminIntegrationTest, CreateListGetDeleteInstanceTestWithLogging) { // In our ci builds, we set GOOGLE_CLOUD_CPP_ENABLE_TRACING to log our tests, // by default. We should unset this variable and create a fresh client in // order to have a conclusive test. testing_util::ScopedEnvironment env = {"GOOGLE_CLOUD_CPP_ENABLE_TRACING", absl::nullopt}; testing_util::ScopedLog log; auto const instance_id = "it-" + google::cloud::internal::Sample( generator_, 8, "abcdefghijklmnopqrstuvwxyz0123456789"); auto const project_name = Project(project_id_).FullName(); auto const instance_name = bigtable::InstanceName(project_id_, instance_id); auto client = BigtableInstanceAdminClient(MakeBigtableInstanceAdminConnection( Options{}.set<TracingComponentsOption>({"rpc"}))); // Create instance auto config = IntegrationTestConfig(project_id_, instance_id, zone_a_); auto instance = client.CreateInstance(config).get(); ASSERT_STATUS_OK(instance); // Verify create auto instances = ListInstances(client); ASSERT_STATUS_OK(instances); EXPECT_THAT(*instances, Contains(instance_name)); // Get instance instance = client.GetInstance(instance_name); ASSERT_STATUS_OK(instance); EXPECT_EQ(instance->name(), instance_name); // Update instance auto const updated_display_name = instance_id + " updated"; instance->set_display_name(updated_display_name); instance = client.PartialUpdateInstance(*instance, Mask("display_name")).get(); ASSERT_STATUS_OK(instance); // Verify update instance = client.GetInstance(instance_name); ASSERT_STATUS_OK(instance); EXPECT_EQ(updated_display_name, instance->display_name()); // Delete instance ASSERT_STATUS_OK(client.DeleteInstance(instance_name)); // Verify delete instances = ListInstances(client); ASSERT_STATUS_OK(instances); EXPECT_THAT(*instances, Not(Contains(instance_name))); auto const log_lines = log.ExtractLines(); EXPECT_THAT(log_lines, Contains(HasSubstr("AsyncCreateInstance"))); EXPECT_THAT(log_lines, Contains(HasSubstr("ListInstances"))); EXPECT_THAT(log_lines, Contains(HasSubstr("GetInstance"))); EXPECT_THAT(log_lines, Contains(HasSubstr("AsyncPartialUpdateInstance"))); EXPECT_THAT(log_lines, Contains(HasSubstr("DeleteInstance"))); // Verify that a normal client does not log. auto no_logging_client = BigtableInstanceAdminClient(MakeBigtableInstanceAdminConnection()); (void)no_logging_client.ListInstances(project_name); EXPECT_THAT(log.ExtractLines(), IsEmpty()); } TEST_F(InstanceAdminIntegrationTest, CustomWorkers) { CompletionQueue cq; auto client = BigtableInstanceAdminClient(MakeBigtableInstanceAdminConnection( Options{}.set<GrpcCompletionQueueOption>(cq))); // CompletionQueue `cq` is not being `Run()`, so this should never finish. auto const instance_id = "it-" + google::cloud::internal::Sample( generator_, 8, "abcdefghijklmnopqrstuvwxyz0123456789"); auto instance_fut = client.CreateInstance(IntegrationTestConfig( project_id_, instance_id, zone_a_, btadmin::Instance::PRODUCTION, 3)); EXPECT_EQ(std::future_status::timeout, instance_fut.wait_for(std::chrono::milliseconds(100))); std::thread t([cq]() mutable { cq.Run(); }); auto instance = instance_fut.get(); ASSERT_STATUS_OK(instance); EXPECT_STATUS_OK( client.DeleteInstance(bigtable::InstanceName(project_id_, instance_id))); cq.CancelAll(); cq.Shutdown(); t.join(); } } // namespace GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace bigtable_admin } // namespace cloud } // namespace google
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2019, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************************************************************/ #include "../ForwardTranslator.hpp" #include "../../model/Construction.hpp" #include "../../model/Construction_Impl.hpp" #include "../../model/Node.hpp" #include "../../model/Node_Impl.hpp" #include "../../model/PipeOutdoor.hpp" #include "../../model/PipeOutdoor_Impl.hpp" #include "../../utilities/idd/IddEnums.hpp" #include <utilities/idd/IddEnums.hxx> #include <utilities/idd/Pipe_Outdoor_FieldEnums.hxx> using namespace openstudio::model; namespace openstudio { namespace energyplus { boost::optional<IdfObject> ForwardTranslator::translatePipeOutdoor(PipeOutdoor & modelObject) { IdfObject idfObject(openstudio::IddObjectType::Pipe_Outdoor); m_idfObjects.push_back(idfObject); if(auto node = modelObject.inletModelObject()) { idfObject.setString(openstudio::Pipe_OutdoorFields::FluidInletNodeName, node->name().get()); } if(auto node = modelObject.outletModelObject()) { idfObject.setString(openstudio::Pipe_OutdoorFields::FluidOutletNodeName, node->name().get()); } if(auto value = modelObject.name()) { idfObject.setName(value.get()); } if(auto construction = modelObject.construction()) { idfObject.setString(openstudio::Pipe_OutdoorFields::ConstructionName, construction->name().get()); } if(auto node = modelObject.ambientTemperatureOutdoorAirNode()) { idfObject.setString(openstudio::Pipe_OutdoorFields::AmbientTemperatureOutdoorAirNodeName, node->name().get()); } else { auto name = modelObject.name().get() + " OA Node"; IdfObject oaNodeListIdf(openstudio::IddObjectType::OutdoorAir_NodeList); oaNodeListIdf.setString(0,name); m_idfObjects.push_back(oaNodeListIdf); idfObject.setString(openstudio::Pipe_OutdoorFields::AmbientTemperatureOutdoorAirNodeName, name); } idfObject.setDouble(openstudio::Pipe_OutdoorFields::PipeInsideDiameter, modelObject.pipeInsideDiameter()); idfObject.setDouble(openstudio::Pipe_OutdoorFields::PipeLength, modelObject.pipeLength()); return idfObject; } } // energyplus } // openstudio
//////////////////////////////////////////////////////////////////////////////////////////////////////// // November 2017 // Author: Juan Jose Chong <juan.chong@analog.com> //////////////////////////////////////////////////////////////////////////////////////////////////////// // ADIS16470.cpp //////////////////////////////////////////////////////////////////////////////////////////////////////// // // This library provides all the functions necessary to interface the ADIS16470 IMU with a // PJRC 32-Bit Teensy 3.2 Development Board. Functions for SPI configuration, reads and writes, // and scaling are included. This library may be used for the entire ADIS1646X family of devices // with some modification. // // 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 "ADIS16470.h" //////////////////////////////////////////////////////////////////////////// // Constructor with configurable CS, DR, and RST //////////////////////////////////////////////////////////////////////////// // CS - Chip select pin // DR - DR output pin for data ready // RST - Hardware reset pin //////////////////////////////////////////////////////////////////////////// ADIS16470::ADIS16470(int CS, int DR, int RST) { _CS = CS; _DR = DR; _RST = RST; // Initialize SPI SPI.begin(); // Set default pin states pinMode(_CS, OUTPUT); // Set CS pin to be an output pinMode(_DR, INPUT); // Set DR pin to be an input pinMode(_RST, OUTPUT); // Set RST pin to be an output digitalWrite(_CS, HIGH); // Initialize CS pin to be high digitalWrite(_RST, HIGH); // Initialize RST pin to be high } //////////////////////////////////////////////////////////////////////////// // Destructor //////////////////////////////////////////////////////////////////////////// ADIS16470::~ADIS16470() { } //////////////////////////////////////////////////////////////////////////// // Performs a hardware reset by setting _RST pin low for delay (in ms). // Returns 1 when complete. //////////////////////////////////////////////////////////////////////////// int ADIS16470::resetDUT(uint8_t ms) { digitalWrite(_RST, LOW); delay(ms); digitalWrite(_RST, HIGH); delay(ms); return(1); } //////////////////////////////////////////////////////////////////////////// // Selects the ADIS16470 for read/write operations. // Sets SPI bit order, clock divider, and data mode. // Also sets chip select to LOW. // This function is useful when there are multiple SPI devices // using different settings. // Returns 1 when complete. //////////////////////////////////////////////////////////////////////////// int ADIS16470::select() { SPISettings IMUSettings(1000000, MSBFIRST, SPI_MODE3); SPI.beginTransaction(IMUSettings); digitalWrite(_CS, LOW); // Set CS low to enable device return (1); } //////////////////////////////////////////////////////////////////////////// // Deselects the ADIS16470 for read/write operations. // Frees up the SPi bus for other devices. // Also sets chip select to HIGH. // Returns 1 when complete. //////////////////////////////////////////////////////////////////////////// int ADIS16470::deselect() { digitalWrite(_CS, HIGH); // Set CS high to disable device SPI.endTransaction(); return (1); } //////////////////////////////////////////////////////////////////////////////////////////// // Reads two bytes (one word) in two sequential registers over SPI // Returns an (int) signed 16 bit 2's complement number //////////////////////////////////////////////////////////////////////////////////////////// // regAddr - address of register to be read //////////////////////////////////////////////////////////////////////////////////////////// int16_t ADIS16470::regRead(uint8_t regAddr) { //Read registers using SPI // Write register address to be read select(); // select the device SPI.transfer(regAddr); // Write address over SPI bus SPI.transfer(0x00); // Write 0x00 to the SPI bus fill the 16 bit transaction requirement deselect(); // deselect the device delayMicroseconds(_stall); // Delay to not violate read rate // Read data from requested register select(); // select the device uint8_t _msbData = SPI.transfer(0x00); // Send (0x00) and place upper byte into variable uint8_t _lsbData = SPI.transfer(0x00); // Send (0x00) and place lower byte into variable deselect(); // deselect the device delayMicroseconds(_stall); // Delay to not violate read rate int16_t _dataOut = (_msbData << 8) | (_lsbData & 0xFF); // Concatenate upper and lower bytes // Shift MSB data left by 8 bits, mask LSB data with 0xFF, and OR both bits. return(_dataOut); } //////////////////////////////////////////////////////////////////////////// // Writes one byte of data to the specified register over SPI. // Returns 1 when complete. //////////////////////////////////////////////////////////////////////////// // regAddr - address of register to be written // regData - data to be written to the register //////////////////////////////////////////////////////////////////////////// int ADIS16470::regWrite(uint8_t regAddr, int16_t regData) { // Write register address and data uint16_t addr = (((regAddr & 0x7F) | 0x80) << 8); // Toggle sign bit, and check that the address is 8 bits uint16_t lowWord = (addr | (regData & 0xFF)); // OR Register address (A) with data(D) (AADD) uint16_t highWord = ((addr | 0x100) | ((regData >> 8) & 0xFF)); // OR Register address with data and increment address // Split words into chars uint8_t highBytehighWord = (highWord >> 8); uint8_t lowBytehighWord = (highWord & 0xFF); uint8_t highBytelowWord = (lowWord >> 8); uint8_t lowBytelowWord = (lowWord & 0xFF); // Write highWord to SPI bus select(); // select the device SPI.transfer(highBytelowWord); // Write high byte from low word to SPI bus SPI.transfer(lowBytelowWord); // Write low byte from low word to SPI bus deselect(); // deselect the device delayMicroseconds(_stall);; // Delay to not violate read rate // Write lowWord to SPI bus select(); // select the device SPI.transfer(highBytehighWord); // Write high byte from high word to SPI bus SPI.transfer(lowBytehighWord); // Write low byte from high word to SPI bus deselect(); // deselect the device delayMicroseconds(_stall);; // Delay to not violate read rate return(1); } //////////////////////////////////////////////////////////////////////////// // Intiates a burst read from the sensor. // Returns a pointer to an array of sensor data. //////////////////////////////////////////////////////////////////////////// // No inputs required. //////////////////////////////////////////////////////////////////////////// uint8_t *ADIS16470::byteBurst(void) { static uint8_t burstdata[20]; // Trigger Burst Read select(); // select the device SPI.transfer(0x68); SPI.transfer(0x00); // Read Burst Data burstdata[0] = SPI.transfer(0x00); //DIAG_STAT burstdata[1] = SPI.transfer(0x00); burstdata[2] = SPI.transfer(0x00); //XGYRO_OUT burstdata[3] = SPI.transfer(0x00); burstdata[4] = SPI.transfer(0x00); //YGYRO_OUT burstdata[5] = SPI.transfer(0x00); burstdata[6] = SPI.transfer(0x00); //ZGYRO_OUT burstdata[7] = SPI.transfer(0x00); burstdata[8] = SPI.transfer(0x00); //XACCEL_OUT burstdata[9] = SPI.transfer(0x00); burstdata[10] = SPI.transfer(0x00); //YACCEL_OUT burstdata[11] = SPI.transfer(0x00); burstdata[12] = SPI.transfer(0x00); //ZACCEL_OUT burstdata[13] = SPI.transfer(0x00); burstdata[14] = SPI.transfer(0x00); //TEMP_OUT burstdata[15] = SPI.transfer(0x00); burstdata[16] = SPI.transfer(0x00); //TIME_STMP burstdata[17] = SPI.transfer(0x00); burstdata[18] = SPI.transfer(0x00); //CHECKSUM burstdata[19] = SPI.transfer(0x00); deselect(); // deselect the device return burstdata; } //////////////////////////////////////////////////////////////////////////// // Intiates a burst read from the sensor. // Returns a pointer to an array of sensor data. //////////////////////////////////////////////////////////////////////////// // No inputs required. //////////////////////////////////////////////////////////////////////////// uint16_t *ADIS16470::wordBurst(void) { static uint16_t burstwords[10]; // Trigger Burst Read select(); // select the device SPI.transfer(0x68); SPI.transfer(0x00); // Read Burst Data burstwords[0] = ((SPI.transfer(0x00) << 8) | (SPI.transfer(0x00) & 0xFF)); //DIAG_STAT burstwords[1] = ((SPI.transfer(0x00) << 8) | (SPI.transfer(0x00) & 0xFF)); //XGYRO burstwords[2] = ((SPI.transfer(0x00) << 8) | (SPI.transfer(0x00) & 0xFF)); //YGYRO burstwords[3] = ((SPI.transfer(0x00) << 8) | (SPI.transfer(0x00) & 0xFF)); //ZGYRO burstwords[4] = ((SPI.transfer(0x00) << 8) | (SPI.transfer(0x00) & 0xFF)); //XACCEL burstwords[5] = ((SPI.transfer(0x00) << 8) | (SPI.transfer(0x00) & 0xFF)); //YACCEL burstwords[6] = ((SPI.transfer(0x00) << 8) | (SPI.transfer(0x00) & 0xFF)); //ZACCEL burstwords[7] = ((SPI.transfer(0x00) << 8) | (SPI.transfer(0x00) & 0xFF)); //TEMP_OUT burstwords[8] = ((SPI.transfer(0x00) << 8) | (SPI.transfer(0x00) & 0xFF)); //TIME_STMP burstwords[9] = ((SPI.transfer(0x00) << 8) | (SPI.transfer(0x00) & 0xFF)); //CHECKSUM deselect(); // deselect the device return burstwords; } //////////////////////////////////////////////////////////////////////////// // Calculates checksum based on burst data. // Returns the calculated checksum. //////////////////////////////////////////////////////////////////////////// // *burstArray - array of burst data // return - (int16_t) signed calculated checksum //////////////////////////////////////////////////////////////////////////// int16_t ADIS16470::checksum(uint16_t * burstArray) { int16_t s = 0; for (int i = 0; i < 9; i++) // Checksum value is not part of the sum!! { s += (burstArray[i] & 0xFF); // Count lower byte s += ((burstArray[i] >> 8) & 0xFF); // Count upper byte } return s; } ///////////////////////////////////////////////////////////////////////////////////////// // Converts accelerometer data output from the regRead() function // Returns (float) signed/scaled accelerometer in g's ///////////////////////////////////////////////////////////////////////////////////////// // sensorData - data output from regRead() ///////////////////////////////////////////////////////////////////////////////////////// float ADIS16470::accelScale(int16_t sensorData) { float finalData = sensorData * 0.00125; // Multiply by accel sensitivity (0.00125g/LSB) return finalData; } ///////////////////////////////////////////////////////////////////////////////////////////// // Converts gyro data output from the regRead() function // Returns (float) signed/scaled gyro in degrees/sec ///////////////////////////////////////////////////////////////////////////////////////////// // sensorData - data output from regRead() ///////////////////////////////////////////////////////////////////////////////////////// float ADIS16470::gyroScale(int16_t sensorData) { float finalData = sensorData * 0.1; // Multiply by gyro sensitivity (0.1 deg/LSB) return finalData; } ///////////////////////////////////////////////////////////////////////////////////////////// // Converts temperature data output from the regRead() function // Returns (float) signed/scaled temperature in degrees Celcius ///////////////////////////////////////////////////////////////////////////////////////////// // sensorData - data output from regRead() ///////////////////////////////////////////////////////////////////////////////////////// float ADIS16470::tempScale(int16_t sensorData) { float finalData = (sensorData * 0.1); // Multiply by temperature scale (0.1 deg C/LSB) return finalData; } ///////////////////////////////////////////////////////////////////////////////////////////// // Converts integrated angle data output from the regRead() function // Returns (float) signed/scaled delta angle in degrees ///////////////////////////////////////////////////////////////////////////////////////////// // sensorData - data output from regRead() ///////////////////////////////////////////////////////////////////////////////////////// float ADIS16470::deltaAngleScale(int16_t sensorData) { float finalData = sensorData * 0.061; // Multiply by delta angle scale (0.061 degrees/LSB) return finalData; } ///////////////////////////////////////////////////////////////////////////////////////////// // Converts integrated velocity data output from the regRead() function // Returns (float) signed/scaled delta velocity in m/sec ///////////////////////////////////////////////////////////////////////////////////////////// // sensorData - data output from regRead() ///////////////////////////////////////////////////////////////////////////////////////// float ADIS16470::deltaVelocityScale(int16_t sensorData) { float finalData = sensorData * 0.01221; // Multiply by velocity scale (0.01221 m/sec/LSB) return finalData; }
/* * Copyright (c) 2019 Contributors. * * The MIT License * * 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 "restriction_predicate.hxx" #include "sliced_lists.hxx" namespace graphene { namespace protocol { using result_type = object_restriction_predicate<operation>; result_type get_restriction_pred_list_9(size_t idx, vector<restriction> rs) { return typelist::runtime::dispatch(operation_list_9::list(), idx, [&rs] (auto t) { using Op = typename decltype(t)::type; result_type to_return = [p=restrictions_to_predicate<Op>(std::move(rs), true)] (const operation& op) { FC_ASSERT(op.which() == operation::tag<Op>::value, "Supplied operation is incorrect type for restriction predicate"); return p(op.get<Op>()); }; return to_return; }); } } }
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_main_parts.h" #include <memory> #include <utility> #if defined(OS_LINUX) #include <glib.h> // for g_setenv() #endif #include "base/base_switches.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/icon_manager.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/device_service.h" #include "content/public/browser/web_ui_controller_factory.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/result_codes.h" #include "electron/buildflags/buildflags.h" #include "media/base/localized_strings.h" #include "services/network/public/cpp/features.h" #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h" #include "shell/app/electron_main_delegate.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/browser.h" #include "shell/browser/browser_process_impl.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_web_ui_controller_factory.h" #include "shell/browser/feature_list.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/media/media_capture_devices_dispatcher.h" #include "shell/browser/node_debugger.h" #include "shell/browser/ui/devtools_manager_delegate.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/application_info.h" #include "shell/common/asar/asar_util.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_helper/trackable_object.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" #include "ui/base/idle/idle.h" #include "ui/base/ui_base_switches.h" #if defined(USE_AURA) #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/views/widget/desktop_aura/desktop_screen.h" #include "ui/wm/core/wm_state.h" #endif #if defined(USE_X11) #include "base/environment.h" #include "base/nix/xdg_util.h" #include "base/threading/thread_task_runner_handle.h" #include "ui/base/x/x11_util.h" #include "ui/events/devices/x11/touch_factory_x11.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/x/x11_types.h" #include "ui/gfx/x/xproto_util.h" #include "ui/gtk/gtk_ui.h" #include "ui/gtk/gtk_ui_delegate.h" #include "ui/gtk/gtk_util.h" #include "ui/gtk/x/gtk_ui_delegate_x11.h" #include "ui/views/linux_ui/linux_ui.h" #endif #if defined(OS_WIN) #include "ui/base/cursor/cursor_loader_win.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/l10n_util_win.h" #include "ui/display/win/dpi.h" #include "ui/gfx/system_fonts_win.h" #include "ui/strings/grit/app_locale_settings.h" #endif #if defined(OS_MAC) #include "shell/browser/ui/cocoa/views_delegate_mac.h" #else #include "shell/browser/ui/views/electron_views_delegate.h" #endif #if defined(OS_LINUX) #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck #endif namespace electron { namespace { template <typename T> void Erase(T* container, typename T::iterator iter) { container->erase(iter); } #if defined(OS_WIN) // gfx::Font callbacks void AdjustUIFont(gfx::win::FontAdjustment* font_adjustment) { l10n_util::NeedOverrideDefaultUIFont(&font_adjustment->font_family_override, &font_adjustment->font_scale); font_adjustment->font_scale *= display::win::GetAccessibilityFontScale(); } int GetMinimumFontSize() { int min_font_size; base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE), &min_font_size); return min_font_size; } #endif base::string16 MediaStringProvider(media::MessageId id) { switch (id) { case media::DEFAULT_AUDIO_DEVICE_NAME: return base::ASCIIToUTF16("Default"); #if defined(OS_WIN) case media::COMMUNICATIONS_AUDIO_DEVICE_NAME: return base::ASCIIToUTF16("Communications"); #endif default: return base::string16(); } } #if defined(USE_X11) // Indicates that we're currently responding to an IO error (by shutting down). bool g_in_x11_io_error_handler = false; // Number of seconds to wait for UI thread to get an IO error if we get it on // the background thread. const int kWaitForUIThreadSeconds = 10; void OverrideLinuxAppDataPath() { base::FilePath path; if (base::PathService::Get(DIR_APP_DATA, &path)) return; std::unique_ptr<base::Environment> env(base::Environment::Create()); path = base::nix::GetXDGDirectory(env.get(), base::nix::kXdgConfigHomeEnvVar, base::nix::kDotConfigDir); base::PathService::Override(DIR_APP_DATA, path); } int BrowserX11ErrorHandler(Display* d, XErrorEvent* error) { if (!g_in_x11_io_error_handler && base::ThreadTaskRunnerHandle::IsSet()) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&x11::LogErrorEventDescription, *error)); } return 0; } // This function is used to help us diagnose crash dumps that happen // during the shutdown process. NOINLINE void WaitingForUIThreadToHandleIOError() { // Ensure function isn't optimized away. asm(""); sleep(kWaitForUIThreadSeconds); } int BrowserX11IOErrorHandler(Display* d) { if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { // Wait for the UI thread (which has a different connection to the X server) // to get the error. We can't call shutdown from this thread without // tripping an error. Doing it through a function so that we'll be able // to see it in any crash dumps. WaitingForUIThreadToHandleIOError(); return 0; } // If there's an IO error it likely means the X server has gone away. // If this DCHECK fails, then that means SessionEnding() below triggered some // code that tried to talk to the X server, resulting in yet another error. DCHECK(!g_in_x11_io_error_handler); g_in_x11_io_error_handler = true; LOG(ERROR) << "X IO error received (X server probably went away)"; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::RunLoop::QuitCurrentWhenIdleClosureDeprecated()); return 0; } int X11EmptyErrorHandler(Display* d, XErrorEvent* error) { return 0; } int X11EmptyIOErrorHandler(Display* d) { return 0; } // GTK does not provide a way to check if current theme is dark, so we compare // the text and background luminosity to get a result. // This trick comes from FireFox. void UpdateDarkThemeSetting() { float bg = color_utils::GetRelativeLuminance(gtk::GetBgColor("GtkLabel")); float fg = color_utils::GetRelativeLuminance(gtk::GetFgColor("GtkLabel")); bool is_dark = fg > bg; // Pass it to NativeUi theme, which is used by the nativeTheme module and most // places in Electron. ui::NativeTheme::GetInstanceForNativeUi()->set_use_dark_colors(is_dark); // Pass it to Web Theme, to make "prefers-color-scheme" media query work. ui::NativeTheme::GetInstanceForWeb()->set_use_dark_colors(is_dark); } #endif } // namespace #if defined(USE_X11) class DarkThemeObserver : public ui::NativeThemeObserver { public: DarkThemeObserver() = default; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override { UpdateDarkThemeSetting(); } }; #endif // static ElectronBrowserMainParts* ElectronBrowserMainParts::self_ = nullptr; ElectronBrowserMainParts::ElectronBrowserMainParts( const content::MainFunctionParams& params) : fake_browser_process_(new BrowserProcessImpl), browser_(new Browser), node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::BROWSER)), electron_bindings_(new ElectronBindings(node_bindings_->uv_loop())) { DCHECK(!self_) << "Cannot have two ElectronBrowserMainParts"; self_ = this; } ElectronBrowserMainParts::~ElectronBrowserMainParts() { asar::ClearArchives(); } // static ElectronBrowserMainParts* ElectronBrowserMainParts::Get() { DCHECK(self_); return self_; } bool ElectronBrowserMainParts::SetExitCode(int code) { if (!exit_code_) return false; *exit_code_ = code; return true; } int ElectronBrowserMainParts::GetExitCode() { return exit_code_ != nullptr ? *exit_code_ : 0; } void ElectronBrowserMainParts::RegisterDestructionCallback( base::OnceClosure callback) { // The destructors should be called in reversed order, so dependencies between // JavaScript objects can be correctly resolved. // For example WebContentsView => WebContents => Session. destructors_.insert(destructors_.begin(), std::move(callback)); } int ElectronBrowserMainParts::PreEarlyInitialization() { field_trial_list_ = std::make_unique<base::FieldTrialList>(nullptr); #if defined(USE_X11) OverrideLinuxAppDataPath(); // Installs the X11 error handlers for the browser process used during // startup. They simply print error messages and exit because // we can't shutdown properly while creating and initializing services. ui::SetX11ErrorHandlers(nullptr, nullptr); #endif #if defined(OS_POSIX) HandleSIGCHLD(); #endif return service_manager::RESULT_CODE_NORMAL_EXIT; } void ElectronBrowserMainParts::PostEarlyInitialization() { // A workaround was previously needed because there was no ThreadTaskRunner // set. If this check is failing we may need to re-add that workaround DCHECK(base::ThreadTaskRunnerHandle::IsSet()); // The ProxyResolverV8 has setup a complete V8 environment, in order to // avoid conflicts we only initialize our V8 environment after that. js_env_ = std::make_unique<JavascriptEnvironment>(node_bindings_->uv_loop()); v8::HandleScope scope(js_env_->isolate()); node_bindings_->Initialize(); // Create the global environment. node::Environment* env = node_bindings_->CreateEnvironment( js_env_->context(), js_env_->platform()); node_env_ = std::make_unique<NodeEnvironment>(env); // Enable support for v8 inspector node_debugger_ = std::make_unique<NodeDebugger>(env); node_debugger_->Start(); env->set_trace_sync_io(env->options()->trace_sync_io); // Add Electron extended APIs. electron_bindings_->BindTo(js_env_->isolate(), env->process_object()); // Load everything. node_bindings_->LoadEnvironment(env); // Wrap the uv loop with global env. node_bindings_->set_uv_env(env); // We already initialized the feature list in PreEarlyInitialization(), but // the user JS script would not have had a chance to alter the command-line // switches at that point. Lets reinitialize it here to pick up the // command-line changes. base::FeatureList::ClearInstanceForTesting(); InitializeFeatureList(); // Initialize after user script environment creation. fake_browser_process_->PostEarlyInitialization(); } int ElectronBrowserMainParts::PreCreateThreads() { #if defined(USE_AURA) display::Screen* screen = views::CreateDesktopScreen(); display::Screen::SetScreenInstance(screen); #if defined(USE_X11) views::LinuxUI::instance()->UpdateDeviceScaleFactor(); #endif #endif if (!views::LayoutProvider::Get()) layout_provider_ = std::make_unique<views::LayoutProvider>(); // Initialize the app locale. fake_browser_process_->SetApplicationLocale( ElectronBrowserClient::Get()->GetApplicationLocale()); // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); #if defined(OS_MAC) ui::InitIdleMonitor(); #endif fake_browser_process_->PreCreateThreads(); // Notify observers. Browser::Get()->PreCreateThreads(); return 0; } void ElectronBrowserMainParts::PostCreateThreads() { base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread)); } void ElectronBrowserMainParts::PostDestroyThreads() { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_browser_client_.reset(); extensions::ExtensionsBrowserClient::Set(nullptr); #endif #if defined(OS_LINUX) device::BluetoothAdapterFactory::Shutdown(); bluez::DBusBluezManagerWrapperLinux::Shutdown(); #endif fake_browser_process_->PostDestroyThreads(); } void ElectronBrowserMainParts::ToolkitInitialized() { #if defined(USE_X11) // In Aura/X11, Gtk-based LinuxUI implementation is used. gtk_ui_delegate_ = std::make_unique<ui::GtkUiDelegateX11>(x11::Connection::Get()); ui::GtkUiDelegate::SetInstance(gtk_ui_delegate_.get()); views::LinuxUI* linux_ui = BuildGtkUi(gtk_ui_delegate_.get()); views::LinuxUI::SetInstance(linux_ui); linux_ui->Initialize(); // Chromium does not respect GTK dark theme setting, but they may change // in future and this code might be no longer needed. Check the Chromium // issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=998903 UpdateDarkThemeSetting(); // Update the naitve theme when GTK theme changes. The GetNativeTheme // here returns a NativeThemeGtk, which monitors GTK settings. dark_theme_observer_.reset(new DarkThemeObserver); linux_ui->GetNativeTheme(nullptr)->AddObserver(dark_theme_observer_.get()); #endif #if defined(USE_AURA) wm_state_ = std::make_unique<wm::WMState>(); #endif #if defined(OS_WIN) gfx::win::SetAdjustFontCallback(&AdjustUIFont); gfx::win::SetGetMinimumFontSizeCallback(&GetMinimumFontSize); wchar_t module_name[MAX_PATH] = {0}; if (GetModuleFileName(NULL, module_name, base::size(module_name))) ui::CursorLoaderWin::SetCursorResourceModule(module_name); #endif #if defined(OS_MAC) views_delegate_.reset(new ViewsDelegateMac); #else views_delegate_ = std::make_unique<ViewsDelegate>(); #endif } void ElectronBrowserMainParts::PreMainMessageLoopRun() { // Run user's main script before most things get initialized, so we can have // a chance to setup everything. node_bindings_->PrepareMessageLoop(); node_bindings_->RunMessageLoop(); // url::Add*Scheme are not threadsafe, this helps prevent data races. url::LockSchemeRegistries(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_client_ = std::make_unique<ElectronExtensionsClient>(); extensions::ExtensionsClient::Set(extensions_client_.get()); // BrowserContextKeyedAPIServiceFactories require an ExtensionsBrowserClient. extensions_browser_client_ = std::make_unique<ElectronExtensionsBrowserClient>(); extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get()); extensions::EnsureBrowserContextKeyedServiceFactoriesBuilt(); extensions::electron::EnsureBrowserContextKeyedServiceFactoriesBuilt(); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) SpellcheckServiceFactory::GetInstance(); #endif #if defined(USE_X11) ui::TouchFactory::SetTouchDeviceListFromCommandLine(); #endif // Start idle gc. gc_timer_.Start(FROM_HERE, base::TimeDelta::FromMinutes(1), base::BindRepeating(&v8::Isolate::LowMemoryNotification, base::Unretained(js_env_->isolate()))); content::WebUIControllerFactory::RegisterFactory( ElectronWebUIControllerFactory::GetInstance()); auto* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kRemoteDebuggingPipe)) { // --remote-debugging-pipe content::DevToolsAgentHost::StartRemoteDebuggingPipeHandler(); } else if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) { // --remote-debugging-port DevToolsManagerDelegate::StartHttpHandler(); } #if !defined(OS_MAC) // The corresponding call in macOS is in ElectronApplicationDelegate. Browser::Get()->WillFinishLaunching(); Browser::Get()->DidFinishLaunching(base::DictionaryValue()); #endif // Notify observers that main thread message loop was initialized. Browser::Get()->PreMainMessageLoopRun(); } bool ElectronBrowserMainParts::MainMessageLoopRun(int* result_code) { js_env_->OnMessageLoopCreated(); exit_code_ = result_code; return content::BrowserMainParts::MainMessageLoopRun(result_code); } void ElectronBrowserMainParts::PreDefaultMainMessageLoopRun( base::OnceClosure quit_closure) { Browser::Get()->SetMainMessageLoopQuitClosure(std::move(quit_closure)); } void ElectronBrowserMainParts::PostMainMessageLoopStart() { #if defined(USE_X11) // Installs the X11 error handlers for the browser process after the // main message loop has started. This will allow us to exit cleanly // if X exits before us. ui::SetX11ErrorHandlers(BrowserX11ErrorHandler, BrowserX11IOErrorHandler); #endif #if defined(OS_LINUX) bluez::DBusBluezManagerWrapperLinux::Initialize(); #endif #if defined(OS_POSIX) HandleShutdownSignals(); #endif } void ElectronBrowserMainParts::PostMainMessageLoopRun() { #if defined(USE_X11) // Unset the X11 error handlers. The X11 error handlers log the errors using a // |PostTask()| on the message-loop. But since the message-loop is in the // process of terminating, this can cause errors. ui::SetX11ErrorHandlers(X11EmptyErrorHandler, X11EmptyIOErrorHandler); #endif #if defined(OS_MAC) FreeAppDelegate(); #endif // Make sure destruction callbacks are called before message loop is // destroyed, otherwise some objects that need to be deleted on IO thread // won't be freed. // We don't use ranged for loop because iterators are getting invalided when // the callback runs. for (auto iter = destructors_.begin(); iter != destructors_.end();) { base::OnceClosure callback = std::move(*iter); if (!callback.is_null()) std::move(callback).Run(); ++iter; } // Destroy node platform after all destructors_ are executed, as they may // invoke Node/V8 APIs inside them. node_debugger_->Stop(); node_env_->env()->set_trace_sync_io(false); js_env_->OnMessageLoopDestroying(); node_env_.reset(); ElectronBrowserContext::browser_context_map().clear(); fake_browser_process_->PostMainMessageLoopRun(); content::DevToolsAgentHost::StopRemoteDebuggingPipeHandler(); } #if !defined(OS_MAC) void ElectronBrowserMainParts::PreMainMessageLoopStart() { PreMainMessageLoopStartCommon(); } #endif void ElectronBrowserMainParts::PreMainMessageLoopStartCommon() { #if defined(OS_MAC) InitializeMainNib(); RegisterURLHandler(); #endif media::SetLocalizedStringProvider(MediaStringProvider); } device::mojom::GeolocationControl* ElectronBrowserMainParts::GetGeolocationControl() { if (!geolocation_control_) { content::GetDeviceService().BindGeolocationControl( geolocation_control_.BindNewPipeAndPassReceiver()); } return geolocation_control_.get(); } IconManager* ElectronBrowserMainParts::GetIconManager() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!icon_manager_.get()) icon_manager_ = std::make_unique<IconManager>(); return icon_manager_.get(); } } // namespace electron
#include <gmock/gmock.h> #include <facter/facts/resolvers/filesystem_resolver.hpp> #include <facter/facts/collection.hpp> #include <facter/facts/fact.hpp> #include <facter/facts/scalar_value.hpp> #include <facter/facts/map_value.hpp> #include <facter/facts/array_value.hpp> using namespace std; using namespace facter::facts; using namespace facter::facts::resolvers; struct empty_filesystem_resolver : filesystem_resolver { protected: virtual data collect_data(collection& facts) override { return {}; } }; struct test_filesystem_resolver : filesystem_resolver { void add_mountpoint(string name, string device, string filesystem, uint64_t size, uint64_t available, vector<string> options) { mountpoint mp; mp.name = move(name); mp.device = move(device); mp.filesystem = move(filesystem); mp.size = size; mp.available = available; mp.options = move(options); mountpoints.emplace_back(move(mp)); } void add_filesystem(string filesystem) { filesystems.emplace(move(filesystem)); } void add_partition(string name, string filesystem, uint64_t size, string uuid, string partuuid, string label, string partlabel, string mount) { partition p; p.name = move(name); p.filesystem = move(filesystem); p.size = size; p.uuid = move(uuid); p.partition_uuid = move(partuuid); p.label = move(label); p.partition_label = move(partlabel); p.mount = move(mount); partitions.emplace_back(move(p)); } protected: virtual data collect_data(collection& facts) override { data result; result.mountpoints = move(mountpoints); result.filesystems = move(filesystems); result.partitions = move(partitions); return result; } vector<mountpoint> mountpoints; set<string> filesystems; vector<partition> partitions; }; TEST(facter_facts_resolvers_filesystem_resolver, empty) { collection facts; facts.add(make_shared<empty_filesystem_resolver>()); ASSERT_EQ(0u, facts.size()); } TEST(facter_facts_resolvers_filesystem_resolver, mountpoints) { collection facts; auto resolver = make_shared<test_filesystem_resolver>(); const unsigned int count = 5; for (unsigned int i = 0; i < count; ++i) { string num = to_string(i); resolver->add_mountpoint("mount" + num, "device" + num, "filesystem" + num, 12345, 1000, {"option1" + num, "option2" + num, "option3" + num}); } facts.add(move(resolver)); ASSERT_EQ(1u, facts.size()); auto mountpoints = facts.get<map_value>(fact::mountpoints); ASSERT_NE(nullptr, mountpoints); ASSERT_EQ(5u, mountpoints->size()); for (unsigned int i = 0; i < count; ++i) { string num = to_string(i); auto mountpoint = mountpoints->get<map_value>("mount" + num); ASSERT_NE(nullptr, mountpoint); ASSERT_EQ(10u, mountpoint->size()); auto available = mountpoint->get<string_value>("available"); ASSERT_NE(nullptr, available); ASSERT_EQ("1000 bytes", available->value()); auto available_bytes = mountpoint->get<integer_value>("available_bytes"); ASSERT_NE(nullptr, available_bytes); ASSERT_EQ(1000, available_bytes->value()); auto capacity = mountpoint->get<string_value>("capacity"); ASSERT_NE(nullptr, capacity); ASSERT_EQ("91.90%", capacity->value()); auto device = mountpoint->get<string_value>("device"); ASSERT_NE(nullptr, device); ASSERT_EQ("device" + num, device->value()); auto filesystem = mountpoint->get<string_value>("filesystem"); ASSERT_NE(nullptr, filesystem); ASSERT_EQ("filesystem" + num, filesystem->value()); auto options = mountpoint->get<array_value>("options"); ASSERT_NE(nullptr, options); ASSERT_EQ(3u, options->size()); ASSERT_EQ("option1" + num, options->get<string_value>(0)->value()); ASSERT_EQ("option2" + num, options->get<string_value>(1)->value()); ASSERT_EQ("option3" + num, options->get<string_value>(2)->value()); auto size = mountpoint->get<string_value>("size"); ASSERT_NE(nullptr, size); ASSERT_EQ("12.06 KiB", size->value()); auto size_bytes = mountpoint->get<integer_value>("size_bytes"); ASSERT_NE(nullptr, size_bytes); ASSERT_EQ(12345, size_bytes->value()); auto used = mountpoint->get<string_value>("used"); ASSERT_NE(nullptr, used); ASSERT_EQ("11.08 KiB", used->value()); auto used_bytes = mountpoint->get<integer_value>("used_bytes"); ASSERT_NE(nullptr, used_bytes); ASSERT_EQ(12345 - 1000, used_bytes->value()); } } TEST(facter_facts_resolvers_filesystem_resolver, filesystems) { collection facts; auto resolver = make_shared<test_filesystem_resolver>(); resolver->add_filesystem("foo"); resolver->add_filesystem("bar"); resolver->add_filesystem("baz"); facts.add(move(resolver)); ASSERT_EQ(1u, facts.size()); auto filesystems = facts.get<string_value>(fact::filesystems); ASSERT_NE(nullptr, filesystems); ASSERT_EQ("bar,baz,foo", filesystems->value()); } TEST(facter_facts_resolvers_filesystem_resolver, partitions) { collection facts; auto resolver = make_shared<test_filesystem_resolver>(); const unsigned int count = 5; for (unsigned int i = 0; i < count; ++i) { string num = to_string(i); resolver->add_partition("partition" + num, "filesystem" + num, 12345 + i, "uuid" + num, "partuuid" + num, "label" + num, "partlabel" + num, "mount" + num); } facts.add(move(resolver)); ASSERT_EQ(1u, facts.size()); auto partitions = facts.get<map_value>(fact::partitions); ASSERT_NE(nullptr, partitions); for (unsigned int i = 0; i < count; ++i) { string num = to_string(i); auto partition = partitions->get<map_value>("partition" + num); ASSERT_NE(nullptr, partition); ASSERT_EQ(8u, partition->size()); auto filesystem = partition->get<string_value>("filesystem"); ASSERT_NE(nullptr, filesystem); ASSERT_EQ("filesystem" + num, filesystem->value()); auto label = partition->get<string_value>("label"); ASSERT_NE(nullptr, label); ASSERT_EQ("label" + num, label->value()); auto partlabel = partition->get<string_value>("partlabel"); ASSERT_NE(nullptr, partlabel); ASSERT_EQ("partlabel" + num, partlabel->value()); auto mount = partition->get<string_value>("mount"); ASSERT_NE(nullptr, mount); ASSERT_EQ("mount" + num, mount->value()); auto partuuid = partition->get<string_value>("partuuid"); ASSERT_NE(nullptr, partuuid); ASSERT_EQ("partuuid" + num, partuuid->value()); auto uuid = partition->get<string_value>("uuid"); ASSERT_NE(nullptr, uuid); ASSERT_EQ("uuid" + num, uuid->value()); auto size_bytes = partition->get<integer_value>("size_bytes"); ASSERT_NE(nullptr, size_bytes); ASSERT_EQ(12345 + i, size_bytes->value()); auto size = partition->get<string_value>("size"); ASSERT_NE(nullptr, size); ASSERT_EQ("12.06 KiB", size->value()); } }
/* * Copyright (c) 2010 WiYun Inc. * Author: luma(stubma@gmail.com) * * For all entities this program is free software; you can redistribute * it and/or modify it under the terms of the 'WiEngine' license with * the additional provision that 'WiEngine' must be credited in a manner * that can be be observed by end users, for example, in the credits or during * start up. (please find WiEngine logo in sdk's logo folder) * * 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 "wyNotifyOnReceiveHttpResponseRunnable.h" #include "wyHttpRequest.h" wyNotifyOnReceiveHttpResponseRunnable::wyNotifyOnReceiveHttpResponseRunnable(wyHttpResponse* response, wyHttpListener* listener) { m_response = response; wyObjectRetain(m_response); m_listener = listener; } wyNotifyOnReceiveHttpResponseRunnable::~wyNotifyOnReceiveHttpResponseRunnable() { wyObjectRelease(m_response); } wyNotifyOnReceiveHttpResponseRunnable* wyNotifyOnReceiveHttpResponseRunnable::make(wyHttpResponse* response, wyHttpListener* listener) { wyNotifyOnReceiveHttpResponseRunnable* n = WYNEW wyNotifyOnReceiveHttpResponseRunnable(response, listener); return (wyNotifyOnReceiveHttpResponseRunnable*)n->autoRelease(); } void wyNotifyOnReceiveHttpResponseRunnable::run() { if(m_listener && !m_response->getRequest()->isCancelled()) { m_listener->onHttpReceiveResponse(m_response); } }
#include <iostream> #include <verilated_vcd_c.h> #define VL_DEBUG #include "Vtop.h" #include "verilated.h" static vluint64_t main_time = 0; double sc_time_stamp() { return main_time; } int main (int argc, char **argv) { Verilated::commandArgs(argc, argv); Vtop *top = new Vtop(); Verilated::traceEverOn(true); VerilatedVcdC* tfp = new VerilatedVcdC; top->trace(tfp, 99); tfp->open("dump.vcd"); while (!Verilated::gotFinish() && (main_time < 100)) { top->eval(); tfp->dump(main_time); main_time += 1; std::cout << "time: " << main_time << std::endl; } top->final(); tfp->close(); delete top; return 0; }
//===-- AlphaTargetInfo.cpp - Alpha Target Implementation -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Alpha.h" #include "llvm/Module.h" #include "llvm/Target/TargetRegistry.h" using namespace llvm; llvm::Target llvm::TheAlphaTarget; extern "C" void LLVMInitializeAlphaTargetInfo() { RegisterTarget<Triple::alpha, /*HasJIT=*/true> X(TheAlphaTarget, "alpha", "Alpha [experimental]"); }
/* * BruteForceClosestPair.cpp * * Created on: Jan 25, 2011 * Author: TF */ #include "BruteForceClosestPair.h" #include "MathTools.h" namespace GEOLIB { BruteForceClosestPair::BruteForceClosestPair( std::vector<GEOLIB::Point*> const & pnts, size_t& id0, size_t& id1) : ClosestPair (pnts, id0, id1) { double sqr_shortest_dist (MathLib::sqrDist (_pnts[0], _pnts[1])); const size_t n_pnts (_pnts.size()); for (size_t i(0); i < n_pnts; i++) for (size_t j(i + 1); j < n_pnts; j++) { double sqr_dist (MathLib::sqrDist (_pnts[i], _pnts[j])); if (sqr_dist < sqr_shortest_dist) { sqr_shortest_dist = sqr_dist; _id0 = i; _id1 = j; } } id0 = _id0; id1 = _id1; } } // end namespace GEOLIB
/*========================== begin_copyright_notice ============================ Copyright (C) 2017-2021 Intel Corporation SPDX-License-Identifier: MIT ============================= end_copyright_notice ===========================*/ #include "common/LLVMWarningsPush.hpp" #include <llvm/Pass.h> #include <llvm/IR/DataLayout.h> #include <llvm/IR/IRBuilder.h> #include <llvmWrapper/Support/Alignment.h> #include <llvm/Support/Debug.h> #include <llvm/Support/MathExtras.h> #include <llvm/Support/raw_ostream.h> #include <llvmWrapper/IR/DerivedTypes.h> #include "common/LLVMWarningsPop.hpp" #include "Compiler/CISACodeGen/ShaderCodeGen.hpp" #include "Compiler/IGCPassSupport.h" #include "Compiler/CISACodeGen/LdShrink.h" #include "Probe/Assertion.h" using namespace llvm; using namespace IGC; namespace { // A simple pass to shrink vector load into scalar or narrow vector load // when only partial elements are used. class LdShrink : public FunctionPass { const DataLayout* DL; public: static char ID; LdShrink() : FunctionPass(ID) { initializeLdShrinkPass(*PassRegistry::getPassRegistry()); } bool runOnFunction(Function& F) override; private: void getAnalysisUsage(AnalysisUsage& AU) const override { AU.setPreservesCFG(); } unsigned getExtractIndexMask(LoadInst* LI) const; }; char LdShrink::ID = 0; } // End anonymous namespace FunctionPass* createLdShrinkPass() { return new LdShrink(); } #define PASS_FLAG "igc-ldshrink" #define PASS_DESC "IGC Load Shrink" #define PASS_CFG_ONLY false #define PASS_ANALYSIS false IGC_INITIALIZE_PASS_BEGIN(LdShrink, PASS_FLAG, PASS_DESC, PASS_CFG_ONLY, PASS_ANALYSIS) IGC_INITIALIZE_PASS_END(LdShrink, PASS_FLAG, PASS_DESC, PASS_CFG_ONLY, PASS_ANALYSIS) unsigned LdShrink::getExtractIndexMask(LoadInst* LI) const { IGCLLVM::FixedVectorType* VTy = dyn_cast<IGCLLVM::FixedVectorType>(LI->getType()); // Skip non-vector loads. if (!VTy) return 0; // Skip if there are more than 32 elements. if (VTy->getNumElements() > 32) return 0; // Check whether all users are ExtractElement with constant index. // Collect index mask at the same time. Type* Ty = VTy->getScalarType(); // Skip non-BYTE addressable data types. So far, check integer types // only. if (IntegerType * ITy = dyn_cast<IntegerType>(Ty)) { // Unroll isPowerOf2ByteWidth, it was removed in LLVM 12. unsigned BitWidth = ITy->getBitWidth(); if (!((BitWidth > 7) && isPowerOf2_32(BitWidth))) return 0; } unsigned Mask = 0; // Maxmimally 32 elements. for (auto UI = LI->user_begin(), UE = LI->user_end(); UI != UE; ++UI) { ExtractElementInst* EEI = dyn_cast<ExtractElementInst>(*UI); if (!EEI) return 0; // Skip non-constant index. auto Idx = dyn_cast<ConstantInt>(EEI->getIndexOperand()); if (!Idx) return 0; IGC_ASSERT_MESSAGE(Idx->getZExtValue() < 32, "Index is out of range!"); Mask |= (1 << Idx->getZExtValue()); } return Mask; } bool LdShrink::runOnFunction(Function& F) { DL = &F.getParent()->getDataLayout(); if (!DL) return false; bool Changed = false; for (auto& BB : F) { for (auto BI = BB.begin(), BE = BB.end(); BI != BE; /*EMPTY*/) { LoadInst* LI = dyn_cast<LoadInst>(BI++); // Skip non-load instructions. if (!LI) continue; // Skip non-simple load. if (!LI->isSimple()) continue; // Replace it with scalar load or narrow vector load. unsigned Mask = getExtractIndexMask(LI); if (!Mask) continue; if (!isShiftedMask_32(Mask)) continue; unsigned Offset = llvm::countTrailingZeros(Mask); unsigned Length = llvm::countTrailingZeros((Mask >> Offset) + 1); // TODO: So far skip narrow vector. if (Length != 1) continue; IRBuilder<> Builder(LI); // Shrink it to scalar load. auto Ptr = LI->getPointerOperand(); Type* Ty = LI->getType(); Type* ScalarTy = Ty->getScalarType(); PointerType* PtrTy = cast<PointerType>(Ptr->getType()); PointerType* ScalarPtrTy = PointerType::get(ScalarTy, PtrTy->getAddressSpace()); Value* ScalarPtr = Builder.CreatePointerCast(Ptr, ScalarPtrTy); if (Offset) ScalarPtr = Builder.CreateInBoundsGEP(ScalarPtr, Builder.getInt32(Offset)); unsigned alignment = int_cast<unsigned int>(MinAlign(LI->getAlignment(), DL->getTypeStoreSize(ScalarTy) * Offset)); LoadInst* NewLoad = Builder.CreateAlignedLoad(ScalarPtr, IGCLLVM::getAlign(alignment)); NewLoad->setDebugLoc(LI->getDebugLoc()); ExtractElementInst* EEI = cast<ExtractElementInst>(*LI->user_begin()); EEI->replaceAllUsesWith(NewLoad); } } return Changed; }
/* * Copyright 2010-2016 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/iam/model/GetAccountPasswordPolicyRequest.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> using namespace Aws::IAM::Model; using namespace Aws::Utils; GetAccountPasswordPolicyRequest::GetAccountPasswordPolicyRequest() { } Aws::String GetAccountPasswordPolicyRequest::SerializePayload() const { Aws::StringStream ss; ss << "Action=GetAccountPasswordPolicy&"; ss << "Version=2010-05-08"; return ss.str(); }
/* Source File : InputFileDriver.h Copyright 2013 Gal Kahana HummusJS 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 "InputFileDriver.h" #include "InputFile.h" #include "ByteReaderWithPositionDriver.h" using namespace v8; Persistent<Function> InputFileDriver::constructor; Persistent<FunctionTemplate> InputFileDriver::constructor_template; InputFileDriver::InputFileDriver() { mInputFileInstance = new InputFile(); mOwnsInstance = true; } InputFileDriver::~InputFileDriver() { if(mOwnsInstance) delete mInputFileInstance; } PDFHummus::EStatusCode InputFileDriver::OpenFile(const std::string& inFilePath) { if(!mInputFileInstance) mInputFileInstance = new InputFile(); mOwnsInstance = true; return mInputFileInstance->OpenFile(inFilePath); } void InputFileDriver::SetFromOwnedFile(InputFile* inFile) { if(mInputFileInstance && mOwnsInstance) delete mInputFileInstance; mOwnsInstance = false; mInputFileInstance = inFile; } void InputFileDriver::Init(Handle<Object> inExports) { CREATE_ISOLATE_CONTEXT; Local<FunctionTemplate> t = NEW_FUNCTION_TEMPLATE(New); t->SetClassName(NEW_STRING("InputFile")); t->InstanceTemplate()->SetInternalFieldCount(1); SET_PROTOTYPE_METHOD(t, "openFile", OpenFile); SET_PROTOTYPE_METHOD(t, "closeFile", CloseFile); SET_PROTOTYPE_METHOD(t, "getFilePath", GetFilePath); SET_PROTOTYPE_METHOD(t, "getFileSize", GetFileSize); SET_PROTOTYPE_METHOD(t, "getInputStream", GetInputStream); SET_CONSTRUCTOR(constructor, t); SET_CONSTRUCTOR_TEMPLATE(constructor_template, t); SET_CONSTRUCTOR_EXPORT(inExports, "InputFile", t); } METHOD_RETURN_TYPE InputFileDriver::NewInstance(const ARGS_TYPE& args) { CREATE_ISOLATE_CONTEXT; CREATE_ESCAPABLE_SCOPE; Local<Object> instance = NEW_INSTANCE(constructor); SET_FUNCTION_RETURN_VALUE(instance); } v8::Handle<v8::Value> InputFileDriver::GetNewInstance(const ARGS_TYPE& args) { CREATE_ISOLATE_CONTEXT; CREATE_ESCAPABLE_SCOPE; Local<Object> instance = NEW_INSTANCE(constructor); return CLOSE_SCOPE(instance); } bool InputFileDriver::HasInstance(Handle<Value> inObject) { CREATE_ISOLATE_CONTEXT; return inObject->IsObject() && HAS_INSTANCE(constructor_template, inObject); } METHOD_RETURN_TYPE InputFileDriver::New(const ARGS_TYPE& args) { CREATE_ISOLATE_CONTEXT; CREATE_ESCAPABLE_SCOPE; InputFileDriver* inputFile = new InputFileDriver(); if(args.Length() == 1 && args[0]->IsString()) inputFile->OpenFile(*String::Utf8Value(args[0]->ToString())); inputFile->Wrap(args.This()); SET_FUNCTION_RETURN_VALUE(args.This()); } METHOD_RETURN_TYPE InputFileDriver::OpenFile(const ARGS_TYPE& args) { CREATE_ISOLATE_CONTEXT; CREATE_ESCAPABLE_SCOPE; if(args.Length() != 1 || !args[0]->IsString()) { THROW_EXCEPTION("wrong arguments. please provide a string for the file path"); SET_FUNCTION_RETURN_VALUE(UNDEFINED); } InputFileDriver* driver = ObjectWrap::Unwrap<InputFileDriver>(args.This()); if(!driver) { THROW_EXCEPTION("no driver created...please create one through Hummus"); SET_FUNCTION_RETURN_VALUE(UNDEFINED); } if(driver->OpenFile(*String::Utf8Value(args[0]->ToString())) != PDFHummus::eSuccess) { THROW_EXCEPTION("can't open file. make sure path exists"); SET_FUNCTION_RETURN_VALUE(UNDEFINED); } SET_FUNCTION_RETURN_VALUE(UNDEFINED); } METHOD_RETURN_TYPE InputFileDriver::CloseFile(const ARGS_TYPE& args) { CREATE_ISOLATE_CONTEXT; CREATE_ESCAPABLE_SCOPE; InputFileDriver* driver = ObjectWrap::Unwrap<InputFileDriver>(args.This()); if(!driver) { THROW_EXCEPTION("no driver created...please create one through Hummus"); SET_FUNCTION_RETURN_VALUE(UNDEFINED); } if(driver->mInputFileInstance) driver->mInputFileInstance->CloseFile(); SET_FUNCTION_RETURN_VALUE(UNDEFINED); } METHOD_RETURN_TYPE InputFileDriver::GetFilePath(const ARGS_TYPE& args) { CREATE_ISOLATE_CONTEXT; CREATE_ESCAPABLE_SCOPE; InputFileDriver* driver = ObjectWrap::Unwrap<InputFileDriver>(args.This()); if(!driver) { THROW_EXCEPTION("no driver created...please create one through Hummus"); SET_FUNCTION_RETURN_VALUE(UNDEFINED); } if(driver->mInputFileInstance && driver->mInputFileInstance->GetInputStream()) SET_FUNCTION_RETURN_VALUE(NEW_STRING(driver->mInputFileInstance->GetFilePath().c_str())); else SET_FUNCTION_RETURN_VALUE(UNDEFINED); } METHOD_RETURN_TYPE InputFileDriver::GetFileSize(const ARGS_TYPE& args) { CREATE_ISOLATE_CONTEXT; CREATE_ESCAPABLE_SCOPE; InputFileDriver* driver = ObjectWrap::Unwrap<InputFileDriver>(args.This()); if(!driver) { THROW_EXCEPTION("no driver created...please create one through Hummus"); SET_FUNCTION_RETURN_VALUE(UNDEFINED); } if(driver->mInputFileInstance && driver->mInputFileInstance->GetInputStream()) SET_FUNCTION_RETURN_VALUE(NEW_NUMBER(driver->mInputFileInstance->GetFileSize())); else SET_FUNCTION_RETURN_VALUE(UNDEFINED); } METHOD_RETURN_TYPE InputFileDriver::GetInputStream(const ARGS_TYPE& args) { CREATE_ISOLATE_CONTEXT; CREATE_ESCAPABLE_SCOPE; InputFileDriver* driver = ObjectWrap::Unwrap<InputFileDriver>(args.This()); if(!driver) { THROW_EXCEPTION("no driver created...please create one through Hummus"); SET_FUNCTION_RETURN_VALUE(UNDEFINED); } if(driver->mInputFileInstance && driver->mInputFileInstance->GetInputStream()) { Handle<Value> result = ByteReaderWithPositionDriver::GetNewInstance(args); ObjectWrap::Unwrap<ByteReaderWithPositionDriver>(result->ToObject())->SetStream(driver->mInputFileInstance->GetInputStream(), false); SET_FUNCTION_RETURN_VALUE(result); } else SET_FUNCTION_RETURN_VALUE(UNDEFINED); }
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_AnimNotifyState_MuteIKLeg_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function AnimNotifyState_MuteIKLeg.AnimNotifyState_MuteIKLeg_C.Received_NotifyEnd struct UAnimNotifyState_MuteIKLeg_C_Received_NotifyEnd_Params { class USkeletalMeshComponent** MeshComp; // (Parm, ZeroConstructor, IsPlainOldData) class UAnimSequenceBase** Animation; // (Parm, ZeroConstructor, IsPlainOldData) bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function AnimNotifyState_MuteIKLeg.AnimNotifyState_MuteIKLeg_C.Received_NotifyBegin struct UAnimNotifyState_MuteIKLeg_C_Received_NotifyBegin_Params { class USkeletalMeshComponent** MeshComp; // (Parm, ZeroConstructor, IsPlainOldData) class UAnimSequenceBase** Animation; // (Parm, ZeroConstructor, IsPlainOldData) float* TotalDuration; // (Parm, ZeroConstructor, IsPlainOldData) bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
/* //@HEADER // ************************************************************************ // // KokkosKernels 0.9: Linear Algebra and Graph Kernels // Copyright 2017 Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact Siva Rajamanickam (srajama@sandia.gov) // // ************************************************************************ //@HEADER */ #define KOKKOSKERNELS_IMPL_COMPILE_LIBRARY true #include "KokkosKernels_config.h" #if defined (KOKKOSKERNELS_INST_DOUBLE) \ && defined (KOKKOSKERNELS_INST_LAYOUTLEFT) \ && defined (KOKKOSKERNELS_INST_EXECSPACE_THREADS) \ && defined (KOKKOSKERNELS_INST_MEMSPACE_HBWSPACE) #include "KokkosBlas1_iamax_spec.hpp" namespace KokkosBlas { namespace Impl { KOKKOSBLAS1_IAMAX_ETI_SPEC_INST(double, Kokkos::LayoutLeft, Kokkos::Threads, Kokkos::Experimental::HBWSpace) } // Impl } // KokkosBlas #endif
/* Description: Pointers homework P7.7 ( QUESTION 3 ) Known bugs: Input must be exactly (number space number space... 'enter') OR youll get bad output */ #include <iostream> #include <string> #include <sstream> using namespace std; double reverse(double *a, int ar_size) { if (ar_size == 0) { return 0.0; } int size = ar_size; double *p_st = a; double *p_end = (a + size - 1); while (p_st<p_end) { double temp = *p_st; *p_st = *p_end; *p_end = temp; p_st++; p_end--; } for (int x = 0; x < size; x++) { if (x < (size - 1)) { cout << a[x] << ", "; } else { cout << a[x] << " \n"; } } } int main() { string moredata = "y"; string nums; unsigned int spacecount = 0; int newsize = 0; do { cout << "Enter a list of numbers: "; getline(cin, nums); for (int i = 0; i < nums.length(); i++) { if (' ' == nums[i]) { spacecount++; } } newsize = spacecount + 1; double *p_dynarr = new double[newsize]; istringstream input(nums); for (int i = 0; i < newsize; i++) { input >> p_dynarr[i]; } reverse(p_dynarr, newsize); p_dynarr = NULL; delete p_dynarr; nums = ""; newsize = 0; spacecount = 0; cout << endl; cout << "Continue? (y/n)"; getline(cin, moredata); cout << endl; } while (moredata == "y"); system("pause"); return 0; }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "kudu/server/webserver.h" #include <cstdlib> #include <functional> #include <iosfwd> #include <memory> #include <string> #include <vector> #include <gflags/gflags.h> #include <glog/logging.h> #include <gtest/gtest.h> #include "kudu/gutil/integral_types.h" #include "kudu/gutil/macros.h" #include "kudu/gutil/stringprintf.h" #include "kudu/gutil/strings/escaping.h" #include "kudu/gutil/strings/substitute.h" #include "kudu/gutil/strings/util.h" #include "kudu/security/test/mini_kdc.h" #include "kudu/security/test/test_certs.h" #include "kudu/security/test/test_pass.h" #include "kudu/server/default_path_handlers.h" #include "kudu/server/webserver_options.h" #include "kudu/util/curl_util.h" #include "kudu/util/env.h" #include "kudu/util/faststring.h" #include "kudu/util/flag_tags.h" #include "kudu/util/logging.h" #include "kudu/util/net/sockaddr.h" #include "kudu/util/slice.h" #include "kudu/util/status.h" #include "kudu/util/test_macros.h" #include "kudu/util/test_util.h" #include "kudu/util/zlib.h" using std::string; using std::vector; using std::unique_ptr; using strings::Substitute; DECLARE_int32(webserver_max_post_length_bytes); DEFINE_bool(test_sensitive_flag, false, "a sensitive flag"); TAG_FLAG(test_sensitive_flag, sensitive); namespace kudu { namespace { void SetSslOptions(WebserverOptions* opts) { string password; CHECK_OK(security::CreateTestSSLCertWithEncryptedKey(GetTestDataDirectory(), &opts->certificate_file, &opts->private_key_file, &password)); opts->private_key_password_cmd = Substitute("echo $0", password); } void SetHTPasswdOptions(WebserverOptions* opts) { CHECK_OK(security::CreateTestHTPasswd(GetTestDataDirectory(), &opts->password_file)); } } // anonymous namespace class WebserverTest : public KuduTest { public: WebserverTest() { static_dir_ = GetTestPath("webserver-docroot"); CHECK_OK(env_->CreateDir(static_dir_)); } void SetUp() override { KuduTest::SetUp(); WebserverOptions opts; opts.port = 0; opts.doc_root = static_dir_; opts.enable_doc_root = enable_doc_root(); if (use_ssl()) SetSslOptions(&opts); if (use_htpasswd()) SetHTPasswdOptions(&opts); MaybeSetupSpnego(&opts); server_.reset(new Webserver(opts)); AddDefaultPathHandlers(server_.get()); ASSERT_OK(server_->Start()); vector<Sockaddr> addrs; ASSERT_OK(server_->GetBoundAddresses(&addrs)); ASSERT_EQ(addrs.size(), 1); ASSERT_TRUE(addrs[0].IsWildcard()); ASSERT_OK(addr_.ParseString("127.0.0.1", addrs[0].port())); url_ = Substitute("http://$0", addr_.ToString()); } void RunTestOptions() { curl_.set_custom_method("OPTIONS"); curl_.set_return_headers(true); ASSERT_OK(curl_.FetchURL(url_, &buf_)); ASSERT_STR_CONTAINS(buf_.ToString(), "Allow: GET, POST, HEAD, OPTIONS, PROPFIND, MKCOL"); } protected: virtual void MaybeSetupSpnego(WebserverOptions* /*opts*/) {} // Overridden by subclasses. virtual bool enable_doc_root() const { return true; } virtual bool use_ssl() const { return false; } virtual bool use_htpasswd() const { return false; } EasyCurl curl_; faststring buf_; unique_ptr<Webserver> server_; Sockaddr addr_; string url_; string static_dir_; }; class SslWebserverTest : public WebserverTest { protected: bool use_ssl() const override { return true; } }; class PasswdWebserverTest : public WebserverTest { protected: bool use_htpasswd() const override { return true; } }; // Send a HTTP request with no username and password. It should reject // the request as the .htpasswd is presented to webserver. TEST_F(PasswdWebserverTest, TestPasswdMissing) { Status status = curl_.FetchURL(url_, &buf_); ASSERT_EQ("Remote error: HTTP 401", status.ToString()); } TEST_F(PasswdWebserverTest, TestPasswdPresent) { ASSERT_OK(curl_.set_auth(CurlAuthType::DIGEST, security::kTestAuthUsername, security::kTestAuthPassword)); ASSERT_OK(curl_.FetchURL(addr_.ToString(), &buf_)); } class SpnegoWebserverTest : public WebserverTest { protected: void MaybeSetupSpnego(WebserverOptions* opts) override { kdc_.reset(new MiniKdc(MiniKdcOptions{})); ASSERT_OK(kdc_->Start()); kdc_->SetKrb5Environment(); string kt_path; ASSERT_OK(kdc_->CreateServiceKeytab("HTTP/127.0.0.1", &kt_path)); CHECK_ERR(setenv("KRB5_KTNAME", kt_path.c_str(), 1)); ASSERT_OK(kdc_->CreateUserPrincipal("alice")); opts->require_spnego = true; opts->spnego_post_authn_callback = [&](const string& spn) { last_authenticated_spn_ = spn; }; } Status DoSpnegoCurl() { curl_.set_auth(CurlAuthType::SPNEGO); if (VLOG_IS_ON(1)) { curl_.set_verbose(true); } return curl_.FetchURL(url_, &buf_); } unique_ptr<MiniKdc> kdc_; const char* const kNotAuthn = "<none>"; string last_authenticated_spn_ = kNotAuthn; // A SPNEGO token manually captured from a client exchange during some prior test run. // This is used as a basis for some fuzz tests. const char* kWellFormedTokenBase64 = "YIICVwYGKwYBBQUCoIICSzCCAkegDTALBgkqhkiG9xIBAgKiggI0BIICMGCCAiwGCSqGSIb3EgECAgEA" "boICGzCCAhegAwIBBaEDAgEOogcDBQAgAAAAo4IBP2GCATswggE3oAMCAQWhDRsLS1JCVEVTVC5DT02i" "HDAaoAMCAQOhEzARGwRIVFRQGwkxMjcuMC4wLjGjggEBMIH+oAMCARGhAwIBA6KB8QSB7pQrIA2cH2l4" "yfHpwhKz2HKYNxoxOw1j++ODByOfN3O/j9/Pp9PwJzQ7hjo5p5nK2OD+2S5YVuS92Ax/LiX8WaYxt9LC" "Hew8TkssFOiDffhag1taEcMG5KksPVxZejs+4NYiLj8dCwow3kShl/fpaLYXFFUgChaM7mVEDfMEIdos" "WB56k/KMJas7kuAkqDy8sEdPpgzbV7tPmkIFecXPKugZFTttkMREe19LcGO2KnOFflLj7s5F4euWzhrG" "v3oZXxDh0G6iyTouSEH+oh/LG97I0umcHrcEit6CjcjVewNhIUaP/Vn2Cu6X0FsF45qkgb4wgbugAwIB" "EaKBswSBsLrv38pBLMZo74lMEWHyOrbwrBG0kHfLHVSnxJJYikOwjAoNUm0/NUJc801TtbQZX/e6nRjS" "4spS2eU1xnPLcVBbtnonkG7xWSDv/Sl/k73oy7rObVWGQAtYkCJdcfWj1mxeojtrOPcKa9ivBiAuKcKl" "EdT2XD6lk161ygu306e7eH8pcuHv+bl9zP42rj85S0c3q0KXRXvsegAFUFk34+AC3fbmKLddEBUoYxms" "f+uj"; }; TEST_F(SpnegoWebserverTest, TestAuthenticated) { ASSERT_OK(kdc_->Kinit("alice")); ASSERT_OK(DoSpnegoCurl()); EXPECT_EQ("alice@KRBTEST.COM", last_authenticated_spn_); EXPECT_STR_CONTAINS(buf_.ToString(), "Kudu"); } TEST_F(SpnegoWebserverTest, TestUnauthenticatedBadKeytab) { ASSERT_OK(kdc_->Kinit("alice")); // Randomize the server's key in the KDC so that the key in the keytab doesn't match the // one for which the client will get a ticket. This is just an easy way to provoke an // error and make sure that our error handling works. ASSERT_OK(kdc_->RandomizePrincipalKey("HTTP/127.0.0.1")); Status s = DoSpnegoCurl(); EXPECT_EQ(s.ToString(), "Remote error: HTTP 401"); EXPECT_EQ(kNotAuthn, last_authenticated_spn_); // The essence here is to get HTTP 401 error status in the server's response. // There might be different messages returned from webserver because of // * different messages from GSSAPI on Linux and macOS (actually depends // on the version of SASL library, see kGssapiPattern in CleanSaslError()) // * different GSSAPI failure paths depending on libkrb5 and libcurl // libraries: with the randomized keytab, the server fails with SASL step // with Status::Incomplete() on macOS. On Linux, the server fails the // SASL step with Status::NotAuthorized(). Instead of finding some // universal way of screwing up the keytab to get the same behavior on // both macOS and Linux, it's easier to rely on the fact that the required // HTTP error code is received and acknowledge for various error messages. ASSERT_STR_MATCHES(buf_.ToString(), "(Unspecified GSS failure|" "GSSAPI Error: Miscellaneous failure|" "Must authenticate with SPNEGO)"); } TEST_F(SpnegoWebserverTest, TestUnauthenticatedNoClientAuth) { Status curl_status = DoSpnegoCurl(); EXPECT_EQ("Remote error: HTTP 401", curl_status.ToString()); EXPECT_EQ("Must authenticate with SPNEGO.", buf_.ToString()); EXPECT_EQ(kNotAuthn, last_authenticated_spn_); } // Test some malformed authorization headers. TEST_F(SpnegoWebserverTest, TestInvalidHeaders) { EXPECT_EQ(curl_.FetchURL(url_, &buf_, { "Authorization: blahblah" }).ToString(), "Remote error: HTTP 500"); EXPECT_STR_CONTAINS(buf_.ToString(), "bad Negotiate header"); EXPECT_EQ(curl_.FetchURL(url_, &buf_, { "Authorization: Negotiate aaa" }).ToString(), "Remote error: HTTP 401"); EXPECT_STR_CONTAINS(buf_.ToString(), "Not authorized"); // Error messages about an invalid token come from the Kerberos library, and // different versions of the library have different messages. ASSERT_STR_MATCHES(buf_.ToString(), "(Invalid token was supplied|A token was invalid)"); } // Test that if no authorization header at all is provided, the response // contains an empty "WWW-Authenticate: Negotiate" header. TEST_F(SpnegoWebserverTest, TestNoAuthHeader) { curl_.set_return_headers(true); ASSERT_EQ(curl_.FetchURL(url_, &buf_).ToString(), "Remote error: HTTP 401"); ASSERT_STR_CONTAINS(buf_.ToString(), "WWW-Authenticate: Negotiate\r\n"); } // Test all single-bit-flips of a well-formed token, to make sure we don't // crash. // // NOTE: the original token is *well-formed* but not *valid* -- i.e. even if unmodified, // it would not produce a successful authentication result, since it is a saved constant // from some previous run of SPNEGO on a different KDC. This test is primarily concerned // with defending against remote buffer overflows during token parsing, etc. TEST_F(SpnegoWebserverTest, TestBitFlippedTokens) { string token; CHECK(strings::Base64Unescape(kWellFormedTokenBase64, &token)); for (int i = 0; i < token.size(); i++) { SCOPED_TRACE(i); for (int bit = 0; bit < 8; bit++) { SCOPED_TRACE(bit); token[i] ^= 1 << bit; string b64_token; strings::Base64Escape(token, &b64_token); string header = Substitute("Authorization: Negotiate $0", b64_token); Status s = curl_.FetchURL(url_, &buf_, { header }); EXPECT_TRUE(s.IsRemoteError()) << s.ToString(); token[i] ^= 1 << bit; } } } // Test all truncations of a well-formed token, to make sure we don't // crash. // // NOTE: see above regarding "well-formed" vs "valid". TEST_F(SpnegoWebserverTest, TestTruncatedTokens) { string token; CHECK(strings::Base64Unescape(kWellFormedTokenBase64, &token)); do { token.resize(token.size() - 1); SCOPED_TRACE(token.size()); string b64_token; strings::Base64Escape(token, &b64_token); string header = Substitute("Authorization: Negotiate $0", b64_token); Status s = curl_.FetchURL(url_, &buf_, { header }); EXPECT_TRUE(s.IsRemoteError()) << s.ToString(); } while (!token.empty()); } // Tests that even if we don't provide adequate authentication information in // an OPTIONS request, the server still honors it. TEST_F(SpnegoWebserverTest, TestAuthNotRequiredForOptions) { NO_FATALS(RunTestOptions()); } TEST_F(WebserverTest, TestIndexPage) { curl_.set_return_headers(true); ASSERT_OK(curl_.FetchURL(url_, &buf_)); // Check expected header. ASSERT_STR_CONTAINS(buf_.ToString(), "X-Frame-Options: DENY"); // Should have expected title. ASSERT_STR_CONTAINS(buf_.ToString(), "Kudu"); // Should have link to default path handlers (e.g memz) ASSERT_STR_CONTAINS(buf_.ToString(), "memz"); } TEST_F(WebserverTest, TestHttpCompression) { std::ostringstream oss; string decoded_str; // Curl with gzip compression enabled. ASSERT_OK(curl_.FetchURL(url_, &buf_, {"Accept-Encoding: deflate, br, gzip"})); // If compressed successfully, we should be able to uncompress. ASSERT_OK(zlib::Uncompress(Slice(buf_.ToString()), &oss)); decoded_str = oss.str(); // Should have expected title. ASSERT_STR_CONTAINS(decoded_str, "Kudu"); // Should have link to default path handlers (e.g memz) ASSERT_STR_CONTAINS(decoded_str, "memz"); // Should have expected header when compressed with headers returned. curl_.set_return_headers(true); ASSERT_OK(curl_.FetchURL(url_, &buf_, {"Accept-Encoding: deflate, megaturbogzip, gzip , br"})); ASSERT_STR_CONTAINS(buf_.ToString(), "Content-Encoding: gzip"); // Curl with compression disabled. curl_.set_return_headers(true); ASSERT_OK(curl_.FetchURL(url_, &buf_)); // Check expected header. ASSERT_STR_CONTAINS(buf_.ToString(), "Content-Type:"); // Check unexpected header. ASSERT_STR_NOT_CONTAINS(buf_.ToString(), "Content-Encoding: gzip"); // Should have expected title. ASSERT_STR_CONTAINS(buf_.ToString(), "Kudu"); // Should have link to default path handlers (e.g memz) ASSERT_STR_CONTAINS(buf_.ToString(), "memz"); // Curl with compression enabled but not accepted by Kudu. curl_.set_return_headers(true); ASSERT_OK(curl_.FetchURL(url_, &buf_, {"Accept-Encoding: megaturbogzip, deflate, xz"})); // Check expected header. ASSERT_STR_CONTAINS(buf_.ToString(), "HTTP/1.1 200 OK"); // Check unexpected header. ASSERT_STR_NOT_CONTAINS(buf_.ToString(), "Content-Encoding: gzip"); // Should have expected title. ASSERT_STR_CONTAINS(buf_.ToString(), "Kudu"); // Should have link to default path handlers (e.g memz) ASSERT_STR_CONTAINS(buf_.ToString(), "memz"); } TEST_F(SslWebserverTest, TestSSL) { // We use a self-signed cert, so we need to disable cert verification in curl. curl_.set_verify_peer(false); ASSERT_OK(curl_.FetchURL(Substitute("https://$0/", addr_.ToString()), &buf_)); // Should have expected title. ASSERT_STR_CONTAINS(buf_.ToString(), "Kudu"); } TEST_F(WebserverTest, TestDefaultPaths) { // Test memz ASSERT_OK(curl_.FetchURL(Substitute("$0/memz?raw=1", url_), &buf_)); #ifdef TCMALLOC_ENABLED ASSERT_STR_CONTAINS(buf_.ToString(), "Bytes in use by application"); #else ASSERT_STR_CONTAINS(buf_.ToString(), "not available unless tcmalloc is enabled"); #endif // Test varz -- check for one of the built-in gflags flags. ASSERT_OK(curl_.FetchURL(Substitute("$0/varz?raw=1", url_), &buf_)); ASSERT_STR_CONTAINS(buf_.ToString(), "--v="); } TEST_F(WebserverTest, TestRedactFlagsDump) { kudu::g_should_redact = kudu::RedactContext::ALL; // Test varz -- check for the sensitive flag is redacted and HTML-escaped. ASSERT_OK(curl_.FetchURL(Substitute("$0/varz", url_), &buf_)); ASSERT_STR_CONTAINS(buf_.ToString(), "--test_sensitive_flag=&lt;redacted&gt;"); // Test varz?raw -- check for the sensitive flag is redacted and not HTML-escaped. ASSERT_OK(curl_.FetchURL(Substitute("$0/varz?raw=1", url_), &buf_)); ASSERT_STR_CONTAINS(buf_.ToString(), Substitute("--test_sensitive_flag=$0", kRedactionMessage)); } // Used in symbolization test below. void SomeMethodForSymbolTest1() {} // Used in symbolization test below. void SomeMethodForSymbolTest2() {} TEST_F(WebserverTest, TestPprofPaths) { // Test /pprof/cmdline GET ASSERT_OK(curl_.FetchURL(Substitute("$0/pprof/cmdline", url_), &buf_)); ASSERT_STR_CONTAINS(buf_.ToString(), "webserver-test"); ASSERT_TRUE(!HasSuffixString(buf_.ToString(), string("\x00", 1))) << "should not have trailing NULL: " << Slice(buf_).ToDebugString(); // Test /pprof/symbol GET ASSERT_OK(curl_.FetchURL(Substitute("$0/pprof/symbol", url_), &buf_)); ASSERT_EQ(buf_.ToString(), "num_symbols: 1"); // Test /pprof/symbol POST { // Formulate a request with some valid symbol addresses. string req = StringPrintf("%p+%p", &SomeMethodForSymbolTest1, &SomeMethodForSymbolTest2); SCOPED_TRACE(req); ASSERT_OK(curl_.PostToURL(Substitute("$0/pprof/symbol", url_), req, &buf_)); ASSERT_EQ(buf_.ToString(), StringPrintf("%p\tkudu::SomeMethodForSymbolTest1()\n" "%p\tkudu::SomeMethodForSymbolTest2()\n", &SomeMethodForSymbolTest1, &SomeMethodForSymbolTest2)); } } // Send a POST request with too much data. It should reject // the request with the correct HTTP error code. TEST_F(WebserverTest, TestPostTooBig) { FLAGS_webserver_max_post_length_bytes = 10; string req(10000, 'c'); Status s = curl_.PostToURL(Substitute("$0/pprof/symbol", url_), req, &buf_); ASSERT_EQ("Remote error: HTTP 413", s.ToString()); } // Test that static files are served and that directory listings are // disabled. TEST_F(WebserverTest, TestStaticFiles) { // Fetch a non-existent static file. Status s = curl_.FetchURL(Substitute("$0/foo.txt", url_), &buf_); ASSERT_EQ("Remote error: HTTP 404", s.ToString()); // Create the file and fetch again. This time it should succeed. ASSERT_OK(WriteStringToFile(env_, "hello world", Substitute("$0/foo.txt", static_dir_))); ASSERT_OK(curl_.FetchURL(Substitute("$0/foo.txt", url_), &buf_)); ASSERT_EQ("hello world", buf_.ToString()); // Create a directory and ensure that subdirectory listing is disabled. ASSERT_OK(env_->CreateDir(Substitute("$0/dir", static_dir_))); s = curl_.FetchURL(Substitute("$0/dir/", url_), &buf_); ASSERT_EQ("Remote error: HTTP 403", s.ToString()); } class DisabledDocRootWebserverTest : public WebserverTest { protected: bool enable_doc_root() const override { return false; } }; TEST_F(DisabledDocRootWebserverTest, TestHandlerNotFound) { Status s = curl_.FetchURL(Substitute("$0/foo", url_), &buf_); ASSERT_EQ("Remote error: HTTP 404", s.ToString()); ASSERT_STR_CONTAINS(buf_.ToString(), "No handler for URI /foo"); } // Test that HTTP OPTIONS requests are permitted. TEST_F(WebserverTest, TestHttpOptions) { NO_FATALS(RunTestOptions()); } // Test that we're able to reuse connections for subsequent fetches. TEST_F(WebserverTest, TestConnectionReuse) { ASSERT_OK(curl_.FetchURL(url_, &buf_)); ASSERT_EQ(1, curl_.num_connects()); ASSERT_OK(curl_.FetchURL(url_, &buf_)); ASSERT_EQ(0, curl_.num_connects()); } class WebserverAdvertisedAddressesTest : public KuduTest { public: void SetUp() override { KuduTest::SetUp(); WebserverOptions opts; opts.port = 0; string iface = use_webserver_interface(); int32 port = use_webserver_port(); string advertised = use_advertised_addresses(); if (!iface.empty()) { opts.bind_interface = iface; } if (port != 0) { opts.port = port; } if (!advertised.empty()) { opts.webserver_advertised_addresses = advertised; } server_.reset(new Webserver(opts)); ASSERT_OK(server_->Start()); } protected: // Overridden by subclasses. virtual string use_webserver_interface() const { return ""; } virtual int32 use_webserver_port() const { return 0; } virtual string use_advertised_addresses() const { return ""; } void GetAddresses(vector<Sockaddr>* bound_addrs, vector<Sockaddr>* advertised_addrs) { ASSERT_OK(server_->GetBoundAddresses(bound_addrs)); ASSERT_OK(server_->GetAdvertisedAddresses(advertised_addrs)); } unique_ptr<Webserver> server_; }; class AdvertisedOnlyWebserverTest : public WebserverAdvertisedAddressesTest { protected: string use_advertised_addresses() const override { return "1.2.3.4:1234"; } }; class BoundOnlyWebserverTest : public WebserverAdvertisedAddressesTest { protected: string use_webserver_interface() const override { return "127.0.0.1"; } int32 use_webserver_port() const override { return 9999; } }; class BothBoundAndAdvertisedWebserverTest : public WebserverAdvertisedAddressesTest { protected: string use_advertised_addresses() const override { return "1.2.3.4:1234"; } string use_webserver_interface() const override { return "127.0.0.1"; } int32 use_webserver_port() const override { return 9999; } }; TEST_F(AdvertisedOnlyWebserverTest, OnlyAdvertisedAddresses) { vector<Sockaddr> bound_addrs, advertised_addrs; NO_FATALS(GetAddresses(&bound_addrs, &advertised_addrs)); ASSERT_EQ(1, advertised_addrs.size()); ASSERT_EQ(1, bound_addrs.size()); ASSERT_EQ("1.2.3.4", advertised_addrs[0].host()); ASSERT_EQ(1234, advertised_addrs[0].port()); ASSERT_NE(9999, bound_addrs[0].port()); } TEST_F(BoundOnlyWebserverTest, OnlyBoundAddresses) { vector<Sockaddr> bound_addrs, advertised_addrs; NO_FATALS(GetAddresses(&bound_addrs, &advertised_addrs)); ASSERT_EQ(1, advertised_addrs.size()); ASSERT_EQ(1, bound_addrs.size()); ASSERT_EQ("127.0.0.1", advertised_addrs[0].host()); ASSERT_EQ(9999, advertised_addrs[0].port()); ASSERT_EQ("127.0.0.1", bound_addrs[0].host()); ASSERT_EQ(9999, bound_addrs[0].port()); } TEST_F(BothBoundAndAdvertisedWebserverTest, BothBoundAndAdvertisedAddresses) { vector<Sockaddr> bound_addrs, advertised_addrs; NO_FATALS(GetAddresses(&bound_addrs, &advertised_addrs)); ASSERT_EQ(1, advertised_addrs.size()); ASSERT_EQ(1, bound_addrs.size()); ASSERT_EQ("1.2.3.4", advertised_addrs[0].host()); ASSERT_EQ(1234, advertised_addrs[0].port()); ASSERT_EQ("127.0.0.1", bound_addrs[0].host()); ASSERT_EQ(9999, bound_addrs[0].port()); } // Various tests for failed webserver startup cases. class WebserverNegativeTests : public KuduTest { protected: // Tries to start the webserver, expecting it to fail. // 'func' is used to set webserver options before starting it. template<class OptsFunc> void ExpectFailedStartup(const OptsFunc& func) { WebserverOptions opts; opts.port = 0; func(&opts); Webserver server(opts); Status s = server.Start(); ASSERT_FALSE(s.ok()) << s.ToString(); } }; TEST_F(WebserverNegativeTests, BadCertFile) { ExpectFailedStartup([](WebserverOptions* opts) { SetSslOptions(opts); opts->certificate_file = "/dev/null"; }); } TEST_F(WebserverNegativeTests, BadKeyFile) { ExpectFailedStartup([](WebserverOptions* opts) { SetSslOptions(opts); opts->private_key_file = "/dev/null"; }); } TEST_F(WebserverNegativeTests, WrongPassword) { ExpectFailedStartup([](WebserverOptions* opts) { SetSslOptions(opts); opts->private_key_password_cmd = "echo wrong_pass"; }); } TEST_F(WebserverNegativeTests, BadPasswordCommand) { ExpectFailedStartup([](WebserverOptions* opts) { SetSslOptions(opts); opts->private_key_password_cmd = "/bin/false"; }); } TEST_F(WebserverNegativeTests, BadAdvertisedAddresses) { ExpectFailedStartup([](WebserverOptions* opts) { opts->webserver_advertised_addresses = ";;;;;"; }); } TEST_F(WebserverNegativeTests, BadAdvertisedAddressesZeroPort) { ExpectFailedStartup([](WebserverOptions* opts) { opts->webserver_advertised_addresses = "localhost:0"; }); } TEST_F(WebserverNegativeTests, SpnegoWithoutKeytab) { ExpectFailedStartup([](WebserverOptions* opts) { opts->require_spnego = true; }); } } // namespace kudu
// // Copyright (c) 2013-2017 Vinnie Falco (vinnie dot falco at gmail dot com) // // 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) // // Test that header file is self-contained. #include <beast/http/string_view_body.hpp> #include <beast/core/ostream.hpp> #include <beast/core/static_buffer.hpp> #include <beast/http/message.hpp> #include <beast/http/write.hpp> #include <beast/http/type_traits.hpp> #include <beast/unit_test/suite.hpp> namespace beast { namespace http { class string_view_body_test : public beast::unit_test::suite { public: void run() override { static_assert(is_body_reader<string_view_body>::value, ""); static_assert(! is_body_writer<string_view_body>::value, ""); request<string_view_body> req{"Hello, world!"}; req.version = 11; req.method(verb::post); req.target("/"); req.prepare_payload(); static_buffer_n<512> b; ostream(b) << req; string_view const s{ boost::asio::buffer_cast<char const*>(*b.data().begin()), boost::asio::buffer_size(*b.data().begin())}; BEAST_EXPECT(s == "POST / HTTP/1.1\r\n" "Content-Length: 13\r\n" "\r\n" "Hello, world!"); } }; BEAST_DEFINE_TESTSUITE(string_view_body,http,beast); } // http } // beast
/* * Copyright (c) 2020-2021 Samsung Electronics Co., Ltd. All rights reserved. * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <thorvg.h> #include <emscripten/bind.h> using namespace emscripten; using namespace std; using namespace tvg; string defaultData("<svg height=\"1000\" viewBox=\"0 0 1000 1000\" width=\"1000\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M.10681413.09784845 1000.0527.01592069V1000.0851L.06005738 999.9983Z\" fill=\"#09bbf1\" stroke-width=\"3.910218\"/><g fill=\"#252f35\"><g stroke-width=\"3.864492\"><path d=\"M256.61221 100.51736H752.8963V386.99554H256.61221Z\"/><path d=\"M201.875 100.51736H238.366478V386.99554H201.875Z\"/><path d=\"M771.14203 100.51736H807.633508V386.99554H771.14203Z\"/></g><path d=\"M420.82388 380H588.68467V422.805317H420.82388Z\" stroke-width=\"3.227\"/><path d=\"m420.82403 440.7101v63.94623l167.86079 25.5782V440.7101Z\"/><path d=\"M420.82403 523.07258V673.47362L588.68482 612.59701V548.13942Z\"/></g><g fill=\"#222f35\"><path d=\"M420.82403 691.37851 588.68482 630.5019 589 834H421Z\"/><path d=\"m420.82403 852.52249h167.86079v28.64782H420.82403v-28.64782 0 0\"/><path d=\"m439.06977 879.17031c0 0-14.90282 8.49429-18.24574 15.8161-4.3792 9.59153 0 31.63185 0 31.63185h167.86079c0 0 4.3792-22.04032 0-31.63185-3.34292-7.32181-18.24574-15.8161-18.24574-15.8161z\"/></g><g fill=\"#09bbf1\"><path d=\"m280 140h15v55l8 10 8-10v-55h15v60l-23 25-23-25z\"/><path d=\"m335 140v80h45v-50h-25v10h10v30h-15v-57h18v-13z\"/></g></svg>"); class __attribute__((visibility("default"))) ThorvgWasm { public: static unique_ptr<ThorvgWasm> create() { return unique_ptr<ThorvgWasm>(new ThorvgWasm()); } string getError() { return mErrorMsg; } string getDefaultData() { return defaultData; } bool load(string data, int width, int height) { mErrorMsg = "None"; if (!mSwCanvas) { mErrorMsg = "Canvas is NULL"; return false; } mPicture = Picture::gen().release(); if (!mPicture) { mErrorMsg = "Picture get failed"; return false; } mSwCanvas->clear(); if (data.empty()) data = defaultData; const char *cdata = data.c_str(); if (mPicture->load(cdata, strlen(cdata)) != Result::Success) { /* mPicture is not handled as unique_ptr yet, so delete here */ delete(mPicture); mPicture = nullptr; mErrorMsg = "Load failed"; return false; } /* need to reset size to calculate scale in Picture.size internally before calling updateSize */ mWidth = 0; mHeight = 0; updateSize(width, height); if (mSwCanvas->push(unique_ptr<Picture>(mPicture)) != Result::Success) { mErrorMsg = "Push failed"; return false; } return true; } void update(int width, int height) { mErrorMsg = "None"; if (!mSwCanvas) { mErrorMsg = "Canvas is NULL"; return; } if (!mPicture) { mErrorMsg = "Picture is NULL"; return; } if (mWidth == width && mHeight == height) { return; } updateSize(width, height); if (mSwCanvas->update(mPicture) != Result::Success) { mErrorMsg = "Update failed"; return; } return; } val render() { mErrorMsg = "None"; if (!mSwCanvas) { mErrorMsg = "Canvas is NULL"; return val(typed_memory_view<uint8_t>(0, nullptr)); } if (mSwCanvas->draw() != Result::Success) { mErrorMsg = "Draw failed"; return val(typed_memory_view<uint8_t>(0, nullptr)); } mSwCanvas->sync(); return val(typed_memory_view(mWidth * mHeight * 4, mBuffer.get())); } private: explicit ThorvgWasm() { mErrorMsg = "None"; Initializer::init(CanvasEngine::Sw, 0); mSwCanvas = SwCanvas::gen(); if (!mSwCanvas) { mErrorMsg = "Canvas get failed"; return; } } void updateSize(int width, int height) { if (!mSwCanvas) return; if (mWidth == width && mHeight == height) return; mWidth = width; mHeight = height; mBuffer = make_unique<uint8_t[]>(mWidth * mHeight * 4); mSwCanvas->target((uint32_t *)mBuffer.get(), mWidth, mWidth, mHeight, SwCanvas::ABGR8888); if (mPicture) mPicture->size(width, height); } private: string mErrorMsg; unique_ptr< SwCanvas > mSwCanvas = nullptr; Picture* mPicture = nullptr; unique_ptr<uint8_t[]> mBuffer = nullptr; uint32_t mWidth{0}; uint32_t mHeight{0}; }; // Binding code EMSCRIPTEN_BINDINGS(thorvg_bindings) { class_<ThorvgWasm>("ThorvgWasm") .constructor(&ThorvgWasm::create) .function("getError", &ThorvgWasm::getError, allow_raw_pointers()) .function("getDefaultData", &ThorvgWasm::getDefaultData, allow_raw_pointers()) .function("load", &ThorvgWasm::load) .function("update", &ThorvgWasm::update) .function("render", &ThorvgWasm::render); }
/* Copyright (c) 2018, MIPI Alliance, 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 the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ /* * Contributors: * Norbert Schulz (Intel Corporation) - Initial API and implementation */ #include "gtest/gtest.h" int main(int argc, char * argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
//***************************************************************************** // Copyright 2017-2020 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include <memory> #include <sstream> #include <string> #include <vector> #include "gtest/gtest.h" #include "ngraph/graph_util.hpp" #include "ngraph/ngraph.hpp" #include "ngraph/pass/manager.hpp" #include "util/test_tools.hpp" using namespace ngraph; using namespace std; TEST(pass_manager, add) { pass::Manager pass_manager; auto graph = make_test_graph(); size_t node_count = 0; traverse_nodes(graph, [&](shared_ptr<Node> /* node */) { node_count++; }); pass_manager.run_passes(graph); auto sorted = graph->get_ordered_ops(); EXPECT_EQ(node_count, sorted.size()); EXPECT_TRUE(validate_list(sorted)); } namespace { class DummyPass : public pass::FunctionPass { public: DummyPass() : FunctionPass() { } bool run_on_function(std::shared_ptr<ngraph::Function> /* f */) override { return false; } }; }
/* * worker.actor.cpp * * This source file is part of the FoundationDB open source project * * Copyright 2013-2018 Apple Inc. and the FoundationDB project authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 <tuple> #include <boost/lexical_cast.hpp> #include "fdbrpc/Locality.h" #include "fdbclient/GlobalConfig.actor.h" #include "fdbclient/ProcessInterface.h" #include "fdbclient/StorageServerInterface.h" #include "fdbserver/Knobs.h" #include "flow/ActorCollection.h" #include "flow/ProtocolVersion.h" #include "flow/SystemMonitor.h" #include "flow/TDMetric.actor.h" #include "fdbrpc/simulator.h" #include "fdbclient/NativeAPI.actor.h" #include "fdbserver/MetricLogger.actor.h" #include "fdbserver/BackupInterface.h" #include "fdbserver/RoleLineage.actor.h" #include "fdbserver/WorkerInterface.actor.h" #include "fdbserver/IKeyValueStore.h" #include "fdbserver/WaitFailure.h" #include "fdbserver/TesterInterface.actor.h" // for poisson() #include "fdbserver/IDiskQueue.h" #include "fdbclient/DatabaseContext.h" #include "fdbserver/DataDistributorInterface.h" #include "fdbserver/BlobManagerInterface.h" #include "fdbserver/ServerDBInfo.h" #include "fdbserver/FDBExecHelper.actor.h" #include "fdbserver/CoordinationInterface.h" #include "fdbserver/LocalConfiguration.h" #include "fdbclient/MonitorLeader.h" #include "fdbclient/ClientWorkerInterface.h" #include "flow/Profiler.h" #include "flow/ThreadHelper.actor.h" #include "flow/Trace.h" #include "flow/flow.h" #include "flow/network.h" #ifdef __linux__ #include <fcntl.h> #include <stdio.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #endif #if defined(__linux__) || defined(__FreeBSD__) #ifdef USE_GPERFTOOLS #include "gperftools/profiler.h" #include "gperftools/heap-profiler.h" #endif #include <unistd.h> #include <thread> #include <execinfo.h> #endif #include "flow/actorcompiler.h" // This must be the last #include. #if CENABLED(0, NOT_IN_CLEAN) extern IKeyValueStore* keyValueStoreCompressTestData(IKeyValueStore* store); #define KV_STORE(filename, uid) keyValueStoreCompressTestData(keyValueStoreSQLite(filename, uid)) #elif CENABLED(0, NOT_IN_CLEAN) #define KV_STORE(filename, uid) keyValueStoreSQLite(filename, uid) #else #define KV_STORE(filename, uid) keyValueStoreMemory(filename, uid) #endif namespace { RoleLineageCollector roleLineageCollector; } ACTOR Future<std::vector<Endpoint>> tryDBInfoBroadcast(RequestStream<UpdateServerDBInfoRequest> stream, UpdateServerDBInfoRequest req) { ErrorOr<std::vector<Endpoint>> rep = wait(stream.getReplyUnlessFailedFor(req, SERVER_KNOBS->DBINFO_FAILED_DELAY, 0)); if (rep.present()) { return rep.get(); } req.broadcastInfo.push_back(stream.getEndpoint()); return req.broadcastInfo; } ACTOR Future<std::vector<Endpoint>> broadcastDBInfoRequest(UpdateServerDBInfoRequest req, int sendAmount, Optional<Endpoint> sender, bool sendReply) { state std::vector<Future<std::vector<Endpoint>>> replies; state ReplyPromise<std::vector<Endpoint>> reply = req.reply; resetReply(req); int currentStream = 0; std::vector<Endpoint> broadcastEndpoints = req.broadcastInfo; for (int i = 0; i < sendAmount && currentStream < broadcastEndpoints.size(); i++) { std::vector<Endpoint> endpoints; RequestStream<UpdateServerDBInfoRequest> cur(broadcastEndpoints[currentStream++]); while (currentStream < broadcastEndpoints.size() * (i + 1) / sendAmount) { endpoints.push_back(broadcastEndpoints[currentStream++]); } req.broadcastInfo = endpoints; replies.push_back(tryDBInfoBroadcast(cur, req)); resetReply(req); } wait(waitForAll(replies)); std::vector<Endpoint> notUpdated; if (sender.present()) { notUpdated.push_back(sender.get()); } for (auto& it : replies) { notUpdated.insert(notUpdated.end(), it.get().begin(), it.get().end()); } if (sendReply) { reply.send(notUpdated); } return notUpdated; } ACTOR static Future<Void> extractClientInfo(Reference<AsyncVar<ServerDBInfo> const> db, Reference<AsyncVar<ClientDBInfo>> info) { state std::vector<UID> lastCommitProxyUIDs; state std::vector<CommitProxyInterface> lastCommitProxies; state std::vector<UID> lastGrvProxyUIDs; state std::vector<GrvProxyInterface> lastGrvProxies; loop { ClientDBInfo ni = db->get().client; shrinkProxyList(ni, lastCommitProxyUIDs, lastCommitProxies, lastGrvProxyUIDs, lastGrvProxies); info->set(ni); wait(db->onChange()); } } Database openDBOnServer(Reference<AsyncVar<ServerDBInfo> const> const& db, TaskPriority taskID, LockAware lockAware, EnableLocalityLoadBalance enableLocalityLoadBalance) { auto info = makeReference<AsyncVar<ClientDBInfo>>(); auto cx = DatabaseContext::create(info, extractClientInfo(db, info), enableLocalityLoadBalance ? db->get().myLocality : LocalityData(), enableLocalityLoadBalance, taskID, lockAware); GlobalConfig::create(cx, db, std::addressof(db->get().client)); GlobalConfig::globalConfig().trigger(samplingFrequency, samplingProfilerUpdateFrequency); GlobalConfig::globalConfig().trigger(samplingWindow, samplingProfilerUpdateWindow); return cx; } struct ErrorInfo { Error error; const Role& role; UID id; ErrorInfo(Error e, const Role& role, UID id) : error(e), role(role), id(id) {} template <class Ar> void serialize(Ar&) { ASSERT(false); } }; Error checkIOTimeout(Error const& e) { // Convert all_errors to io_timeout if global timeout bool was set bool timeoutOccurred = (bool)g_network->global(INetwork::enASIOTimedOut); // In simulation, have to check global timed out flag for both this process and the machine process on which IO is // done if (g_network->isSimulated() && !timeoutOccurred) timeoutOccurred = g_pSimulator->getCurrentProcess()->machine->machineProcess->global(INetwork::enASIOTimedOut); if (timeoutOccurred) { TEST(true); // Timeout occurred Error timeout = io_timeout(); // Preserve injectedness of error if (e.isInjectedFault()) timeout = timeout.asInjectedFault(); return timeout; } return e; } ACTOR Future<Void> forwardError(PromiseStream<ErrorInfo> errors, Role role, UID id, Future<Void> process) { try { wait(process); errors.send(ErrorInfo(success(), role, id)); return Void(); } catch (Error& e) { errors.send(ErrorInfo(e, role, id)); return Void(); } } ACTOR Future<Void> handleIOErrors(Future<Void> actor, IClosable* store, UID id, Future<Void> onClosed = Void()) { state Future<ErrorOr<Void>> storeError = actor.isReady() ? Never() : errorOr(store->getError()); choose { when(state ErrorOr<Void> e = wait(errorOr(actor))) { if (e.isError() && e.getError().code() == error_code_please_reboot) { // no need to wait. } else { wait(onClosed); } if (e.isError() && e.getError().code() == error_code_broken_promise && !storeError.isReady()) { wait(delay(0.00001 + FLOW_KNOBS->MAX_BUGGIFIED_DELAY)); } if (storeError.isReady()) throw storeError.get().getError(); if (e.isError()) throw e.getError(); else return e.get(); } when(ErrorOr<Void> e = wait(storeError)) { TraceEvent("WorkerTerminatingByIOError", id).error(e.getError(), true); actor.cancel(); // file_not_found can occur due to attempting to open a partially deleted DiskQueue, which should not be // reported SevError. if (e.getError().code() == error_code_file_not_found) { TEST(true); // Worker terminated with file_not_found error return Void(); } throw e.getError(); } } } ACTOR Future<Void> workerHandleErrors(FutureStream<ErrorInfo> errors) { loop choose { when(ErrorInfo _err = waitNext(errors)) { ErrorInfo err = _err; bool ok = err.error.code() == error_code_success || err.error.code() == error_code_please_reboot || err.error.code() == error_code_actor_cancelled || err.error.code() == error_code_coordinators_changed || // The worker server was cancelled err.error.code() == error_code_shutdown_in_progress; if (!ok) { err.error = checkIOTimeout(err.error); // Possibly convert error to io_timeout } endRole(err.role, err.id, "Error", ok, err.error); if (err.error.code() == error_code_please_reboot || (err.role == Role::SHARED_TRANSACTION_LOG && (err.error.code() == error_code_io_error || err.error.code() == error_code_io_timeout))) throw err.error; } } } // Improve simulation code coverage by sometimes deferring the destruction of workerInterface (and therefore "endpoint // not found" responses to clients // for an extra second, so that clients are more likely to see broken_promise errors ACTOR template <class T> Future<Void> zombie(T workerInterface, Future<Void> worker) { try { wait(worker); if (BUGGIFY) wait(delay(1.0)); return Void(); } catch (Error& e) { throw; } } ACTOR Future<Void> loadedPonger(FutureStream<LoadedPingRequest> pings) { state Standalone<StringRef> payloadBack(std::string(20480, '.')); loop { LoadedPingRequest pong = waitNext(pings); LoadedReply rep; rep.payload = (pong.loadReply ? payloadBack : LiteralStringRef("")); rep.id = pong.id; pong.reply.send(rep); } } StringRef fileStoragePrefix = LiteralStringRef("storage-"); StringRef testingStoragePrefix = LiteralStringRef("testingstorage-"); StringRef fileLogDataPrefix = LiteralStringRef("log-"); StringRef fileVersionedLogDataPrefix = LiteralStringRef("log2-"); StringRef fileLogQueuePrefix = LiteralStringRef("logqueue-"); StringRef tlogQueueExtension = LiteralStringRef("fdq"); enum class FilesystemCheck { FILES_ONLY, DIRECTORIES_ONLY, FILES_AND_DIRECTORIES, }; struct KeyValueStoreSuffix { KeyValueStoreType type; std::string suffix; FilesystemCheck check; }; KeyValueStoreSuffix bTreeV1Suffix = { KeyValueStoreType::SSD_BTREE_V1, ".fdb", FilesystemCheck::FILES_ONLY }; KeyValueStoreSuffix bTreeV2Suffix = { KeyValueStoreType::SSD_BTREE_V2, ".sqlite", FilesystemCheck::FILES_ONLY }; KeyValueStoreSuffix memorySuffix = { KeyValueStoreType::MEMORY, "-0.fdq", FilesystemCheck::FILES_ONLY }; KeyValueStoreSuffix memoryRTSuffix = { KeyValueStoreType::MEMORY_RADIXTREE, "-0.fdr", FilesystemCheck::FILES_ONLY }; KeyValueStoreSuffix redwoodSuffix = { KeyValueStoreType::SSD_REDWOOD_V1, ".redwood-v1", FilesystemCheck::FILES_ONLY }; KeyValueStoreSuffix rocksdbSuffix = { KeyValueStoreType::SSD_ROCKSDB_V1, ".rocksdb", FilesystemCheck::DIRECTORIES_ONLY }; std::string validationFilename = "_validate"; std::string filenameFromSample(KeyValueStoreType storeType, std::string folder, std::string sample_filename) { if (storeType == KeyValueStoreType::SSD_BTREE_V1) return joinPath(folder, sample_filename); else if (storeType == KeyValueStoreType::SSD_BTREE_V2) return joinPath(folder, sample_filename); else if (storeType == KeyValueStoreType::MEMORY || storeType == KeyValueStoreType::MEMORY_RADIXTREE) return joinPath(folder, sample_filename.substr(0, sample_filename.size() - 5)); else if (storeType == KeyValueStoreType::SSD_REDWOOD_V1) return joinPath(folder, sample_filename); else if (storeType == KeyValueStoreType::SSD_ROCKSDB_V1) return joinPath(folder, sample_filename); UNREACHABLE(); } std::string filenameFromId(KeyValueStoreType storeType, std::string folder, std::string prefix, UID id) { if (storeType == KeyValueStoreType::SSD_BTREE_V1) return joinPath(folder, prefix + id.toString() + ".fdb"); else if (storeType == KeyValueStoreType::SSD_BTREE_V2) return joinPath(folder, prefix + id.toString() + ".sqlite"); else if (storeType == KeyValueStoreType::MEMORY || storeType == KeyValueStoreType::MEMORY_RADIXTREE) return joinPath(folder, prefix + id.toString() + "-"); else if (storeType == KeyValueStoreType::SSD_REDWOOD_V1) return joinPath(folder, prefix + id.toString() + ".redwood-v1"); else if (storeType == KeyValueStoreType::SSD_ROCKSDB_V1) return joinPath(folder, prefix + id.toString() + ".rocksdb"); TraceEvent(SevError, "UnknownStoreType").detail("StoreType", storeType.toString()); UNREACHABLE(); } struct TLogOptions { TLogOptions() = default; TLogOptions(TLogVersion v, TLogSpillType s) : version(v), spillType(s) {} TLogVersion version = TLogVersion::DEFAULT; TLogSpillType spillType = TLogSpillType::UNSET; static ErrorOr<TLogOptions> FromStringRef(StringRef s) { TLogOptions options; for (StringRef key = s.eat("_"), value = s.eat("_"); s.size() != 0 || key.size(); key = s.eat("_"), value = s.eat("_")) { if (key.size() != 0 && value.size() == 0) return default_error_or(); if (key == LiteralStringRef("V")) { ErrorOr<TLogVersion> tLogVersion = TLogVersion::FromStringRef(value); if (tLogVersion.isError()) return tLogVersion.getError(); options.version = tLogVersion.get(); } else if (key == LiteralStringRef("LS")) { ErrorOr<TLogSpillType> tLogSpillType = TLogSpillType::FromStringRef(value); if (tLogSpillType.isError()) return tLogSpillType.getError(); options.spillType = tLogSpillType.get(); } else { return default_error_or(); } } return options; } bool operator==(const TLogOptions& o) { return version == o.version && (spillType == o.spillType || version >= TLogVersion::V5); } std::string toPrefix() const { std::string toReturn = ""; switch (version) { case TLogVersion::UNSET: ASSERT(false); case TLogVersion::V2: return ""; case TLogVersion::V3: case TLogVersion::V4: toReturn = "V_" + boost::lexical_cast<std::string>(version) + "_LS_" + boost::lexical_cast<std::string>(spillType); break; case TLogVersion::V5: case TLogVersion::V6: toReturn = "V_" + boost::lexical_cast<std::string>(version); break; } ASSERT_WE_THINK(FromStringRef(toReturn).get() == *this); return toReturn + "-"; } }; TLogFn tLogFnForOptions(TLogOptions options) { switch (options.version) { case TLogVersion::V2: if (options.spillType == TLogSpillType::REFERENCE) ASSERT(false); return oldTLog_6_0::tLog; case TLogVersion::V3: case TLogVersion::V4: if (options.spillType == TLogSpillType::VALUE) return oldTLog_6_0::tLog; else return oldTLog_6_2::tLog; case TLogVersion::V5: case TLogVersion::V6: return tLog; default: ASSERT(false); } return tLog; } struct DiskStore { enum COMPONENT { TLogData, Storage, UNSET }; UID storeID = UID(); std::string filename = ""; // For KVStoreMemory just the base filename to be passed to IDiskQueue COMPONENT storedComponent = UNSET; KeyValueStoreType storeType = KeyValueStoreType::END; TLogOptions tLogOptions; }; std::vector<DiskStore> getDiskStores(std::string folder, std::string suffix, KeyValueStoreType type, FilesystemCheck check) { std::vector<DiskStore> result; std::vector<std::string> files; if (check == FilesystemCheck::FILES_ONLY || check == FilesystemCheck::FILES_AND_DIRECTORIES) { files = platform::listFiles(folder, suffix); } if (check == FilesystemCheck::DIRECTORIES_ONLY || check == FilesystemCheck::FILES_AND_DIRECTORIES) { for (const auto& directory : platform::listDirectories(folder)) { if (StringRef(directory).endsWith(suffix)) { files.push_back(directory); } } } for (int idx = 0; idx < files.size(); idx++) { DiskStore store; store.storeType = type; StringRef filename = StringRef(files[idx]); Standalone<StringRef> prefix; if (filename.startsWith(fileStoragePrefix)) { store.storedComponent = DiskStore::Storage; prefix = fileStoragePrefix; } else if (filename.startsWith(testingStoragePrefix)) { store.storedComponent = DiskStore::Storage; prefix = testingStoragePrefix; } else if (filename.startsWith(fileVersionedLogDataPrefix)) { store.storedComponent = DiskStore::TLogData; // Use the option string that's in the file rather than tLogOptions.toPrefix(), // because they might be different if a new option was introduced in this version. StringRef optionsString = filename.removePrefix(fileVersionedLogDataPrefix).eat("-"); TraceEvent("DiskStoreVersioned").detail("Filename", filename); ErrorOr<TLogOptions> tLogOptions = TLogOptions::FromStringRef(optionsString); if (tLogOptions.isError()) { TraceEvent(SevWarn, "DiskStoreMalformedFilename").detail("Filename", filename); continue; } TraceEvent("DiskStoreVersionedSuccess").detail("Filename", filename); store.tLogOptions = tLogOptions.get(); prefix = filename.substr(0, fileVersionedLogDataPrefix.size() + optionsString.size() + 1); } else if (filename.startsWith(fileLogDataPrefix)) { TraceEvent("DiskStoreUnversioned").detail("Filename", filename); store.storedComponent = DiskStore::TLogData; store.tLogOptions.version = TLogVersion::V2; store.tLogOptions.spillType = TLogSpillType::VALUE; prefix = fileLogDataPrefix; } else { continue; } store.storeID = UID::fromString(files[idx].substr(prefix.size(), 32)); store.filename = filenameFromSample(type, folder, files[idx]); result.push_back(store); } return result; } std::vector<DiskStore> getDiskStores(std::string folder) { auto result = getDiskStores(folder, bTreeV1Suffix.suffix, bTreeV1Suffix.type, bTreeV1Suffix.check); auto result1 = getDiskStores(folder, bTreeV2Suffix.suffix, bTreeV2Suffix.type, bTreeV2Suffix.check); result.insert(result.end(), result1.begin(), result1.end()); auto result2 = getDiskStores(folder, memorySuffix.suffix, memorySuffix.type, memorySuffix.check); result.insert(result.end(), result2.begin(), result2.end()); auto result3 = getDiskStores(folder, redwoodSuffix.suffix, redwoodSuffix.type, redwoodSuffix.check); result.insert(result.end(), result3.begin(), result3.end()); auto result4 = getDiskStores(folder, memoryRTSuffix.suffix, memoryRTSuffix.type, memoryRTSuffix.check); result.insert(result.end(), result4.begin(), result4.end()); auto result5 = getDiskStores(folder, rocksdbSuffix.suffix, rocksdbSuffix.type, rocksdbSuffix.check); result.insert(result.end(), result5.begin(), result5.end()); return result; } // Register the worker interf to cluster controller (cc) and // re-register the worker when key roles interface, e.g., cc, dd, ratekeeper, change. ACTOR Future<Void> registrationClient(Reference<AsyncVar<Optional<ClusterControllerFullInterface>> const> ccInterface, WorkerInterface interf, Reference<AsyncVar<ClusterControllerPriorityInfo>> asyncPriorityInfo, ProcessClass initialClass, Reference<AsyncVar<Optional<DataDistributorInterface>> const> ddInterf, Reference<AsyncVar<Optional<RatekeeperInterface>> const> rkInterf, Reference<AsyncVar<Optional<BlobManagerInterface>> const> bmInterf, Reference<AsyncVar<bool> const> degraded, Reference<IClusterConnectionRecord> connRecord, Reference<AsyncVar<std::set<std::string>> const> issues, Reference<LocalConfiguration> localConfig, Reference<AsyncVar<ServerDBInfo>> dbInfo) { // Keeps the cluster controller (as it may be re-elected) informed that this worker exists // The cluster controller uses waitFailureClient to find out if we die, and returns from registrationReply // (requiring us to re-register) The registration request piggybacks optional distributor interface if it exists. state Generation requestGeneration = 0; state ProcessClass processClass = initialClass; state Reference<AsyncVar<Optional<std::pair<uint16_t, StorageServerInterface>>>> scInterf( new AsyncVar<Optional<std::pair<uint16_t, StorageServerInterface>>>()); state Future<Void> cacheProcessFuture; state Future<Void> cacheErrorsFuture; state Optional<double> incorrectTime; state bool firstReg = true; loop { state ClusterConnectionString storedConnectionString; state bool upToDate = true; if (connRecord) { bool upToDateResult = wait(connRecord->upToDate(storedConnectionString)); upToDate = upToDateResult; } if (upToDate) { incorrectTime = Optional<double>(); } RegisterWorkerRequest request(interf, initialClass, processClass, asyncPriorityInfo->get(), requestGeneration++, ddInterf->get(), rkInterf->get(), bmInterf->get(), degraded->get(), localConfig->lastSeenVersion(), localConfig->configClassSet()); for (auto const& i : issues->get()) { request.issues.push_back_deep(request.issues.arena(), i); } if (!upToDate) { request.issues.push_back_deep(request.issues.arena(), LiteralStringRef("incorrect_cluster_file_contents")); std::string connectionString = connRecord->getConnectionString().toString(); if (!incorrectTime.present()) { incorrectTime = now(); } // Don't log a SevWarnAlways initially to account for transient issues (e.g. someone else changing // the file right before us) TraceEvent(now() - incorrectTime.get() > 300 ? SevWarnAlways : SevWarn, "IncorrectClusterFileContents") .detail("ClusterFile", connRecord->toString()) .detail("StoredConnectionString", storedConnectionString.toString()) .detail("CurrentConnectionString", connectionString); } auto peers = FlowTransport::transport().getIncompatiblePeers(); for (auto it = peers->begin(); it != peers->end();) { if (now() - it->second.second > FLOW_KNOBS->INCOMPATIBLE_PEER_DELAY_BEFORE_LOGGING) { request.incompatiblePeers.push_back(it->first); it = peers->erase(it); } else { it++; } } state bool ccInterfacePresent = ccInterface->get().present(); if (ccInterfacePresent) { request.requestDbInfo = (ccInterface->get().get().id() != dbInfo->get().clusterInterface.id()); if (firstReg) { request.requestDbInfo = true; firstReg = false; } } state Future<RegisterWorkerReply> registrationReply = ccInterfacePresent ? brokenPromiseToNever(ccInterface->get().get().registerWorker.getReply(request)) : Never(); state double startTime = now(); loop choose { when(RegisterWorkerReply reply = wait(registrationReply)) { processClass = reply.processClass; asyncPriorityInfo->set(reply.priorityInfo); TraceEvent("WorkerRegisterReply") .detail("CCID", ccInterface->get().get().id()) .detail("ProcessClass", reply.processClass.toString()); break; } when(wait(delay(SERVER_KNOBS->UNKNOWN_CC_TIMEOUT))) { if (!ccInterfacePresent) { TraceEvent(SevWarn, "WorkerRegisterTimeout").detail("WaitTime", now() - startTime); } } when(wait(ccInterface->onChange())) { break; } when(wait(ddInterf->onChange())) { break; } when(wait(rkInterf->onChange())) { break; } when(wait(bmInterf->onChange())) { break; } when(wait(degraded->onChange())) { break; } when(wait(FlowTransport::transport().onIncompatibleChanged())) { break; } when(wait(issues->onChange())) { break; } } } } // Returns true if `address` is used in the db (indicated by `dbInfo`) transaction system and in the db's primary DC. bool addressInDbAndPrimaryDc(const NetworkAddress& address, Reference<AsyncVar<ServerDBInfo> const> dbInfo) { const auto& dbi = dbInfo->get(); if (dbi.master.addresses().contains(address)) { return true; } if (dbi.distributor.present() && dbi.distributor.get().address() == address) { return true; } if (dbi.ratekeeper.present() && dbi.ratekeeper.get().address() == address) { return true; } if (dbi.blobManager.present() && dbi.blobManager.get().address() == address) { return true; } for (const auto& resolver : dbi.resolvers) { if (resolver.address() == address) { return true; } } for (const auto& grvProxy : dbi.client.grvProxies) { if (grvProxy.addresses().contains(address)) { return true; } } for (const auto& commitProxy : dbi.client.commitProxies) { if (commitProxy.addresses().contains(address)) { return true; } } auto localityIsInPrimaryDc = [&dbInfo](const LocalityData& locality) { return locality.dcId() == dbInfo->get().master.locality.dcId(); }; for (const auto& logSet : dbi.logSystemConfig.tLogs) { for (const auto& tlog : logSet.tLogs) { if (!tlog.present()) { continue; } if (!localityIsInPrimaryDc(tlog.interf().filteredLocality)) { continue; } if (tlog.interf().addresses().contains(address)) { return true; } } } return false; } bool addressesInDbAndPrimaryDc(const NetworkAddressList& addresses, Reference<AsyncVar<ServerDBInfo> const> dbInfo) { return addressInDbAndPrimaryDc(addresses.address, dbInfo) || (addresses.secondaryAddress.present() && addressInDbAndPrimaryDc(addresses.secondaryAddress.get(), dbInfo)); } namespace { TEST_CASE("/fdbserver/worker/addressInDbAndPrimaryDc") { // Setup a ServerDBInfo for test. ServerDBInfo testDbInfo; LocalityData testLocal; testLocal.set(LiteralStringRef("dcid"), StringRef(std::to_string(1))); testDbInfo.master.locality = testLocal; // Manually set up a master address. NetworkAddress testAddress(IPAddress(0x13131313), 1); testDbInfo.master.getCommitVersion = RequestStream<struct GetCommitVersionRequest>(Endpoint({ testAddress }, UID(1, 2))); // First, create an empty TLogInterface, and check that it shouldn't be considered as in primary DC. testDbInfo.logSystemConfig.tLogs.push_back(TLogSet()); testDbInfo.logSystemConfig.tLogs.back().tLogs.push_back(OptionalInterface<TLogInterface>()); ASSERT(!addressInDbAndPrimaryDc(g_network->getLocalAddress(), makeReference<AsyncVar<ServerDBInfo>>(testDbInfo))); // Create a remote TLog. Although the remote TLog also uses the local address, it shouldn't be considered as // in primary DC given the remote locality. LocalityData fakeRemote; fakeRemote.set(LiteralStringRef("dcid"), StringRef(std::to_string(2))); TLogInterface remoteTlog(fakeRemote); remoteTlog.initEndpoints(); testDbInfo.logSystemConfig.tLogs.back().tLogs.push_back(OptionalInterface(remoteTlog)); ASSERT(!addressInDbAndPrimaryDc(g_network->getLocalAddress(), makeReference<AsyncVar<ServerDBInfo>>(testDbInfo))); // Next, create a local TLog. Now, the local address should be considered as in local DC. TLogInterface localTlog(testLocal); localTlog.initEndpoints(); testDbInfo.logSystemConfig.tLogs.back().tLogs.push_back(OptionalInterface(localTlog)); ASSERT(addressInDbAndPrimaryDc(g_network->getLocalAddress(), makeReference<AsyncVar<ServerDBInfo>>(testDbInfo))); // Use the master's address to test, which should be considered as in local DC. testDbInfo.logSystemConfig.tLogs.clear(); ASSERT(addressInDbAndPrimaryDc(testAddress, makeReference<AsyncVar<ServerDBInfo>>(testDbInfo))); // Last, tests that proxies included in the ClientDbInfo are considered as local. NetworkAddress grvProxyAddress(IPAddress(0x26262626), 1); GrvProxyInterface grvProxyInterf; grvProxyInterf.getConsistentReadVersion = RequestStream<struct GetReadVersionRequest>(Endpoint({ grvProxyAddress }, UID(1, 2))); testDbInfo.client.grvProxies.push_back(grvProxyInterf); ASSERT(addressInDbAndPrimaryDc(grvProxyAddress, makeReference<AsyncVar<ServerDBInfo>>(testDbInfo))); NetworkAddress commitProxyAddress(IPAddress(0x37373737), 1); CommitProxyInterface commitProxyInterf; commitProxyInterf.commit = RequestStream<struct CommitTransactionRequest>(Endpoint({ commitProxyAddress }, UID(1, 2))); testDbInfo.client.commitProxies.push_back(commitProxyInterf); ASSERT(addressInDbAndPrimaryDc(commitProxyAddress, makeReference<AsyncVar<ServerDBInfo>>(testDbInfo))); return Void(); } } // namespace bool addressInDbAndRemoteDc(const NetworkAddress& address, Reference<AsyncVar<ServerDBInfo> const> dbInfo) { const auto& dbi = dbInfo->get(); for (const auto& logSet : dbi.logSystemConfig.tLogs) { if (logSet.isLocal || logSet.locality == tagLocalitySatellite) { continue; } for (const auto& tlog : logSet.tLogs) { if (tlog.present() && tlog.interf().addresses().contains(address)) { return true; } } for (const auto& logRouter : logSet.logRouters) { if (logRouter.present() && logRouter.interf().addresses().contains(address)) { return true; } } } return false; } bool addressesInDbAndRemoteDc(const NetworkAddressList& addresses, Reference<AsyncVar<ServerDBInfo> const> dbInfo) { return addressInDbAndRemoteDc(addresses.address, dbInfo) || (addresses.secondaryAddress.present() && addressInDbAndRemoteDc(addresses.secondaryAddress.get(), dbInfo)); } namespace { TEST_CASE("/fdbserver/worker/addressInDbAndRemoteDc") { // Setup a ServerDBInfo for test. ServerDBInfo testDbInfo; LocalityData testLocal; testLocal.set(LiteralStringRef("dcid"), StringRef(std::to_string(1))); testDbInfo.master.locality = testLocal; // First, create an empty TLogInterface, and check that it shouldn't be considered as in remote DC. testDbInfo.logSystemConfig.tLogs.push_back(TLogSet()); testDbInfo.logSystemConfig.tLogs.back().isLocal = true; testDbInfo.logSystemConfig.tLogs.back().tLogs.push_back(OptionalInterface<TLogInterface>()); ASSERT(!addressInDbAndRemoteDc(g_network->getLocalAddress(), makeReference<AsyncVar<ServerDBInfo>>(testDbInfo))); TLogInterface localTlog(testLocal); localTlog.initEndpoints(); testDbInfo.logSystemConfig.tLogs.back().tLogs.push_back(OptionalInterface(localTlog)); ASSERT(!addressInDbAndRemoteDc(g_network->getLocalAddress(), makeReference<AsyncVar<ServerDBInfo>>(testDbInfo))); // Create a remote TLog, and it should be considered as in remote DC. LocalityData fakeRemote; fakeRemote.set(LiteralStringRef("dcid"), StringRef(std::to_string(2))); TLogInterface remoteTlog(fakeRemote); remoteTlog.initEndpoints(); testDbInfo.logSystemConfig.tLogs.push_back(TLogSet()); testDbInfo.logSystemConfig.tLogs.back().isLocal = false; testDbInfo.logSystemConfig.tLogs.back().tLogs.push_back(OptionalInterface(remoteTlog)); ASSERT(addressInDbAndRemoteDc(g_network->getLocalAddress(), makeReference<AsyncVar<ServerDBInfo>>(testDbInfo))); // Create a remote log router, and it should be considered as in remote DC. NetworkAddress logRouterAddress(IPAddress(0x26262626), 1); TLogInterface remoteLogRouter(fakeRemote); remoteLogRouter.initEndpoints(); remoteLogRouter.peekMessages = RequestStream<struct TLogPeekRequest>(Endpoint({ logRouterAddress }, UID(1, 2))); testDbInfo.logSystemConfig.tLogs.back().logRouters.push_back(OptionalInterface(remoteLogRouter)); ASSERT(addressInDbAndRemoteDc(logRouterAddress, makeReference<AsyncVar<ServerDBInfo>>(testDbInfo))); // Create a satellite tlog, and it shouldn't be considered as in remote DC. testDbInfo.logSystemConfig.tLogs.push_back(TLogSet()); testDbInfo.logSystemConfig.tLogs.back().locality = tagLocalitySatellite; NetworkAddress satelliteTLogAddress(IPAddress(0x13131313), 1); TLogInterface satelliteTLog(fakeRemote); satelliteTLog.initEndpoints(); satelliteTLog.peekMessages = RequestStream<struct TLogPeekRequest>(Endpoint({ satelliteTLogAddress }, UID(1, 2))); testDbInfo.logSystemConfig.tLogs.back().tLogs.push_back(OptionalInterface(satelliteTLog)); ASSERT(!addressInDbAndRemoteDc(satelliteTLogAddress, makeReference<AsyncVar<ServerDBInfo>>(testDbInfo))); return Void(); } } // namespace // The actor that actively monitors the health of local and peer servers, and reports anomaly to the cluster controller. ACTOR Future<Void> healthMonitor(Reference<AsyncVar<Optional<ClusterControllerFullInterface>> const> ccInterface, WorkerInterface interf, LocalityData locality, Reference<AsyncVar<ServerDBInfo> const> dbInfo) { loop { Future<Void> nextHealthCheckDelay = Never(); if (dbInfo->get().recoveryState >= RecoveryState::ACCEPTING_COMMITS && ccInterface->get().present()) { nextHealthCheckDelay = delay(SERVER_KNOBS->WORKER_HEALTH_MONITOR_INTERVAL); const auto& allPeers = FlowTransport::transport().getAllPeers(); UpdateWorkerHealthRequest req; bool workerInDb = false; bool workerInPrimary = false; if (addressesInDbAndPrimaryDc(interf.addresses(), dbInfo)) { workerInDb = true; workerInPrimary = true; } else if (addressesInDbAndRemoteDc(interf.addresses(), dbInfo)) { workerInDb = true; workerInPrimary = false; } if (workerInDb) { for (const auto& [address, peer] : allPeers) { if (peer->pingLatencies.getPopulationSize() < SERVER_KNOBS->PEER_LATENCY_CHECK_MIN_POPULATION) { // Ignore peers that don't have enough samples. // TODO(zhewu): Currently, FlowTransport latency monitor clears ping latency samples on a // regular // basis, which may affect the measurement count. Currently, // WORKER_HEALTH_MONITOR_INTERVAL is much smaller than the ping clearance interval, // so it may be ok. If this ends to be a problem, we need to consider keep track of // last ping latencies logged. continue; } if ((workerInPrimary && addressInDbAndPrimaryDc(address, dbInfo)) || (!workerInPrimary && addressInDbAndRemoteDc(address, dbInfo))) { // Only monitoring the servers that in the primary or remote DC's transaction systems. // Note that currently we are not monitor storage servers, since lagging in storage servers // today already can trigger server exclusion by data distributor. if (peer->pingLatencies.percentile(SERVER_KNOBS->PEER_LATENCY_DEGRADATION_PERCENTILE) > SERVER_KNOBS->PEER_LATENCY_DEGRADATION_THRESHOLD || peer->timeoutCount / (double)(peer->pingLatencies.getPopulationSize()) > SERVER_KNOBS->PEER_TIMEOUT_PERCENTAGE_DEGRADATION_THRESHOLD) { // This is a degraded peer. TraceEvent("HealthMonitorDetectDegradedPeer") .suppressFor(30) .detail("Peer", address) .detail("Elapsed", now() - peer->lastLoggedTime) .detail("MinLatency", peer->pingLatencies.min()) .detail("MaxLatency", peer->pingLatencies.max()) .detail("MeanLatency", peer->pingLatencies.mean()) .detail("MedianLatency", peer->pingLatencies.median()) .detail("CheckedPercentile", SERVER_KNOBS->PEER_LATENCY_DEGRADATION_PERCENTILE) .detail( "CheckedPercentileLatency", peer->pingLatencies.percentile(SERVER_KNOBS->PEER_LATENCY_DEGRADATION_PERCENTILE)) .detail("Count", peer->pingLatencies.getPopulationSize()) .detail("TimeoutCount", peer->timeoutCount); req.degradedPeers.push_back(address); } } } } if (!req.degradedPeers.empty()) { req.address = FlowTransport::transport().getLocalAddress(); ccInterface->get().get().updateWorkerHealth.send(req); } } choose { when(wait(nextHealthCheckDelay)) {} when(wait(ccInterface->onChange())) {} when(wait(dbInfo->onChange())) {} } } } #if (defined(__linux__) || defined(__FreeBSD__)) && defined(USE_GPERFTOOLS) // A set of threads that should be profiled std::set<std::thread::id> profiledThreads; // Returns whether or not a given thread should be profiled int filter_in_thread(void* arg) { return profiledThreads.count(std::this_thread::get_id()) > 0 ? 1 : 0; } #endif // Enables the calling thread to be profiled void registerThreadForProfiling() { #if (defined(__linux__) || defined(__FreeBSD__)) && defined(USE_GPERFTOOLS) // Not sure if this is actually needed, but a call to backtrace was advised here: // http://groups.google.com/group/google-perftools/browse_thread/thread/0dfd74532e038eb8/2686d9f24ac4365f?pli=1 profiledThreads.insert(std::this_thread::get_id()); const int num_levels = 100; void* pc[num_levels]; backtrace(pc, num_levels); #endif } // Starts or stops the CPU profiler void updateCpuProfiler(ProfilerRequest req) { switch (req.type) { case ProfilerRequest::Type::GPROF: #if (defined(__linux__) || defined(__FreeBSD__)) && defined(USE_GPERFTOOLS) && !defined(VALGRIND) switch (req.action) { case ProfilerRequest::Action::ENABLE: { const char* path = (const char*)req.outputFile.begin(); ProfilerOptions* options = new ProfilerOptions(); options->filter_in_thread = &filter_in_thread; options->filter_in_thread_arg = nullptr; ProfilerStartWithOptions(path, options); break; } case ProfilerRequest::Action::DISABLE: ProfilerStop(); break; case ProfilerRequest::Action::RUN: ASSERT(false); // User should have called runProfiler. break; } #endif break; case ProfilerRequest::Type::FLOW: switch (req.action) { case ProfilerRequest::Action::ENABLE: startProfiling(g_network, {}, req.outputFile); break; case ProfilerRequest::Action::DISABLE: stopProfiling(); break; case ProfilerRequest::Action::RUN: ASSERT(false); // User should have called runProfiler. break; } break; default: ASSERT(false); break; } } ACTOR Future<Void> runCpuProfiler(ProfilerRequest req) { if (req.action == ProfilerRequest::Action::RUN) { req.action = ProfilerRequest::Action::ENABLE; updateCpuProfiler(req); wait(delay(req.duration)); req.action = ProfilerRequest::Action::DISABLE; updateCpuProfiler(req); return Void(); } else { updateCpuProfiler(req); return Void(); } } void runHeapProfiler(const char* msg) { #if defined(__linux__) && defined(USE_GPERFTOOLS) && !defined(VALGRIND) if (IsHeapProfilerRunning()) { HeapProfilerDump(msg); } else { TraceEvent("ProfilerError").detail("Message", "HeapProfiler not running"); } #else TraceEvent("ProfilerError").detail("Message", "HeapProfiler Unsupported"); #endif } ACTOR Future<Void> runProfiler(ProfilerRequest req) { if (req.type == ProfilerRequest::Type::GPROF_HEAP) { runHeapProfiler("User triggered heap dump"); } else { wait(runCpuProfiler(req)); } return Void(); } bool checkHighMemory(int64_t threshold, bool* error) { #if defined(__linux__) && defined(USE_GPERFTOOLS) && !defined(VALGRIND) *error = false; uint64_t page_size = sysconf(_SC_PAGESIZE); int fd = open("/proc/self/statm", O_RDONLY | O_CLOEXEC); if (fd < 0) { TraceEvent("OpenStatmFileFailure").log(); *error = true; return false; } const int buf_sz = 256; char stat_buf[buf_sz]; ssize_t stat_nread = read(fd, stat_buf, buf_sz); if (stat_nread < 0) { TraceEvent("ReadStatmFileFailure").log(); *error = true; return false; } uint64_t vmsize, rss; sscanf(stat_buf, "%lu %lu", &vmsize, &rss); rss *= page_size; if (rss >= threshold) { return true; } #else TraceEvent("CheckHighMemoryUnsupported").log(); *error = true; #endif return false; } // Runs heap profiler when RSS memory usage is high. ACTOR Future<Void> monitorHighMemory(int64_t threshold) { if (threshold <= 0) return Void(); loop { bool err = false; bool highmem = checkHighMemory(threshold, &err); if (err) break; if (highmem) runHeapProfiler("Highmem heap dump"); wait(delay(SERVER_KNOBS->HEAP_PROFILER_INTERVAL)); } return Void(); } struct TrackRunningStorage { UID self; KeyValueStoreType storeType; std::set<std::pair<UID, KeyValueStoreType>>* runningStorages; TrackRunningStorage(UID self, KeyValueStoreType storeType, std::set<std::pair<UID, KeyValueStoreType>>* runningStorages) : self(self), storeType(storeType), runningStorages(runningStorages) { runningStorages->emplace(self, storeType); } ~TrackRunningStorage() { runningStorages->erase(std::make_pair(self, storeType)); }; }; ACTOR Future<Void> storageServerRollbackRebooter(std::set<std::pair<UID, KeyValueStoreType>>* runningStorages, Future<Void> prevStorageServer, KeyValueStoreType storeType, std::string filename, UID id, LocalityData locality, bool isTss, Reference<AsyncVar<ServerDBInfo> const> db, std::string folder, ActorCollection* filesClosed, int64_t memoryLimit, IKeyValueStore* store) { state TrackRunningStorage _(id, storeType, runningStorages); loop { ErrorOr<Void> e = wait(errorOr(prevStorageServer)); if (!e.isError()) return Void(); else if (e.getError().code() != error_code_please_reboot) throw e.getError(); TraceEvent("StorageServerRequestedReboot", id).log(); StorageServerInterface recruited; recruited.uniqueID = id; recruited.locality = locality; recruited.tssPairID = isTss ? Optional<UID>(UID()) : Optional<UID>(); // set this here since we use its presence to determine // whether this server is a tss or not recruited.initEndpoints(); DUMPTOKEN(recruited.getValue); DUMPTOKEN(recruited.getKey); DUMPTOKEN(recruited.getKeyValues); DUMPTOKEN(recruited.getKeyValuesAndFlatMap); DUMPTOKEN(recruited.getShardState); DUMPTOKEN(recruited.waitMetrics); DUMPTOKEN(recruited.splitMetrics); DUMPTOKEN(recruited.getReadHotRanges); DUMPTOKEN(recruited.getRangeSplitPoints); DUMPTOKEN(recruited.getStorageMetrics); DUMPTOKEN(recruited.waitFailure); DUMPTOKEN(recruited.getQueuingMetrics); DUMPTOKEN(recruited.getKeyValueStoreType); DUMPTOKEN(recruited.watchValue); DUMPTOKEN(recruited.getKeyValuesStream); DUMPTOKEN(recruited.getKeyValuesAndFlatMap); prevStorageServer = storageServer(store, recruited, db, folder, Promise<Void>(), Reference<IClusterConnectionRecord>(nullptr)); prevStorageServer = handleIOErrors(prevStorageServer, store, id, store->onClosed()); } } ACTOR Future<Void> storageCacheRollbackRebooter(Future<Void> prevStorageCache, UID id, LocalityData locality, Reference<AsyncVar<ServerDBInfo> const> db) { loop { ErrorOr<Void> e = wait(errorOr(prevStorageCache)); if (!e.isError()) { TraceEvent("StorageCacheRequestedReboot1", id).log(); return Void(); } else if (e.getError().code() != error_code_please_reboot && e.getError().code() != error_code_worker_removed) { TraceEvent("StorageCacheRequestedReboot2", id).detail("Code", e.getError().code()); throw e.getError(); } TraceEvent("StorageCacheRequestedReboot", id).log(); StorageServerInterface recruited; recruited.uniqueID = deterministicRandom()->randomUniqueID(); // id; recruited.locality = locality; recruited.initEndpoints(); DUMPTOKEN(recruited.getValue); DUMPTOKEN(recruited.getKey); DUMPTOKEN(recruited.getKeyValues); DUMPTOKEN(recruited.getShardState); DUMPTOKEN(recruited.waitMetrics); DUMPTOKEN(recruited.splitMetrics); DUMPTOKEN(recruited.getStorageMetrics); DUMPTOKEN(recruited.waitFailure); DUMPTOKEN(recruited.getQueuingMetrics); DUMPTOKEN(recruited.getKeyValueStoreType); DUMPTOKEN(recruited.watchValue); prevStorageCache = storageCacheServer(recruited, 0, db); } } // FIXME: This will not work correctly in simulation as all workers would share the same roles map std::set<std::pair<std::string, std::string>> g_roles; Standalone<StringRef> roleString(std::set<std::pair<std::string, std::string>> roles, bool with_ids) { std::string result; for (auto& r : roles) { if (!result.empty()) result.append(","); result.append(r.first); if (with_ids) { result.append(":"); result.append(r.second); } } return StringRef(result); } void startRole(const Role& role, UID roleId, UID workerId, const std::map<std::string, std::string>& details, const std::string& origination) { if (role.includeInTraceRoles) { addTraceRole(role.abbreviation); } TraceEvent ev("Role", roleId); ev.detail("As", role.roleName) .detail("Transition", "Begin") .detail("Origination", origination) .detail("OnWorker", workerId); for (auto it = details.begin(); it != details.end(); it++) ev.detail(it->first.c_str(), it->second); ev.trackLatest(roleId.shortString() + ".Role"); // Update roles map, log Roles metrics g_roles.insert({ role.roleName, roleId.shortString() }); StringMetricHandle(LiteralStringRef("Roles")) = roleString(g_roles, false); StringMetricHandle(LiteralStringRef("RolesWithIDs")) = roleString(g_roles, true); if (g_network->isSimulated()) g_simulator.addRole(g_network->getLocalAddress(), role.roleName); } void endRole(const Role& role, UID id, std::string reason, bool ok, Error e) { { TraceEvent ev("Role", id); if (e.code() != invalid_error_code) ev.error(e, true); ev.detail("Transition", "End").detail("As", role.roleName).detail("Reason", reason); ev.trackLatest(id.shortString() + ".Role"); } if (!ok) { std::string type = role.roleName + "Failed"; TraceEvent err(SevError, type.c_str(), id); if (e.code() != invalid_error_code) { err.error(e, true); } err.detail("Reason", reason); } latestEventCache.clear(id.shortString()); // Update roles map, log Roles metrics g_roles.erase({ role.roleName, id.shortString() }); StringMetricHandle(LiteralStringRef("Roles")) = roleString(g_roles, false); StringMetricHandle(LiteralStringRef("RolesWithIDs")) = roleString(g_roles, true); if (g_network->isSimulated()) g_simulator.removeRole(g_network->getLocalAddress(), role.roleName); if (role.includeInTraceRoles) { removeTraceRole(role.abbreviation); } } ACTOR Future<Void> traceRole(Role role, UID roleId) { loop { wait(delay(SERVER_KNOBS->WORKER_LOGGING_INTERVAL)); TraceEvent("Role", roleId).detail("Transition", "Refresh").detail("As", role.roleName); } } ACTOR Future<Void> workerSnapCreate(WorkerSnapRequest snapReq, Standalone<StringRef> snapFolder) { state ExecCmdValueString snapArg(snapReq.snapPayload); try { int err = wait(execHelper(&snapArg, snapReq.snapUID, snapFolder.toString(), snapReq.role.toString())); std::string uidStr = snapReq.snapUID.toString(); TraceEvent("ExecTraceWorker") .detail("Uid", uidStr) .detail("Status", err) .detail("Role", snapReq.role) .detail("Value", snapFolder) .detail("ExecPayload", snapReq.snapPayload); if (err != 0) { throw operation_failed(); } if (snapReq.role.toString() == "storage") { printStorageVersionInfo(); } snapReq.reply.send(Void()); } catch (Error& e) { TraceEvent("ExecHelperError").error(e, true /*includeCancelled*/); if (e.code() != error_code_operation_cancelled) { snapReq.reply.sendError(e); } else { throw e; } } return Void(); } // TODO: `issues` is right now only updated by `monitorTraceLogIssues` and thus is being `set` on every update. // It could be changed to `insert` and `trigger` later if we want to use it as a generic way for the caller of this // function to report issues to cluster controller. ACTOR Future<Void> monitorTraceLogIssues(Reference<AsyncVar<std::set<std::string>>> issues) { state bool pingTimeout = false; loop { wait(delay(SERVER_KNOBS->TRACE_LOG_FLUSH_FAILURE_CHECK_INTERVAL_SECONDS)); Future<Void> pingAck = pingTraceLogWriterThread(); try { wait(timeoutError(pingAck, SERVER_KNOBS->TRACE_LOG_PING_TIMEOUT_SECONDS)); } catch (Error& e) { if (e.code() == error_code_timed_out) { pingTimeout = true; } else { throw; } } std::set<std::string> _issues; retrieveTraceLogIssues(_issues); if (pingTimeout) { // Ping trace log writer thread timeout. _issues.insert("trace_log_writer_thread_unresponsive"); pingTimeout = false; } issues->set(_issues); } } class SharedLogsKey { TLogVersion logVersion; TLogSpillType spillType; KeyValueStoreType storeType; public: SharedLogsKey(const TLogOptions& options, KeyValueStoreType kvst) : logVersion(options.version), spillType(options.spillType), storeType(kvst) { if (logVersion >= TLogVersion::V5) spillType = TLogSpillType::UNSET; } bool operator<(const SharedLogsKey& other) const { return std::tie(logVersion, spillType, storeType) < std::tie(other.logVersion, other.spillType, other.storeType); } }; struct SharedLogsValue { Future<Void> actor = Void(); UID uid = UID(); PromiseStream<InitializeTLogRequest> requests; SharedLogsValue() = default; SharedLogsValue(Future<Void> actor, UID uid, PromiseStream<InitializeTLogRequest> requests) : actor(actor), uid(uid), requests(requests) {} }; ACTOR Future<Void> chaosMetricsLogger() { auto res = g_network->global(INetwork::enChaosMetrics); if (!res) return Void(); state ChaosMetrics* chaosMetrics = static_cast<ChaosMetrics*>(res); chaosMetrics->clear(); loop { wait(delay(FLOW_KNOBS->CHAOS_LOGGING_INTERVAL)); TraceEvent e("ChaosMetrics"); double elapsed = now() - chaosMetrics->startTime; e.detail("Elapsed", elapsed); chaosMetrics->getFields(&e); e.trackLatest("ChaosMetrics"); chaosMetrics->clear(); } } ACTOR Future<Void> workerServer(Reference<IClusterConnectionRecord> connRecord, Reference<AsyncVar<Optional<ClusterControllerFullInterface>> const> ccInterface, LocalityData locality, Reference<AsyncVar<ClusterControllerPriorityInfo>> asyncPriorityInfo, ProcessClass initialClass, std::string folder, int64_t memoryLimit, std::string metricsConnFile, std::string metricsPrefix, Promise<Void> recoveredDiskFiles, int64_t memoryProfileThreshold, std::string _coordFolder, std::string whitelistBinPaths, Reference<AsyncVar<ServerDBInfo>> dbInfo, ConfigDBType configDBType, Reference<LocalConfiguration> localConfig) { state PromiseStream<ErrorInfo> errors; state Reference<AsyncVar<Optional<DataDistributorInterface>>> ddInterf( new AsyncVar<Optional<DataDistributorInterface>>()); state Reference<AsyncVar<Optional<RatekeeperInterface>>> rkInterf(new AsyncVar<Optional<RatekeeperInterface>>()); state Reference<AsyncVar<Optional<BlobManagerInterface>>> bmInterf(new AsyncVar<Optional<BlobManagerInterface>>()); state Future<Void> handleErrors = workerHandleErrors(errors.getFuture()); // Needs to be stopped last state ActorCollection errorForwarders(false); state Future<Void> loggingTrigger = Void(); state double loggingDelay = SERVER_KNOBS->WORKER_LOGGING_INTERVAL; state ActorCollection filesClosed(true); state Promise<Void> stopping; state WorkerCache<InitializeStorageReply> storageCache; state Future<Void> metricsLogger; state Future<Void> chaosMetricsActor; state Reference<AsyncVar<bool>> degraded = FlowTransport::transport().getDegraded(); // tLogFnForOptions() can return a function that doesn't correspond with the FDB version that the // TLogVersion represents. This can be done if the newer TLog doesn't support a requested option. // As (store type, spill type) can map to the same TLogFn across multiple TLogVersions, we need to // decide if we should collapse them into the same SharedTLog instance as well. The answer // here is no, so that when running with log_version==3, all files should say V=3. state std::map<SharedLogsKey, SharedLogsValue> sharedLogs; state Reference<AsyncVar<UID>> activeSharedTLog(new AsyncVar<UID>()); state WorkerCache<InitializeBackupReply> backupWorkerCache; state std::string coordFolder = abspath(_coordFolder); state WorkerInterface interf(locality); state std::set<std::pair<UID, KeyValueStoreType>> runningStorages; interf.initEndpoints(); state Reference<AsyncVar<std::set<std::string>>> issues(new AsyncVar<std::set<std::string>>()); if (FLOW_KNOBS->ENABLE_CHAOS_FEATURES) { TraceEvent(SevInfo, "ChaosFeaturesEnabled"); chaosMetricsActor = chaosMetricsLogger(); } folder = abspath(folder); if (metricsPrefix.size() > 0) { if (metricsConnFile.size() > 0) { try { state Database db = Database::createDatabase(metricsConnFile, Database::API_VERSION_LATEST, IsInternal::True, locality); metricsLogger = runMetrics(db, KeyRef(metricsPrefix)); } catch (Error& e) { TraceEvent(SevWarnAlways, "TDMetricsBadClusterFile").error(e).detail("ConnFile", metricsConnFile); } } else { auto lockAware = metricsPrefix.size() && metricsPrefix[0] == '\xff' ? LockAware::True : LockAware::False; metricsLogger = runMetrics(openDBOnServer(dbInfo, TaskPriority::DefaultEndpoint, lockAware), KeyRef(metricsPrefix)); } GlobalConfig::globalConfig().trigger(samplingFrequency, samplingProfilerUpdateFrequency); } errorForwarders.add(resetAfter(degraded, SERVER_KNOBS->DEGRADED_RESET_INTERVAL, false, SERVER_KNOBS->DEGRADED_WARNING_LIMIT, SERVER_KNOBS->DEGRADED_WARNING_RESET_DELAY, "DegradedReset")); errorForwarders.add(loadedPonger(interf.debugPing.getFuture())); errorForwarders.add(waitFailureServer(interf.waitFailure.getFuture())); errorForwarders.add(monitorTraceLogIssues(issues)); errorForwarders.add(testerServerCore(interf.testerInterface, connRecord, dbInfo, locality)); errorForwarders.add(monitorHighMemory(memoryProfileThreshold)); filesClosed.add(stopping.getFuture()); initializeSystemMonitorMachineState(SystemMonitorMachineState( folder, locality.dcId(), locality.zoneId(), locality.machineId(), g_network->getLocalAddress().ip)); { auto recruited = interf; DUMPTOKEN(recruited.clientInterface.reboot); DUMPTOKEN(recruited.clientInterface.profiler); DUMPTOKEN(recruited.tLog); DUMPTOKEN(recruited.master); DUMPTOKEN(recruited.commitProxy); DUMPTOKEN(recruited.grvProxy); DUMPTOKEN(recruited.resolver); DUMPTOKEN(recruited.storage); DUMPTOKEN(recruited.debugPing); DUMPTOKEN(recruited.coordinationPing); DUMPTOKEN(recruited.waitFailure); DUMPTOKEN(recruited.setMetricsRate); DUMPTOKEN(recruited.eventLogRequest); DUMPTOKEN(recruited.traceBatchDumpRequest); DUMPTOKEN(recruited.updateServerDBInfo); } state std::vector<Future<Void>> recoveries; try { std::vector<DiskStore> stores = getDiskStores(folder); bool validateDataFiles = deleteFile(joinPath(folder, validationFilename)); for (int f = 0; f < stores.size(); f++) { DiskStore s = stores[f]; // FIXME: Error handling if (s.storedComponent == DiskStore::Storage) { LocalLineage _; getCurrentLineage()->modify(&RoleLineage::role) = ProcessClass::ClusterRole::Storage; IKeyValueStore* kv = openKVStore(s.storeType, s.filename, s.storeID, memoryLimit, false, validateDataFiles); Future<Void> kvClosed = kv->onClosed(); filesClosed.add(kvClosed); // std::string doesn't have startsWith std::string tssPrefix = testingStoragePrefix.toString(); // TODO might be more efficient to mark a boolean on DiskStore in getDiskStores, but that kind of breaks // the abstraction since DiskStore also applies to storage cache + tlog bool isTss = s.filename.find(tssPrefix) != std::string::npos; Role ssRole = isTss ? Role::TESTING_STORAGE_SERVER : Role::STORAGE_SERVER; StorageServerInterface recruited; recruited.uniqueID = s.storeID; recruited.locality = locality; recruited.tssPairID = isTss ? Optional<UID>(UID()) : Optional<UID>(); // presence of optional is used as source of truth for tss vs not. Value // gets overridden later in restoreDurableState recruited.initEndpoints(); std::map<std::string, std::string> details; details["StorageEngine"] = s.storeType.toString(); details["IsTSS"] = isTss ? "Yes" : "No"; startRole(ssRole, recruited.id(), interf.id(), details, "Restored"); DUMPTOKEN(recruited.getValue); DUMPTOKEN(recruited.getKey); DUMPTOKEN(recruited.getKeyValues); DUMPTOKEN(recruited.getShardState); DUMPTOKEN(recruited.waitMetrics); DUMPTOKEN(recruited.splitMetrics); DUMPTOKEN(recruited.getReadHotRanges); DUMPTOKEN(recruited.getRangeSplitPoints); DUMPTOKEN(recruited.getStorageMetrics); DUMPTOKEN(recruited.waitFailure); DUMPTOKEN(recruited.getQueuingMetrics); DUMPTOKEN(recruited.getKeyValueStoreType); DUMPTOKEN(recruited.watchValue); DUMPTOKEN(recruited.getKeyValuesStream); DUMPTOKEN(recruited.getKeyValuesAndFlatMap); Promise<Void> recovery; Future<Void> f = storageServer(kv, recruited, dbInfo, folder, recovery, connRecord); recoveries.push_back(recovery.getFuture()); f = handleIOErrors(f, kv, s.storeID, kvClosed); f = storageServerRollbackRebooter(&runningStorages, f, s.storeType, s.filename, recruited.id(), recruited.locality, isTss, dbInfo, folder, &filesClosed, memoryLimit, kv); errorForwarders.add(forwardError(errors, ssRole, recruited.id(), f)); } else if (s.storedComponent == DiskStore::TLogData) { LocalLineage _; getCurrentLineage()->modify(&RoleLineage::role) = ProcessClass::ClusterRole::TLog; std::string logQueueBasename; const std::string filename = basename(s.filename); if (StringRef(filename).startsWith(fileLogDataPrefix)) { logQueueBasename = fileLogQueuePrefix.toString(); } else { StringRef optionsString = StringRef(filename).removePrefix(fileVersionedLogDataPrefix).eat("-"); logQueueBasename = fileLogQueuePrefix.toString() + optionsString.toString() + "-"; } ASSERT_WE_THINK(abspath(parentDirectory(s.filename)) == folder); IKeyValueStore* kv = openKVStore(s.storeType, s.filename, s.storeID, memoryLimit, validateDataFiles); const DiskQueueVersion dqv = s.tLogOptions.version >= TLogVersion::V3 ? DiskQueueVersion::V1 : DiskQueueVersion::V0; const int64_t diskQueueWarnSize = s.tLogOptions.spillType == TLogSpillType::VALUE ? 10 * SERVER_KNOBS->TARGET_BYTES_PER_TLOG : -1; IDiskQueue* queue = openDiskQueue(joinPath(folder, logQueueBasename + s.storeID.toString() + "-"), tlogQueueExtension.toString(), s.storeID, dqv, diskQueueWarnSize); filesClosed.add(kv->onClosed()); filesClosed.add(queue->onClosed()); std::map<std::string, std::string> details; details["StorageEngine"] = s.storeType.toString(); startRole(Role::SHARED_TRANSACTION_LOG, s.storeID, interf.id(), details, "Restored"); Promise<Void> oldLog; Promise<Void> recovery; TLogFn tLogFn = tLogFnForOptions(s.tLogOptions); auto& logData = sharedLogs[SharedLogsKey(s.tLogOptions, s.storeType)]; // FIXME: Shouldn't if logData.first isValid && !isReady, shouldn't we // be sending a fake InitializeTLogRequest rather than calling tLog() ? Future<Void> tl = tLogFn(kv, queue, dbInfo, locality, !logData.actor.isValid() || logData.actor.isReady() ? logData.requests : PromiseStream<InitializeTLogRequest>(), s.storeID, interf.id(), true, oldLog, recovery, folder, degraded, activeSharedTLog); recoveries.push_back(recovery.getFuture()); activeSharedTLog->set(s.storeID); tl = handleIOErrors(tl, kv, s.storeID); tl = handleIOErrors(tl, queue, s.storeID); if (!logData.actor.isValid() || logData.actor.isReady()) { logData.actor = oldLog.getFuture() || tl; logData.uid = s.storeID; } errorForwarders.add(forwardError(errors, Role::SHARED_TRANSACTION_LOG, s.storeID, tl)); } } bool hasCache = false; // start cache role if we have the right process class if (initialClass.classType() == ProcessClass::StorageCacheClass) { hasCache = true; StorageServerInterface recruited; recruited.locality = locality; recruited.initEndpoints(); std::map<std::string, std::string> details; startRole(Role::STORAGE_CACHE, recruited.id(), interf.id(), details); // DUMPTOKEN(recruited.getVersion); DUMPTOKEN(recruited.getValue); DUMPTOKEN(recruited.getKey); DUMPTOKEN(recruited.getKeyValues); DUMPTOKEN(recruited.getKeyValuesAndFlatMap); DUMPTOKEN(recruited.getShardState); DUMPTOKEN(recruited.waitMetrics); DUMPTOKEN(recruited.splitMetrics); DUMPTOKEN(recruited.getStorageMetrics); DUMPTOKEN(recruited.waitFailure); DUMPTOKEN(recruited.getQueuingMetrics); DUMPTOKEN(recruited.getKeyValueStoreType); DUMPTOKEN(recruited.watchValue); auto f = storageCacheServer(recruited, 0, dbInfo); f = storageCacheRollbackRebooter(f, recruited.id(), recruited.locality, dbInfo); errorForwarders.add(forwardError(errors, Role::STORAGE_CACHE, recruited.id(), f)); } std::map<std::string, std::string> details; details["Locality"] = locality.toString(); details["DataFolder"] = folder; details["StoresPresent"] = format("%d", stores.size()); details["CachePresent"] = hasCache ? "true" : "false"; startRole(Role::WORKER, interf.id(), interf.id(), details); errorForwarders.add(traceRole(Role::WORKER, interf.id())); wait(waitForAll(recoveries)); recoveredDiskFiles.send(Void()); errorForwarders.add(registrationClient(ccInterface, interf, asyncPriorityInfo, initialClass, ddInterf, rkInterf, bmInterf, degraded, connRecord, issues, localConfig, dbInfo)); if (configDBType != ConfigDBType::DISABLED) { errorForwarders.add(localConfig->consume(interf.configBroadcastInterface)); } if (SERVER_KNOBS->ENABLE_WORKER_HEALTH_MONITOR) { errorForwarders.add(healthMonitor(ccInterface, interf, locality, dbInfo)); } TraceEvent("RecoveriesComplete", interf.id()); loop choose { when(UpdateServerDBInfoRequest req = waitNext(interf.updateServerDBInfo.getFuture())) { ServerDBInfo localInfo = BinaryReader::fromStringRef<ServerDBInfo>( req.serializedDbInfo, AssumeVersion(g_network->protocolVersion())); localInfo.myLocality = locality; if (localInfo.infoGeneration < dbInfo->get().infoGeneration && localInfo.clusterInterface == dbInfo->get().clusterInterface) { std::vector<Endpoint> rep = req.broadcastInfo; rep.push_back(interf.updateServerDBInfo.getEndpoint()); req.reply.send(rep); } else { Optional<Endpoint> notUpdated; if (!ccInterface->get().present() || localInfo.clusterInterface != ccInterface->get().get()) { notUpdated = interf.updateServerDBInfo.getEndpoint(); } else if (localInfo.infoGeneration > dbInfo->get().infoGeneration || dbInfo->get().clusterInterface != ccInterface->get().get()) { TraceEvent("GotServerDBInfoChange") .detail("ChangeID", localInfo.id) .detail("MasterID", localInfo.master.id()) .detail("RatekeeperID", localInfo.ratekeeper.present() ? localInfo.ratekeeper.get().id() : UID()) .detail("DataDistributorID", localInfo.distributor.present() ? localInfo.distributor.get().id() : UID()) .detail("BlobManagerID", localInfo.blobManager.present() ? localInfo.blobManager.get().id() : UID()); dbInfo->set(localInfo); } errorForwarders.add( success(broadcastDBInfoRequest(req, SERVER_KNOBS->DBINFO_SEND_AMOUNT, notUpdated, true))); } } when(RebootRequest req = waitNext(interf.clientInterface.reboot.getFuture())) { state RebootRequest rebootReq = req; // If suspendDuration is INT_MAX, the trace will not be logged if it was inside the next block // Also a useful trace to have even if suspendDuration is 0 TraceEvent("RebootRequestSuspendingProcess").detail("Duration", req.waitForDuration); if (req.waitForDuration) { flushTraceFileVoid(); setProfilingEnabled(0); g_network->stop(); threadSleep(req.waitForDuration); } if (rebootReq.checkData) { Reference<IAsyncFile> checkFile = wait(IAsyncFileSystem::filesystem()->open(joinPath(folder, validationFilename), IAsyncFile::OPEN_CREATE | IAsyncFile::OPEN_READWRITE, 0600)); wait(checkFile->sync()); } if (g_network->isSimulated()) { TraceEvent("SimulatedReboot").detail("Deletion", rebootReq.deleteData); if (rebootReq.deleteData) { throw please_reboot_delete(); } throw please_reboot(); } else { TraceEvent("ProcessReboot").log(); ASSERT(!rebootReq.deleteData); flushAndExit(0); } } when(SetFailureInjection req = waitNext(interf.clientInterface.setFailureInjection.getFuture())) { if (FLOW_KNOBS->ENABLE_CHAOS_FEATURES) { if (req.diskFailure.present()) { auto diskFailureInjector = DiskFailureInjector::injector(); diskFailureInjector->setDiskFailure(req.diskFailure.get().stallInterval, req.diskFailure.get().stallPeriod, req.diskFailure.get().throttlePeriod); } else if (req.flipBits.present()) { auto bitFlipper = BitFlipper::flipper(); bitFlipper->setBitFlipPercentage(req.flipBits.get().percentBitFlips); } req.reply.send(Void()); } else { req.reply.sendError(client_invalid_operation()); } } when(ProfilerRequest req = waitNext(interf.clientInterface.profiler.getFuture())) { state ProfilerRequest profilerReq = req; // There really isn't a great "filepath sanitizer" or "filepath escape" function available, // thus we instead enforce a different requirement. One can only write to a file that's // beneath the working directory, and we remove the ability to do any symlink or ../.. // tricks by resolving all paths through `abspath` first. try { std::string realLogDir = abspath(SERVER_KNOBS->LOG_DIRECTORY); std::string realOutPath = abspath(realLogDir + "/" + profilerReq.outputFile.toString()); if (realLogDir.size() < realOutPath.size() && strncmp(realLogDir.c_str(), realOutPath.c_str(), realLogDir.size()) == 0) { profilerReq.outputFile = realOutPath; uncancellable(runProfiler(profilerReq)); profilerReq.reply.send(Void()); } else { profilerReq.reply.sendError(client_invalid_operation()); } } catch (Error& e) { profilerReq.reply.sendError(e); } } when(RecruitMasterRequest req = waitNext(interf.master.getFuture())) { LocalLineage _; getCurrentLineage()->modify(&RoleLineage::role) = ProcessClass::ClusterRole::Master; MasterInterface recruited; recruited.locality = locality; recruited.initEndpoints(); startRole(Role::MASTER, recruited.id(), interf.id()); DUMPTOKEN(recruited.waitFailure); DUMPTOKEN(recruited.getCommitVersion); DUMPTOKEN(recruited.getLiveCommittedVersion); DUMPTOKEN(recruited.reportLiveCommittedVersion); DUMPTOKEN(recruited.updateRecoveryData); // printf("Recruited as masterServer\n"); Future<Void> masterProcess = masterServer( recruited, dbInfo, ccInterface, ServerCoordinators(connRecord), req.lifetime, req.forceRecovery); errorForwarders.add( zombie(recruited, forwardError(errors, Role::MASTER, recruited.id(), masterProcess))); req.reply.send(recruited); } when(InitializeDataDistributorRequest req = waitNext(interf.dataDistributor.getFuture())) { LocalLineage _; getCurrentLineage()->modify(&RoleLineage::role) = ProcessClass::ClusterRole::DataDistributor; DataDistributorInterface recruited(locality, req.reqId); recruited.initEndpoints(); if (ddInterf->get().present()) { recruited = ddInterf->get().get(); TEST(true); // Recruited while already a data distributor. } else { startRole(Role::DATA_DISTRIBUTOR, recruited.id(), interf.id()); DUMPTOKEN(recruited.waitFailure); Future<Void> dataDistributorProcess = dataDistributor(recruited, dbInfo); errorForwarders.add(forwardError( errors, Role::DATA_DISTRIBUTOR, recruited.id(), setWhenDoneOrError(dataDistributorProcess, ddInterf, Optional<DataDistributorInterface>()))); ddInterf->set(Optional<DataDistributorInterface>(recruited)); } TraceEvent("DataDistributorReceived", req.reqId).detail("DataDistributorId", recruited.id()); req.reply.send(recruited); } when(InitializeRatekeeperRequest req = waitNext(interf.ratekeeper.getFuture())) { LocalLineage _; getCurrentLineage()->modify(&RoleLineage::role) = ProcessClass::ClusterRole::Ratekeeper; RatekeeperInterface recruited(locality, req.reqId); recruited.initEndpoints(); if (rkInterf->get().present()) { recruited = rkInterf->get().get(); TEST(true); // Recruited while already a ratekeeper. } else { startRole(Role::RATEKEEPER, recruited.id(), interf.id()); DUMPTOKEN(recruited.waitFailure); DUMPTOKEN(recruited.getRateInfo); DUMPTOKEN(recruited.haltRatekeeper); DUMPTOKEN(recruited.reportCommitCostEstimation); Future<Void> ratekeeperProcess = ratekeeper(recruited, dbInfo); errorForwarders.add( forwardError(errors, Role::RATEKEEPER, recruited.id(), setWhenDoneOrError(ratekeeperProcess, rkInterf, Optional<RatekeeperInterface>()))); rkInterf->set(Optional<RatekeeperInterface>(recruited)); } TraceEvent("Ratekeeper_InitRequest", req.reqId).detail("RatekeeperId", recruited.id()); req.reply.send(recruited); } when(InitializeBlobManagerRequest req = waitNext(interf.blobManager.getFuture())) { LocalLineage _; getCurrentLineage()->modify(&RoleLineage::role) = ProcessClass::ClusterRole::BlobManager; BlobManagerInterface recruited(locality, req.reqId); recruited.initEndpoints(); if (bmInterf->get().present()) { recruited = bmInterf->get().get(); TEST(true); // Recruited while already a blob manager. } else { startRole(Role::BLOB_MANAGER, recruited.id(), interf.id()); DUMPTOKEN(recruited.waitFailure); DUMPTOKEN(recruited.haltBlobManager); Future<Void> blobManagerProcess = blobManager(recruited, dbInfo, req.epoch); errorForwarders.add(forwardError( errors, Role::BLOB_MANAGER, recruited.id(), setWhenDoneOrError(blobManagerProcess, bmInterf, Optional<BlobManagerInterface>()))); bmInterf->set(Optional<BlobManagerInterface>(recruited)); } TraceEvent("BlobManagerReceived", req.reqId).detail("BlobManagerId", recruited.id()); req.reply.send(recruited); } when(InitializeBackupRequest req = waitNext(interf.backup.getFuture())) { if (!backupWorkerCache.exists(req.reqId)) { LocalLineage _; getCurrentLineage()->modify(&RoleLineage::role) = ProcessClass::ClusterRole::Backup; BackupInterface recruited(locality); recruited.initEndpoints(); startRole(Role::BACKUP, recruited.id(), interf.id()); DUMPTOKEN(recruited.waitFailure); ReplyPromise<InitializeBackupReply> backupReady = req.reply; backupWorkerCache.set(req.reqId, backupReady.getFuture()); Future<Void> backupProcess = backupWorker(recruited, req, dbInfo); backupProcess = storageCache.removeOnReady(req.reqId, backupProcess); errorForwarders.add(forwardError(errors, Role::BACKUP, recruited.id(), backupProcess)); TraceEvent("BackupInitRequest", req.reqId).detail("BackupId", recruited.id()); InitializeBackupReply reply(recruited, req.backupEpoch); backupReady.send(reply); } else { forwardPromise(req.reply, backupWorkerCache.get(req.reqId)); } } when(InitializeTLogRequest req = waitNext(interf.tLog.getFuture())) { // For now, there's a one-to-one mapping of spill type to TLogVersion. // With future work, a particular version of the TLog can support multiple // different spilling strategies, at which point SpillType will need to be // plumbed down into tLogFn. if (req.logVersion < TLogVersion::MIN_RECRUITABLE) { TraceEvent(SevError, "InitializeTLogInvalidLogVersion") .detail("Version", req.logVersion) .detail("MinRecruitable", TLogVersion::MIN_RECRUITABLE); req.reply.sendError(internal_error()); } LocalLineage _; getCurrentLineage()->modify(&RoleLineage::role) = ProcessClass::ClusterRole::TLog; TLogOptions tLogOptions(req.logVersion, req.spillType); TLogFn tLogFn = tLogFnForOptions(tLogOptions); auto& logData = sharedLogs[SharedLogsKey(tLogOptions, req.storeType)]; logData.requests.send(req); if (!logData.actor.isValid() || logData.actor.isReady()) { UID logId = deterministicRandom()->randomUniqueID(); std::map<std::string, std::string> details; details["ForMaster"] = req.recruitmentID.shortString(); details["StorageEngine"] = req.storeType.toString(); // FIXME: start role for every tlog instance, rather that just for the shared actor, also use a // different role type for the shared actor startRole(Role::SHARED_TRANSACTION_LOG, logId, interf.id(), details); const StringRef prefix = req.logVersion > TLogVersion::V2 ? fileVersionedLogDataPrefix : fileLogDataPrefix; std::string filename = filenameFromId(req.storeType, folder, prefix.toString() + tLogOptions.toPrefix(), logId); IKeyValueStore* data = openKVStore(req.storeType, filename, logId, memoryLimit); const DiskQueueVersion dqv = tLogOptions.version >= TLogVersion::V3 ? DiskQueueVersion::V1 : DiskQueueVersion::V0; IDiskQueue* queue = openDiskQueue( joinPath(folder, fileLogQueuePrefix.toString() + tLogOptions.toPrefix() + logId.toString() + "-"), tlogQueueExtension.toString(), logId, dqv); filesClosed.add(data->onClosed()); filesClosed.add(queue->onClosed()); Future<Void> tLogCore = tLogFn(data, queue, dbInfo, locality, logData.requests, logId, interf.id(), false, Promise<Void>(), Promise<Void>(), folder, degraded, activeSharedTLog); tLogCore = handleIOErrors(tLogCore, data, logId); tLogCore = handleIOErrors(tLogCore, queue, logId); errorForwarders.add(forwardError(errors, Role::SHARED_TRANSACTION_LOG, logId, tLogCore)); logData.actor = tLogCore; logData.uid = logId; } activeSharedTLog->set(logData.uid); } when(InitializeStorageRequest req = waitNext(interf.storage.getFuture())) { // We want to prevent double recruiting on a worker unless we try to recruit something // with a different storage engine (otherwise storage migration won't work for certain // configuration). Additionally we also need to allow double recruitment for seed servers. // The reason for this is that a storage will only remove itself if after it was able // to read the system key space. But if recovery fails right after a `configure new ...` // was run it won't be able to do so. if (!storageCache.exists(req.reqId) && (std::all_of(runningStorages.begin(), runningStorages.end(), [&req](const auto& p) { return p.second != req.storeType; }) || req.seedTag != invalidTag)) { ASSERT(req.clusterId.isValid()); LocalLineage _; getCurrentLineage()->modify(&RoleLineage::role) = ProcessClass::ClusterRole::Storage; bool isTss = req.tssPairIDAndVersion.present(); StorageServerInterface recruited(req.interfaceId); recruited.locality = locality; recruited.tssPairID = isTss ? req.tssPairIDAndVersion.get().first : Optional<UID>(); recruited.initEndpoints(); std::map<std::string, std::string> details; details["StorageEngine"] = req.storeType.toString(); details["IsTSS"] = std::to_string(isTss); Role ssRole = isTss ? Role::TESTING_STORAGE_SERVER : Role::STORAGE_SERVER; startRole(ssRole, recruited.id(), interf.id(), details); DUMPTOKEN(recruited.getValue); DUMPTOKEN(recruited.getKey); DUMPTOKEN(recruited.getKeyValues); DUMPTOKEN(recruited.getShardState); DUMPTOKEN(recruited.waitMetrics); DUMPTOKEN(recruited.splitMetrics); DUMPTOKEN(recruited.getReadHotRanges); DUMPTOKEN(recruited.getRangeSplitPoints); DUMPTOKEN(recruited.getStorageMetrics); DUMPTOKEN(recruited.waitFailure); DUMPTOKEN(recruited.getQueuingMetrics); DUMPTOKEN(recruited.getKeyValueStoreType); DUMPTOKEN(recruited.watchValue); DUMPTOKEN(recruited.getKeyValuesStream); DUMPTOKEN(recruited.getKeyValuesAndFlatMap); // printf("Recruited as storageServer\n"); std::string filename = filenameFromId(req.storeType, folder, isTss ? testingStoragePrefix.toString() : fileStoragePrefix.toString(), recruited.id()); IKeyValueStore* data = openKVStore(req.storeType, filename, recruited.id(), memoryLimit); Future<Void> kvClosed = data->onClosed(); filesClosed.add(kvClosed); ReplyPromise<InitializeStorageReply> storageReady = req.reply; storageCache.set(req.reqId, storageReady.getFuture()); Future<Void> s = storageServer(data, recruited, req.seedTag, req.clusterId, isTss ? req.tssPairIDAndVersion.get().second : 0, storageReady, dbInfo, folder); s = handleIOErrors(s, data, recruited.id(), kvClosed); s = storageCache.removeOnReady(req.reqId, s); s = storageServerRollbackRebooter(&runningStorages, s, req.storeType, filename, recruited.id(), recruited.locality, isTss, dbInfo, folder, &filesClosed, memoryLimit, data); errorForwarders.add(forwardError(errors, ssRole, recruited.id(), s)); } else if (storageCache.exists(req.reqId)) { forwardPromise(req.reply, storageCache.get(req.reqId)); } else { TraceEvent("AttemptedDoubleRecruitement", interf.id()).detail("ForRole", "StorageServer"); errorForwarders.add(map(delay(0.5), [reply = req.reply](Void) { reply.sendError(recruitment_failed()); return Void(); })); } } when(InitializeBlobWorkerRequest req = waitNext(interf.blobWorker.getFuture())) { BlobWorkerInterface recruited(locality, req.interfaceId); recruited.initEndpoints(); startRole(Role::BLOB_WORKER, recruited.id(), interf.id()); ReplyPromise<InitializeBlobWorkerReply> blobWorkerReady = req.reply; Future<Void> bw = blobWorker(recruited, blobWorkerReady, dbInfo); errorForwarders.add(forwardError(errors, Role::BLOB_WORKER, recruited.id(), bw)); } when(InitializeCommitProxyRequest req = waitNext(interf.commitProxy.getFuture())) { LocalLineage _; getCurrentLineage()->modify(&RoleLineage::role) = ProcessClass::ClusterRole::CommitProxy; CommitProxyInterface recruited; recruited.processId = locality.processId(); recruited.provisional = false; recruited.initEndpoints(); std::map<std::string, std::string> details; details["ForMaster"] = req.master.id().shortString(); startRole(Role::COMMIT_PROXY, recruited.id(), interf.id(), details); DUMPTOKEN(recruited.commit); DUMPTOKEN(recruited.getConsistentReadVersion); DUMPTOKEN(recruited.getKeyServersLocations); DUMPTOKEN(recruited.getStorageServerRejoinInfo); DUMPTOKEN(recruited.waitFailure); DUMPTOKEN(recruited.txnState); // printf("Recruited as commitProxyServer\n"); errorForwarders.add(zombie(recruited, forwardError(errors, Role::COMMIT_PROXY, recruited.id(), commitProxyServer(recruited, req, dbInfo, whitelistBinPaths)))); req.reply.send(recruited); } when(InitializeGrvProxyRequest req = waitNext(interf.grvProxy.getFuture())) { LocalLineage _; getCurrentLineage()->modify(&RoleLineage::role) = ProcessClass::ClusterRole::GrvProxy; GrvProxyInterface recruited; recruited.processId = locality.processId(); recruited.provisional = false; recruited.initEndpoints(); std::map<std::string, std::string> details; details["ForMaster"] = req.master.id().shortString(); startRole(Role::GRV_PROXY, recruited.id(), interf.id(), details); DUMPTOKEN(recruited.getConsistentReadVersion); DUMPTOKEN(recruited.waitFailure); DUMPTOKEN(recruited.getHealthMetrics); // printf("Recruited as grvProxyServer\n"); errorForwarders.add(zombie( recruited, forwardError(errors, Role::GRV_PROXY, recruited.id(), grvProxyServer(recruited, req, dbInfo)))); req.reply.send(recruited); } when(InitializeResolverRequest req = waitNext(interf.resolver.getFuture())) { LocalLineage _; getCurrentLineage()->modify(&RoleLineage::role) = ProcessClass::ClusterRole::Resolver; ResolverInterface recruited; recruited.locality = locality; recruited.initEndpoints(); std::map<std::string, std::string> details; startRole(Role::RESOLVER, recruited.id(), interf.id(), details); DUMPTOKEN(recruited.resolve); DUMPTOKEN(recruited.metrics); DUMPTOKEN(recruited.split); DUMPTOKEN(recruited.waitFailure); errorForwarders.add(zombie( recruited, forwardError(errors, Role::RESOLVER, recruited.id(), resolver(recruited, req, dbInfo)))); req.reply.send(recruited); } when(InitializeLogRouterRequest req = waitNext(interf.logRouter.getFuture())) { LocalLineage _; getCurrentLineage()->modify(&RoleLineage::role) = ProcessClass::ClusterRole::LogRouter; TLogInterface recruited(locality); recruited.initEndpoints(); std::map<std::string, std::string> details; startRole(Role::LOG_ROUTER, recruited.id(), interf.id(), details); DUMPTOKEN(recruited.peekMessages); DUMPTOKEN(recruited.peekStreamMessages); DUMPTOKEN(recruited.popMessages); DUMPTOKEN(recruited.commit); DUMPTOKEN(recruited.lock); DUMPTOKEN(recruited.getQueuingMetrics); DUMPTOKEN(recruited.confirmRunning); DUMPTOKEN(recruited.waitFailure); DUMPTOKEN(recruited.recoveryFinished); DUMPTOKEN(recruited.disablePopRequest); DUMPTOKEN(recruited.enablePopRequest); DUMPTOKEN(recruited.snapRequest); errorForwarders.add( zombie(recruited, forwardError(errors, Role::LOG_ROUTER, recruited.id(), logRouter(recruited, req, dbInfo)))); req.reply.send(recruited); } when(CoordinationPingMessage m = waitNext(interf.coordinationPing.getFuture())) { TraceEvent("CoordinationPing", interf.id()) .detail("CCID", m.clusterControllerId) .detail("TimeStep", m.timeStep); } when(SetMetricsLogRateRequest req = waitNext(interf.setMetricsRate.getFuture())) { TraceEvent("LoggingRateChange", interf.id()) .detail("OldDelay", loggingDelay) .detail("NewLogPS", req.metricsLogsPerSecond); if (req.metricsLogsPerSecond != 0) { loggingDelay = 1.0 / req.metricsLogsPerSecond; loggingTrigger = Void(); } } when(EventLogRequest req = waitNext(interf.eventLogRequest.getFuture())) { TraceEventFields e; if (req.getLastError) e = latestEventCache.getLatestError(); else e = latestEventCache.get(req.eventName.toString()); req.reply.send(e); } when(TraceBatchDumpRequest req = waitNext(interf.traceBatchDumpRequest.getFuture())) { g_traceBatch.dump(); req.reply.send(Void()); } when(DiskStoreRequest req = waitNext(interf.diskStoreRequest.getFuture())) { Standalone<VectorRef<UID>> ids; for (DiskStore d : getDiskStores(folder)) { bool included = true; if (!req.includePartialStores) { if (d.storeType == KeyValueStoreType::SSD_BTREE_V1) { included = fileExists(d.filename + ".fdb-wal"); } else if (d.storeType == KeyValueStoreType::SSD_BTREE_V2) { included = fileExists(d.filename + ".sqlite-wal"); } else if (d.storeType == KeyValueStoreType::SSD_REDWOOD_V1) { included = fileExists(d.filename + "0.pagerlog") && fileExists(d.filename + "1.pagerlog"); } else if (d.storeType == KeyValueStoreType::SSD_ROCKSDB_V1) { included = fileExists(joinPath(d.filename, "CURRENT")) && fileExists(joinPath(d.filename, "IDENTITY")); } else if (d.storeType == KeyValueStoreType::MEMORY) { included = fileExists(d.filename + "1.fdq"); } else { ASSERT(d.storeType == KeyValueStoreType::MEMORY_RADIXTREE); included = fileExists(d.filename + "1.fdr"); } if (d.storedComponent == DiskStore::COMPONENT::TLogData && included) { included = false; // The previous code assumed that d.filename is a filename. But that is not true. // d.filename is a path. Removing a prefix and adding a new one just makes a broken // directory name. So fileExists would always return false. // Weirdly, this doesn't break anything, as tested by taking a clean check of FDB, // setting included to false always, and then running correctness. So I'm just // improving the situation by actually marking it as broken. // FIXME: this whole thing /* std::string logDataBasename; StringRef filename = d.filename; if (filename.startsWith(fileLogDataPrefix)) { logDataBasename = fileLogQueuePrefix.toString() + d.filename.substr(fileLogDataPrefix.size()); } else { StringRef optionsString = filename.removePrefix(fileVersionedLogDataPrefix).eat("-"); logDataBasename = fileLogQueuePrefix.toString() + optionsString.toString() + "-"; } TraceEvent("DiskStoreRequest").detail("FilenameBasename", logDataBasename); if (fileExists(logDataBasename + "0.fdq") && fileExists(logDataBasename + "1.fdq")) { included = true; } */ } } if (included) { ids.push_back(ids.arena(), d.storeID); } } req.reply.send(ids); } when(wait(loggingTrigger)) { systemMonitor(); loggingTrigger = delay(loggingDelay, TaskPriority::FlushTrace); } when(state WorkerSnapRequest snapReq = waitNext(interf.workerSnapReq.getFuture())) { Standalone<StringRef> snapFolder = StringRef(folder); if (snapReq.role.toString() == "coord") { snapFolder = coordFolder; } errorForwarders.add(workerSnapCreate(snapReq, snapFolder)); } when(wait(errorForwarders.getResult())) {} when(wait(handleErrors)) {} } } catch (Error& err) { // Make sure actors are cancelled before "recovery" promises are destructed. for (auto f : recoveries) f.cancel(); state Error e = err; bool ok = e.code() == error_code_please_reboot || e.code() == error_code_actor_cancelled || e.code() == error_code_please_reboot_delete; endRole(Role::WORKER, interf.id(), "WorkerError", ok, e); errorForwarders.clear(false); sharedLogs.clear(); if (e.code() != error_code_actor_cancelled) { // We get cancelled e.g. when an entire simulation times out, but in that case // we won't be restarted and don't need to wait for shutdown stopping.send(Void()); wait(filesClosed.getResult()); // Wait for complete shutdown of KV stores wait(delay(0.0)); // Unwind the callstack to make sure that IAsyncFile references are all gone TraceEvent(SevInfo, "WorkerShutdownComplete", interf.id()); } throw e; } } ACTOR Future<Void> extractClusterInterface(Reference<AsyncVar<Optional<ClusterControllerFullInterface>> const> in, Reference<AsyncVar<Optional<ClusterInterface>>> out) { loop { if (in->get().present()) out->set(in->get().get().clientInterface); else out->set(Optional<ClusterInterface>()); wait(in->onChange()); } } static std::set<int> const& normalWorkerErrors() { static std::set<int> s; if (s.empty()) { s.insert(error_code_please_reboot); s.insert(error_code_please_reboot_delete); } return s; } ACTOR Future<Void> fileNotFoundToNever(Future<Void> f) { try { wait(f); return Void(); } catch (Error& e) { if (e.code() == error_code_file_not_found) { TraceEvent(SevWarn, "ClusterCoordinatorFailed").error(e); return Never(); } throw; } } ACTOR Future<Void> printTimeout() { wait(delay(5)); if (!g_network->isSimulated()) { fprintf(stderr, "Warning: FDBD has not joined the cluster after 5 seconds.\n"); fprintf(stderr, " Check configuration and availability using the 'status' command with the fdbcli\n"); } return Void(); } ACTOR Future<Void> printOnFirstConnected(Reference<AsyncVar<Optional<ClusterInterface>> const> ci) { state Future<Void> timeoutFuture = printTimeout(); loop { choose { when(wait(ci->get().present() ? IFailureMonitor::failureMonitor().onStateEqual( ci->get().get().openDatabase.getEndpoint(), FailureStatus(false)) : Never())) { printf("FDBD joined cluster.\n"); TraceEvent("FDBDConnected").log(); return Void(); } when(wait(ci->onChange())) {} } } } ClusterControllerPriorityInfo getCCPriorityInfo(std::string filePath, ProcessClass processClass) { if (!fileExists(filePath)) return ClusterControllerPriorityInfo(ProcessClass(processClass.classType(), ProcessClass::CommandLineSource) .machineClassFitness(ProcessClass::ClusterController), false, ClusterControllerPriorityInfo::FitnessUnknown); std::string contents(readFileBytes(filePath, 1000)); BinaryReader br(StringRef(contents), IncludeVersion()); ClusterControllerPriorityInfo priorityInfo( ProcessClass::UnsetFit, false, ClusterControllerPriorityInfo::FitnessUnknown); br >> priorityInfo; if (!br.empty()) { if (g_network->isSimulated()) { ASSERT(false); } else { TraceEvent(SevWarnAlways, "FitnessFileCorrupted").detail("filePath", filePath); return ClusterControllerPriorityInfo(ProcessClass(processClass.classType(), ProcessClass::CommandLineSource) .machineClassFitness(ProcessClass::ClusterController), false, ClusterControllerPriorityInfo::FitnessUnknown); } } return priorityInfo; } ACTOR Future<Void> monitorAndWriteCCPriorityInfo(std::string filePath, Reference<AsyncVar<ClusterControllerPriorityInfo>> asyncPriorityInfo) { loop { wait(asyncPriorityInfo->onChange()); std::string contents(BinaryWriter::toValue(asyncPriorityInfo->get(), IncludeVersion(ProtocolVersion::withClusterControllerPriorityInfo())) .toString()); atomicReplace(filePath, contents, false); } } ACTOR Future<UID> createAndLockProcessIdFile(std::string folder) { state UID processIDUid; platform::createDirectory(folder); loop { try { state std::string lockFilePath = joinPath(folder, "processId"); state ErrorOr<Reference<IAsyncFile>> lockFile = wait(errorOr(IAsyncFileSystem::filesystem(g_network)->open( lockFilePath, IAsyncFile::OPEN_READWRITE | IAsyncFile::OPEN_LOCK, 0600))); if (lockFile.isError() && lockFile.getError().code() == error_code_file_not_found && !fileExists(lockFilePath)) { Reference<IAsyncFile> _lockFile = wait(IAsyncFileSystem::filesystem()->open( lockFilePath, IAsyncFile::OPEN_ATOMIC_WRITE_AND_CREATE | IAsyncFile::OPEN_CREATE | IAsyncFile::OPEN_LOCK | IAsyncFile::OPEN_READWRITE, 0600)); lockFile = _lockFile; processIDUid = deterministicRandom()->randomUniqueID(); BinaryWriter wr(IncludeVersion(ProtocolVersion::withProcessIDFile())); wr << processIDUid; wait(lockFile.get()->write(wr.getData(), wr.getLength(), 0)); wait(lockFile.get()->sync()); } else { if (lockFile.isError()) throw lockFile.getError(); // If we've failed to open the file, throw an exception int64_t fileSize = wait(lockFile.get()->size()); state Key fileData = makeString(fileSize); wait(success(lockFile.get()->read(mutateString(fileData), fileSize, 0))); try { processIDUid = BinaryReader::fromStringRef<UID>(fileData, IncludeVersion()); return processIDUid; } catch (Error& e) { if (!g_network->isSimulated()) { throw; } lockFile = ErrorOr<Reference<IAsyncFile>>(); wait(IAsyncFileSystem::filesystem()->deleteFile(lockFilePath, true)); } } } catch (Error& e) { if (e.code() == error_code_actor_cancelled) { throw; } if (!e.isInjectedFault()) { fprintf(stderr, "ERROR: error creating or opening process id file `%s'.\n", joinPath(folder, "processId").c_str()); } TraceEvent(SevError, "OpenProcessIdError").error(e); throw; } } } ACTOR Future<MonitorLeaderInfo> monitorLeaderWithDelayedCandidacyImplOneGeneration( Reference<IClusterConnectionRecord> connRecord, Reference<AsyncVar<Value>> result, MonitorLeaderInfo info) { state ClusterConnectionString ccf = info.intermediateConnRecord->getConnectionString(); state std::vector<NetworkAddress> addrs = ccf.coordinators(); state ElectionResultRequest request; state int index = 0; state int successIndex = 0; request.key = ccf.clusterKey(); request.coordinators = ccf.coordinators(); deterministicRandom()->randomShuffle(addrs); loop { LeaderElectionRegInterface interf(addrs[index]); request.reply = ReplyPromise<Optional<LeaderInfo>>(); ErrorOr<Optional<LeaderInfo>> leader = wait(interf.electionResult.tryGetReply(request)); if (leader.present()) { if (leader.get().present()) { if (leader.get().get().forward) { info.intermediateConnRecord = connRecord->makeIntermediateRecord( ClusterConnectionString(leader.get().get().serializedInfo.toString())); return info; } if (connRecord != info.intermediateConnRecord) { if (!info.hasConnected) { TraceEvent(SevWarnAlways, "IncorrectClusterFileContentsAtConnection") .detail("ClusterFile", connRecord->toString()) .detail("StoredConnectionString", connRecord->getConnectionString().toString()) .detail("CurrentConnectionString", info.intermediateConnRecord->getConnectionString().toString()); } connRecord->setConnectionString(info.intermediateConnRecord->getConnectionString()); info.intermediateConnRecord = connRecord; } info.hasConnected = true; connRecord->notifyConnected(); request.knownLeader = leader.get().get().changeID; ClusterControllerPriorityInfo info = leader.get().get().getPriorityInfo(); if (leader.get().get().serializedInfo.size() && !info.isExcluded && (info.dcFitness == ClusterControllerPriorityInfo::FitnessPrimary || info.dcFitness == ClusterControllerPriorityInfo::FitnessPreferred || info.dcFitness == ClusterControllerPriorityInfo::FitnessUnknown)) { result->set(leader.get().get().serializedInfo); } else { result->set(Value()); } } successIndex = index; } else { index = (index + 1) % addrs.size(); if (index == successIndex) { wait(delay(CLIENT_KNOBS->COORDINATOR_RECONNECTION_DELAY)); } } } } ACTOR Future<Void> monitorLeaderWithDelayedCandidacyImplInternal(Reference<IClusterConnectionRecord> connRecord, Reference<AsyncVar<Value>> outSerializedLeaderInfo) { state MonitorLeaderInfo info(connRecord); loop { MonitorLeaderInfo _info = wait(monitorLeaderWithDelayedCandidacyImplOneGeneration(connRecord, outSerializedLeaderInfo, info)); info = _info; } } template <class LeaderInterface> Future<Void> monitorLeaderWithDelayedCandidacyImpl( Reference<IClusterConnectionRecord> const& connRecord, Reference<AsyncVar<Optional<LeaderInterface>>> const& outKnownLeader) { LeaderDeserializer<LeaderInterface> deserializer; auto serializedInfo = makeReference<AsyncVar<Value>>(); Future<Void> m = monitorLeaderWithDelayedCandidacyImplInternal(connRecord, serializedInfo); return m || deserializer(serializedInfo, outKnownLeader); } ACTOR Future<Void> monitorLeaderWithDelayedCandidacy( Reference<IClusterConnectionRecord> connRecord, Reference<AsyncVar<Optional<ClusterControllerFullInterface>>> currentCC, Reference<AsyncVar<ClusterControllerPriorityInfo>> asyncPriorityInfo, Future<Void> recoveredDiskFiles, LocalityData locality, Reference<AsyncVar<ServerDBInfo>> dbInfo, ConfigDBType configDBType) { state Future<Void> monitor = monitorLeaderWithDelayedCandidacyImpl(connRecord, currentCC); state Future<Void> timeout; wait(recoveredDiskFiles); loop { if (currentCC->get().present() && dbInfo->get().clusterInterface == currentCC->get().get() && IFailureMonitor::failureMonitor() .getState(currentCC->get().get().registerWorker.getEndpoint()) .isAvailable()) { timeout = Future<Void>(); } else if (!timeout.isValid()) { timeout = delay(SERVER_KNOBS->MIN_DELAY_CC_WORST_FIT_CANDIDACY_SECONDS + (deterministicRandom()->random01() * (SERVER_KNOBS->MAX_DELAY_CC_WORST_FIT_CANDIDACY_SECONDS - SERVER_KNOBS->MIN_DELAY_CC_WORST_FIT_CANDIDACY_SECONDS))); } choose { when(wait(currentCC->onChange())) {} when(wait(dbInfo->onChange())) {} when(wait(currentCC->get().present() ? IFailureMonitor::failureMonitor().onStateChanged( currentCC->get().get().registerWorker.getEndpoint()) : Never())) {} when(wait(timeout.isValid() ? timeout : Never())) { monitor.cancel(); wait(clusterController( connRecord, currentCC, asyncPriorityInfo, recoveredDiskFiles, locality, configDBType)); return Void(); } } } } extern void setupStackSignal(); ACTOR Future<Void> serveProtocolInfo() { state RequestStream<ProtocolInfoRequest> protocolInfo( PeerCompatibilityPolicy{ RequirePeer::AtLeast, ProtocolVersion::withStableInterfaces() }); protocolInfo.makeWellKnownEndpoint(WLTOKEN_PROTOCOL_INFO, TaskPriority::DefaultEndpoint); loop { state ProtocolInfoRequest req = waitNext(protocolInfo.getFuture()); req.reply.send(ProtocolInfoReply{ g_network->protocolVersion() }); } } // Handles requests from ProcessInterface, an interface meant for direct // communication between the client and FDB processes. ACTOR Future<Void> serveProcess() { state ProcessInterface process; process.getInterface.makeWellKnownEndpoint(WLTOKEN_PROCESS, TaskPriority::DefaultEndpoint); loop { choose { when(GetProcessInterfaceRequest req = waitNext(process.getInterface.getFuture())) { req.reply.send(process); } when(ActorLineageRequest req = waitNext(process.actorLineage.getFuture())) { state SampleCollection sampleCollector; auto samples = sampleCollector->get(req.timeStart, req.timeEnd); std::vector<SerializedSample> serializedSamples; for (const auto& samplePtr : samples) { auto serialized = SerializedSample{ .time = samplePtr->time }; for (const auto& [waitState, pair] : samplePtr->data) { if (waitState >= req.waitStateStart && waitState <= req.waitStateEnd) { serialized.data[waitState] = std::string(pair.first, pair.second); } } serializedSamples.push_back(std::move(serialized)); } ActorLineageReply reply{ serializedSamples }; req.reply.send(reply); } } } } ACTOR Future<Void> fdbd(Reference<IClusterConnectionRecord> connRecord, LocalityData localities, ProcessClass processClass, std::string dataFolder, std::string coordFolder, int64_t memoryLimit, std::string metricsConnFile, std::string metricsPrefix, int64_t memoryProfileThreshold, std::string whitelistBinPaths, std::string configPath, std::map<std::string, std::string> manualKnobOverrides, ConfigDBType configDBType) { state std::vector<Future<Void>> actors; state Promise<Void> recoveredDiskFiles; state Reference<LocalConfiguration> localConfig = makeReference<LocalConfiguration>(dataFolder, configPath, manualKnobOverrides); // setupStackSignal(); getCurrentLineage()->modify(&RoleLineage::role) = ProcessClass::Worker; // FIXME: Initializing here causes simulation issues, these must be fixed /* if (configDBType != ConfigDBType::DISABLED) { wait(localConfig->initialize()); } */ actors.push_back(serveProtocolInfo()); actors.push_back(serveProcess()); try { ServerCoordinators coordinators(connRecord); if (g_network->isSimulated()) { whitelistBinPaths = ",, random_path, /bin/snap_create.sh,,"; } TraceEvent("StartingFDBD") .detail("ZoneID", localities.zoneId()) .detail("MachineId", localities.machineId()) .detail("DiskPath", dataFolder) .detail("CoordPath", coordFolder) .detail("WhiteListBinPath", whitelistBinPaths); // SOMEDAY: start the services on the machine in a staggered fashion in simulation? // Endpoints should be registered first before any process trying to connect to it. // So coordinationServer actor should be the first one executed before any other. if (coordFolder.size()) { // SOMEDAY: remove the fileNotFound wrapper and make DiskQueue construction safe from errors setting up // their files actors.push_back(fileNotFoundToNever(coordinationServer(coordFolder, coordinators.ccr, configDBType))); } state UID processIDUid = wait(createAndLockProcessIdFile(dataFolder)); localities.set(LocalityData::keyProcessId, processIDUid.toString()); // Only one process can execute on a dataFolder from this point onwards std::string fitnessFilePath = joinPath(dataFolder, "fitness"); auto cc = makeReference<AsyncVar<Optional<ClusterControllerFullInterface>>>(); auto ci = makeReference<AsyncVar<Optional<ClusterInterface>>>(); auto asyncPriorityInfo = makeReference<AsyncVar<ClusterControllerPriorityInfo>>(getCCPriorityInfo(fitnessFilePath, processClass)); auto dbInfo = makeReference<AsyncVar<ServerDBInfo>>(); actors.push_back(reportErrors(monitorAndWriteCCPriorityInfo(fitnessFilePath, asyncPriorityInfo), "MonitorAndWriteCCPriorityInfo")); if (processClass.machineClassFitness(ProcessClass::ClusterController) == ProcessClass::NeverAssign) { actors.push_back(reportErrors(monitorLeader(connRecord, cc), "ClusterController")); } else if (processClass.machineClassFitness(ProcessClass::ClusterController) == ProcessClass::WorstFit && SERVER_KNOBS->MAX_DELAY_CC_WORST_FIT_CANDIDACY_SECONDS > 0) { actors.push_back(reportErrors(monitorLeaderWithDelayedCandidacy(connRecord, cc, asyncPriorityInfo, recoveredDiskFiles.getFuture(), localities, dbInfo, configDBType), "ClusterController")); } else { actors.push_back(reportErrors( clusterController( connRecord, cc, asyncPriorityInfo, recoveredDiskFiles.getFuture(), localities, configDBType), "ClusterController")); } actors.push_back(reportErrors(extractClusterInterface(cc, ci), "ExtractClusterInterface")); actors.push_back(reportErrorsExcept(workerServer(connRecord, cc, localities, asyncPriorityInfo, processClass, dataFolder, memoryLimit, metricsConnFile, metricsPrefix, recoveredDiskFiles, memoryProfileThreshold, coordFolder, whitelistBinPaths, dbInfo, configDBType, localConfig), "WorkerServer", UID(), &normalWorkerErrors())); state Future<Void> firstConnect = reportErrors(printOnFirstConnected(ci), "ClusterFirstConnectedError"); wait(quorum(actors, 1)); ASSERT(false); // None of these actors should terminate normally throw internal_error(); } catch (Error& e) { // Make sure actors are cancelled before recoveredDiskFiles is destructed. // Otherwise, these actors may get a broken promise error. for (auto f : actors) f.cancel(); Error err = checkIOTimeout(e); throw err; } } const Role Role::WORKER("Worker", "WK", false); const Role Role::STORAGE_SERVER("StorageServer", "SS"); const Role Role::TESTING_STORAGE_SERVER("TestingStorageServer", "ST"); const Role Role::TRANSACTION_LOG("TLog", "TL"); const Role Role::SHARED_TRANSACTION_LOG("SharedTLog", "SL", false); const Role Role::COMMIT_PROXY("CommitProxyServer", "CP"); const Role Role::GRV_PROXY("GrvProxyServer", "GP"); const Role Role::MASTER("MasterServer", "MS"); const Role Role::RESOLVER("Resolver", "RV"); const Role Role::CLUSTER_CONTROLLER("ClusterController", "CC"); const Role Role::TESTER("Tester", "TS"); const Role Role::LOG_ROUTER("LogRouter", "LR"); const Role Role::DATA_DISTRIBUTOR("DataDistributor", "DD"); const Role Role::RATEKEEPER("Ratekeeper", "RK"); const Role Role::BLOB_MANAGER("BlobManager", "BM"); const Role Role::BLOB_WORKER("BlobWorker", "BW"); const Role Role::STORAGE_CACHE("StorageCache", "SC"); const Role Role::COORDINATOR("Coordinator", "CD"); const Role Role::BACKUP("Backup", "BK");
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: Annotation.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "Annotation.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace atom { namespace proto { namespace { const ::google::protobuf::Descriptor* Annotation_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* Annotation_reflection_ = NULL; } // namespace void protobuf_AssignDesc_Annotation_2eproto() { protobuf_AddDesc_Annotation_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "Annotation.proto"); GOOGLE_CHECK(file != NULL); Annotation_descriptor_ = file->message_type(0); static const int Annotation_offsets_[4] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Annotation, name_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Annotation, text_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Annotation, world_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Annotation, initialvisibility_), }; Annotation_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( Annotation_descriptor_, Annotation::default_instance_, Annotation_offsets_, -1, -1, -1, sizeof(Annotation), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Annotation, _internal_metadata_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Annotation, _is_default_instance_)); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_Annotation_2eproto); } void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( Annotation_descriptor_, &Annotation::default_instance()); } } // namespace void protobuf_ShutdownFile_Annotation_2eproto() { delete Annotation::default_instance_; delete Annotation_reflection_; } void protobuf_AddDesc_Annotation_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::atom::proto::protobuf_AddDesc_Matrix_2eproto(); ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\020Annotation.proto\022\natom.proto\032\014Matrix.p" "roto\"f\n\nAnnotation\022\014\n\004Name\030\001 \001(\t\022\014\n\004Text" "\030\002 \001(\t\022!\n\005World\030\003 \001(\0132\022.atom.proto.Matri" "x\022\031\n\021InitialVisibility\030\004 \001(\010b\006proto3", 156); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "Annotation.proto", &protobuf_RegisterTypes); Annotation::default_instance_ = new Annotation(); Annotation::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_Annotation_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_Annotation_2eproto { StaticDescriptorInitializer_Annotation_2eproto() { protobuf_AddDesc_Annotation_2eproto(); } } static_descriptor_initializer_Annotation_2eproto_; namespace { static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD; static void MergeFromFail(int line) { GOOGLE_CHECK(false) << __FILE__ << ":" << line; } } // namespace // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Annotation::kNameFieldNumber; const int Annotation::kTextFieldNumber; const int Annotation::kWorldFieldNumber; const int Annotation::kInitialVisibilityFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Annotation::Annotation() : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); // @@protoc_insertion_point(constructor:atom.proto.Annotation) } void Annotation::InitAsDefaultInstance() { _is_default_instance_ = true; world_ = const_cast< ::atom::proto::Matrix*>(&::atom::proto::Matrix::default_instance()); } Annotation::Annotation(const Annotation& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:atom.proto.Annotation) } void Annotation::SharedCtor() { _is_default_instance_ = false; ::google::protobuf::internal::GetEmptyString(); _cached_size_ = 0; name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); text_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); world_ = NULL; initialvisibility_ = false; } Annotation::~Annotation() { // @@protoc_insertion_point(destructor:atom.proto.Annotation) SharedDtor(); } void Annotation::SharedDtor() { name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); text_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (this != default_instance_) { delete world_; } } void Annotation::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Annotation::descriptor() { protobuf_AssignDescriptorsOnce(); return Annotation_descriptor_; } const Annotation& Annotation::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_Annotation_2eproto(); return *default_instance_; } Annotation* Annotation::default_instance_ = NULL; Annotation* Annotation::New(::google::protobuf::Arena* arena) const { Annotation* n = new Annotation; if (arena != NULL) { arena->Own(n); } return n; } void Annotation::Clear() { name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); text_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (GetArenaNoVirtual() == NULL && world_ != NULL) delete world_; world_ = NULL; initialvisibility_ = false; } bool Annotation::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:atom.proto.Annotation) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional string Name = 1; case 1: { if (tag == 10) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_name())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->name().data(), this->name().length(), ::google::protobuf::internal::WireFormatLite::PARSE, "atom.proto.Annotation.Name")); } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_Text; break; } // optional string Text = 2; case 2: { if (tag == 18) { parse_Text: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_text())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->text().data(), this->text().length(), ::google::protobuf::internal::WireFormatLite::PARSE, "atom.proto.Annotation.Text")); } else { goto handle_unusual; } if (input->ExpectTag(26)) goto parse_World; break; } // optional .atom.proto.Matrix World = 3; case 3: { if (tag == 26) { parse_World: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_world())); } else { goto handle_unusual; } if (input->ExpectTag(32)) goto parse_InitialVisibility; break; } // optional bool InitialVisibility = 4; case 4: { if (tag == 32) { parse_InitialVisibility: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &initialvisibility_))); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); break; } } } success: // @@protoc_insertion_point(parse_success:atom.proto.Annotation) return true; failure: // @@protoc_insertion_point(parse_failure:atom.proto.Annotation) return false; #undef DO_ } void Annotation::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:atom.proto.Annotation) // optional string Name = 1; if (this->name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->name().data(), this->name().length(), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "atom.proto.Annotation.Name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } // optional string Text = 2; if (this->text().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->text().data(), this->text().length(), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "atom.proto.Annotation.Text"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->text(), output); } // optional .atom.proto.Matrix World = 3; if (this->has_world()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, *this->world_, output); } // optional bool InitialVisibility = 4; if (this->initialvisibility() != 0) { ::google::protobuf::internal::WireFormatLite::WriteBool(4, this->initialvisibility(), output); } // @@protoc_insertion_point(serialize_end:atom.proto.Annotation) } ::google::protobuf::uint8* Annotation::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:atom.proto.Annotation) // optional string Name = 1; if (this->name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->name().data(), this->name().length(), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "atom.proto.Annotation.Name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } // optional string Text = 2; if (this->text().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->text().data(), this->text().length(), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "atom.proto.Annotation.Text"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->text(), target); } // optional .atom.proto.Matrix World = 3; if (this->has_world()) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 3, *this->world_, target); } // optional bool InitialVisibility = 4; if (this->initialvisibility() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(4, this->initialvisibility(), target); } // @@protoc_insertion_point(serialize_to_array_end:atom.proto.Annotation) return target; } int Annotation::ByteSize() const { int total_size = 0; // optional string Name = 1; if (this->name().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->name()); } // optional string Text = 2; if (this->text().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->text()); } // optional .atom.proto.Matrix World = 3; if (this->has_world()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->world_); } // optional bool InitialVisibility = 4; if (this->initialvisibility() != 0) { total_size += 1 + 1; } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Annotation::MergeFrom(const ::google::protobuf::Message& from) { if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); const Annotation* source = ::google::protobuf::internal::DynamicCastToGenerated<const Annotation>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void Annotation::MergeFrom(const Annotation& from) { if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); if (from.name().size() > 0) { name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); } if (from.text().size() > 0) { text_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.text_); } if (from.has_world()) { mutable_world()->::atom::proto::Matrix::MergeFrom(from.world()); } if (from.initialvisibility() != 0) { set_initialvisibility(from.initialvisibility()); } } void Annotation::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void Annotation::CopyFrom(const Annotation& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool Annotation::IsInitialized() const { return true; } void Annotation::Swap(Annotation* other) { if (other == this) return; InternalSwap(other); } void Annotation::InternalSwap(Annotation* other) { name_.Swap(&other->name_); text_.Swap(&other->text_); std::swap(world_, other->world_); std::swap(initialvisibility_, other->initialvisibility_); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Annotation::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = Annotation_descriptor_; metadata.reflection = Annotation_reflection_; return metadata; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // Annotation // optional string Name = 1; void Annotation::clear_name() { name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } const ::std::string& Annotation::name() const { // @@protoc_insertion_point(field_get:atom.proto.Annotation.Name) return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Annotation::set_name(const ::std::string& value) { name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:atom.proto.Annotation.Name) } void Annotation::set_name(const char* value) { name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:atom.proto.Annotation.Name) } void Annotation::set_name(const char* value, size_t size) { name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:atom.proto.Annotation.Name) } ::std::string* Annotation::mutable_name() { // @@protoc_insertion_point(field_mutable:atom.proto.Annotation.Name) return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } ::std::string* Annotation::release_name() { return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Annotation::set_allocated_name(::std::string* name) { if (name != NULL) { } else { } name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name); // @@protoc_insertion_point(field_set_allocated:atom.proto.Annotation.Name) } // optional string Text = 2; void Annotation::clear_text() { text_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } const ::std::string& Annotation::text() const { // @@protoc_insertion_point(field_get:atom.proto.Annotation.Text) return text_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Annotation::set_text(const ::std::string& value) { text_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:atom.proto.Annotation.Text) } void Annotation::set_text(const char* value) { text_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:atom.proto.Annotation.Text) } void Annotation::set_text(const char* value, size_t size) { text_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:atom.proto.Annotation.Text) } ::std::string* Annotation::mutable_text() { // @@protoc_insertion_point(field_mutable:atom.proto.Annotation.Text) return text_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } ::std::string* Annotation::release_text() { return text_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Annotation::set_allocated_text(::std::string* text) { if (text != NULL) { } else { } text_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), text); // @@protoc_insertion_point(field_set_allocated:atom.proto.Annotation.Text) } // optional .atom.proto.Matrix World = 3; bool Annotation::has_world() const { return !_is_default_instance_ && world_ != NULL; } void Annotation::clear_world() { if (GetArenaNoVirtual() == NULL && world_ != NULL) delete world_; world_ = NULL; } const ::atom::proto::Matrix& Annotation::world() const { // @@protoc_insertion_point(field_get:atom.proto.Annotation.World) return world_ != NULL ? *world_ : *default_instance_->world_; } ::atom::proto::Matrix* Annotation::mutable_world() { if (world_ == NULL) { world_ = new ::atom::proto::Matrix; } // @@protoc_insertion_point(field_mutable:atom.proto.Annotation.World) return world_; } ::atom::proto::Matrix* Annotation::release_world() { ::atom::proto::Matrix* temp = world_; world_ = NULL; return temp; } void Annotation::set_allocated_world(::atom::proto::Matrix* world) { delete world_; world_ = world; if (world) { } else { } // @@protoc_insertion_point(field_set_allocated:atom.proto.Annotation.World) } // optional bool InitialVisibility = 4; void Annotation::clear_initialvisibility() { initialvisibility_ = false; } bool Annotation::initialvisibility() const { // @@protoc_insertion_point(field_get:atom.proto.Annotation.InitialVisibility) return initialvisibility_; } void Annotation::set_initialvisibility(bool value) { initialvisibility_ = value; // @@protoc_insertion_point(field_set:atom.proto.Annotation.InitialVisibility) } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // @@protoc_insertion_point(namespace_scope) } // namespace proto } // namespace atom // @@protoc_insertion_point(global_scope)